diff --git a/bom/pom.xml b/bom/pom.xml index 165f191e91c..eb75ce9afa0 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -309,11 +309,6 @@ rdf4j-common-transaction ${project.version} - - org.eclipse.rdf4j - rdf4j-common-util - ${project.version} - org.eclipse.rdf4j rdf4j-common-xml diff --git a/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchIndexTest.java b/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchIndexTest.java index 75c47e613e0..0a279ae7dc1 100644 --- a/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchIndexTest.java +++ b/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchIndexTest.java @@ -17,11 +17,9 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.Set; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; -import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; @@ -307,9 +305,7 @@ public void testAddMultiple() throws Exception { assertStatement(statement22, document); // check if the text field stores all added string values - Set texts = new HashSet<>(); - texts.add("cats"); - texts.add("dogs"); + HashSet texts = new HashSet<>(List.of("cats", "dogs")); // FIXME // assertTexts(texts, document); @@ -377,7 +373,7 @@ public void testContexts() throws Exception { // delete context 1 connection.begin(); - connection.clear(new Resource[] { CONTEXT_1 }); + connection.clear(CONTEXT_1); connection.commit(); assertNoStatement(statementContext111); assertNoStatement(statementContext121); @@ -428,7 +424,7 @@ public void testContextsRemoveContext2() throws Exception { // delete context 2 connection.begin(); - connection.clear(new Resource[] { CONTEXT_2 }); + connection.clear(CONTEXT_2); connection.commit(); assertStatement(statementContext111); assertStatement(statementContext121); @@ -449,10 +445,10 @@ public void testRejectedDatatypes() { Literal literal2 = vf.createLiteral("hi there, too", STRING); Literal literal3 = vf.createLiteral("1.0"); Literal literal4 = vf.createLiteral("1.0", FLOAT); - assertEquals("Is the first literal accepted?", true, index.accept(literal1)); - assertEquals("Is the second literal accepted?", true, index.accept(literal2)); - assertEquals("Is the third literal accepted?", true, index.accept(literal3)); - assertEquals("Is the fourth literal accepted?", false, index.accept(literal4)); + assertTrue("Is the first literal accepted?", index.accept(literal1)); + assertTrue("Is the second literal accepted?", index.accept(literal2)); + assertTrue("Is the third literal accepted?", index.accept(literal3)); + assertFalse("Is the fourth literal accepted?", index.accept(literal4)); } private void assertStatement(Statement statement) throws Exception { @@ -471,10 +467,6 @@ private void assertNoStatement(Statement statement) throws Exception { assertNoStatement(statement, document); } - /** - * @param statement112 - * @param document - */ private void assertStatement(Statement statement, SearchDocument document) { List fields = document.getProperty(SearchFields.getPropertyField(statement.getPredicate())); assertNotNull("field " + statement.getPredicate() + " not found in document " + document, fields); @@ -486,10 +478,6 @@ private void assertStatement(Statement statement, SearchDocument document) { fail("Statement not found in document " + statement); } - /** - * @param statement112 - * @param document - */ private void assertNoStatement(Statement statement, SearchDocument document) { List fields = document.getProperty(SearchFields.getPropertyField(statement.getPredicate())); if (fields == null) { diff --git a/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailGeoSPARQLTest.java b/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailGeoSPARQLTest.java index d865d2cc953..27cbcb6fb55 100644 --- a/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailGeoSPARQLTest.java +++ b/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailGeoSPARQLTest.java @@ -75,7 +75,7 @@ public void tearDown() throws Exception { } @Test - public void testTriplesStored() throws Exception { + public void testTriplesStored() { delegateTest.testTriplesStored(); } diff --git a/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailIndexedPropertiesTest.java b/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailIndexedPropertiesTest.java index b183a7a057e..686760b42f4 100644 --- a/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailIndexedPropertiesTest.java +++ b/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailIndexedPropertiesTest.java @@ -74,7 +74,7 @@ public void tearDown() throws Exception { } @Test - public void testTriplesStored() throws Exception { + public void testTriplesStored() { delegateTest.testTriplesStored(); } diff --git a/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailTest.java b/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailTest.java index d1dd51065c9..d436d6ab955 100644 --- a/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailTest.java +++ b/compliance/elasticsearch/src/test/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchSailTest.java @@ -74,7 +74,7 @@ public void tearDown() throws Exception { } @Test - public void testTriplesStored() throws Exception { + public void testTriplesStored() { delegateTest.testTriplesStored(); } @@ -133,17 +133,17 @@ public void testUnionQuery() throws RepositoryException, MalformedQueryException } @Test - public void testContextHandling() throws Exception { + public void testContextHandling() { delegateTest.testContextHandling(); } @Test - public void testConcurrentReadingAndWriting() throws Exception { + public void testConcurrentReadingAndWriting() { delegateTest.testConcurrentReadingAndWriting(); } @Test - public void testNullContextHandling() throws Exception { + public void testNullContextHandling() { delegateTest.testNullContextHandling(); } @@ -153,7 +153,7 @@ public void testFuzzyQuery() throws MalformedQueryException, RepositoryException } @Test - public void testReindexing() throws Exception { + public void testReindexing() { delegateTest.testReindexing(); } diff --git a/compliance/elasticsearch/src/test/java/org/elasticsearch/bootstrap/JarHell.java b/compliance/elasticsearch/src/test/java/org/elasticsearch/bootstrap/JarHell.java index 3aae44f99fe..96bd031b72f 100644 --- a/compliance/elasticsearch/src/test/java/org/elasticsearch/bootstrap/JarHell.java +++ b/compliance/elasticsearch/src/test/java/org/elasticsearch/bootstrap/JarHell.java @@ -24,10 +24,10 @@ public class JarHell { private JarHell() { } - public static void checkJarHell() throws Exception { + public static void checkJarHell() { } - public static void checkJarHell(URL urls[]) throws Exception { + public static void checkJarHell(URL urls[]) { } public static void checkVersionFormat(String targetVersion) { diff --git a/compliance/geosparql/src/test/java/org/eclipse/rdf4j/query/algebra/geosparql/MemoryGeoSPARQLQueryTest.java b/compliance/geosparql/src/test/java/org/eclipse/rdf4j/query/algebra/geosparql/MemoryGeoSPARQLQueryTest.java index 3c359fb7946..fc351f8358d 100644 --- a/compliance/geosparql/src/test/java/org/eclipse/rdf4j/query/algebra/geosparql/MemoryGeoSPARQLQueryTest.java +++ b/compliance/geosparql/src/test/java/org/eclipse/rdf4j/query/algebra/geosparql/MemoryGeoSPARQLQueryTest.java @@ -24,7 +24,7 @@ public MemoryGeoSPARQLQueryTest(String displayName, String testURI, String name, } @Override - protected Repository newRepository() throws Exception { + protected Repository newRepository() { return new SailRepository(new MemoryStore()); } } diff --git a/compliance/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneSailTest.java b/compliance/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneSailTest.java index 295fa4e3ce4..9f93f91cb1b 100644 --- a/compliance/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneSailTest.java +++ b/compliance/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneSailTest.java @@ -12,7 +12,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; import java.util.Collections; import java.util.List; @@ -36,13 +35,13 @@ public class LuceneSailTest extends AbstractLuceneSailTest { * LuceneSail) */ @Override - protected void configure(LuceneSail sail) throws IOException { + protected void configure(LuceneSail sail) { sail.setParameter(LuceneSail.INDEX_CLASS_KEY, LuceneIndex.class.getName()); sail.setParameter(LuceneSail.LUCENE_RAMDIR_KEY, "true"); } @Test - public void testReindexing_SingleResource() throws Exception { + public void testReindexing_SingleResource() { // wipe the Lucene index to allow specific test data try (RepositoryConnection connection = repository.getConnection()) { diff --git a/compliance/model/src/test/java/org/eclipse/rdf4j/model/util/IsomorphicTest.java b/compliance/model/src/test/java/org/eclipse/rdf4j/model/util/IsomorphicTest.java index b74595bbe0c..abb13e98fe4 100644 --- a/compliance/model/src/test/java/org/eclipse/rdf4j/model/util/IsomorphicTest.java +++ b/compliance/model/src/test/java/org/eclipse/rdf4j/model/util/IsomorphicTest.java @@ -182,7 +182,7 @@ public void bsbmNotIsomorphic() { } @Test - public void testValidationReport() throws IOException { + public void testValidationReport() { Model m1 = getModel("shaclValidationReport.ttl"); Model m2 = getModel("shaclValidationReport.ttl"); @@ -191,7 +191,7 @@ public void testValidationReport() throws IOException { @Test @Timeout(2) - public void testValidationReport_LexicalOrdering() throws IOException { + public void testValidationReport_LexicalOrdering() { Model m1 = getModel("shaclValidationReport.ttl"); Model m2 = getModel("shaclValidationReport.ttl"); @@ -205,7 +205,7 @@ public void testValidationReport_LexicalOrdering() throws IOException { } @Test - public void testValidationReport_Changed() throws IOException { + public void testValidationReport_Changed() { Model m1 = getModel("shaclValidationReport.ttl"); Model m2 = getModel("shaclValidationReport-changed.ttl"); diff --git a/compliance/pom.xml b/compliance/pom.xml index 9d36c436e3d..f1f901ce146 100644 --- a/compliance/pom.xml +++ b/compliance/pom.xml @@ -173,6 +173,13 @@ + + com.github.siom79.japicmp + japicmp-maven-plugin + + true + + diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/HTTPRepositoryTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/HTTPRepositoryTest.java index 3214a789d36..a29b6d0cab4 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/HTTPRepositoryTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/HTTPRepositoryTest.java @@ -59,7 +59,7 @@ protected Repository createRepository() { @Test @Timeout(value = 10) - public void testSubqueryDeadlock() throws Exception { + public void testSubqueryDeadlock() { String mainQueryStr = "SELECT ?property WHERE { ?property a rdf:Property . }"; String subQueryStr = "SELECT ?range WHERE { ?property rdfs:range ?range . }"; diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/HTTPStoreConnectionTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/HTTPStoreConnectionTest.java index 3f946758ef2..9728d94387a 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/HTTPStoreConnectionTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/HTTPStoreConnectionTest.java @@ -73,7 +73,7 @@ public void testContextInTransactionAdd(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testUpdateExecution(IsolationLevel level) throws Exception { + public void testUpdateExecution(IsolationLevel level) { setupTest(level); IRI foobar = vf.createIRI("foo:bar"); @@ -116,7 +116,7 @@ public void testAddMalformedLiteralsDefaultConfig(IsolationLevel level) throws E @MethodSource("parameters") @Override @Disabled("See SES-1833") - public void testAddMalformedLiteralsStrictConfig(IsolationLevel level) throws Exception { + public void testAddMalformedLiteralsStrictConfig(IsolationLevel level) { System.err.println("SES-1833: temporarily disabled testAddMalformedLiteralsStrictConfig() for HTTPRepository"); } diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/RDFSchemaHTTPRepositoryConnectionTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/RDFSchemaHTTPRepositoryConnectionTest.java index b1783d81709..dc3891ca895 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/RDFSchemaHTTPRepositoryConnectionTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/http/RDFSchemaHTTPRepositoryConnectionTest.java @@ -56,7 +56,7 @@ protected Repository createRepository(File dataDir) { @ParameterizedTest @MethodSource("parameters") @Override - public void testTransactionIsolation(IsolationLevel level) throws Exception { + public void testTransactionIsolation(IsolationLevel level) { System.err.println("temporarily disabled testTransactionIsolation() for HTTPRepository"); } @@ -64,7 +64,7 @@ public void testTransactionIsolation(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testAutoCommit(IsolationLevel level) throws Exception { + public void testAutoCommit(IsolationLevel level) { System.err.println("temporarily disabled testAutoCommit() for HTTPRepository"); } @@ -72,7 +72,7 @@ public void testAutoCommit(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testRollback(IsolationLevel level) throws Exception { + public void testRollback(IsolationLevel level) { System.err.println("temporarily disabled testRollback() for HTTPRepository"); } @@ -80,7 +80,7 @@ public void testRollback(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testEmptyCommit(IsolationLevel level) throws Exception { + public void testEmptyCommit(IsolationLevel level) { System.err.println("temporarily disabled testEmptyCommit() for HTTPRepository"); } @@ -88,7 +88,7 @@ public void testEmptyCommit(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testEmptyRollback(IsolationLevel level) throws Exception { + public void testEmptyRollback(IsolationLevel level) { System.err.println("temporarily disabled testEmptyRollback() for HTTPRepository"); } @@ -96,7 +96,7 @@ public void testEmptyRollback(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testSizeCommit(IsolationLevel level) throws Exception { + public void testSizeCommit(IsolationLevel level) { System.err.println("temporarily disabled testSizeCommit() for HTTPRepository"); } @@ -104,7 +104,7 @@ public void testSizeCommit(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testSizeRollback(IsolationLevel level) throws Exception { + public void testSizeRollback(IsolationLevel level) { System.err.println("temporarily disabled testSizeRollback() for HTTPRepository"); } @@ -112,7 +112,7 @@ public void testSizeRollback(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testGetContextIDs(IsolationLevel level) throws Exception { + public void testGetContextIDs(IsolationLevel level) { System.err.println("temporarily disabled testGetContextIDs() for HTTPRepository"); } @@ -120,7 +120,7 @@ public void testGetContextIDs(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testInferencerQueryDuringTransaction(IsolationLevel level) throws Exception { + public void testInferencerQueryDuringTransaction(IsolationLevel level) { System.err.println("temporarily disabled testInferencerDuringTransaction() for HTTPRepository"); } @@ -128,7 +128,7 @@ public void testInferencerQueryDuringTransaction(IsolationLevel level) throws Ex @ParameterizedTest @MethodSource("parameters") @Override - public void testInferencerTransactionIsolation(IsolationLevel level) throws Exception { + public void testInferencerTransactionIsolation(IsolationLevel level) { System.err.println("temporarily disabled testInferencerTransactionIsolation() for HTTPRepository"); } @@ -150,7 +150,7 @@ public void testAddMalformedLiteralsDefaultConfig(IsolationLevel level) throws E @ParameterizedTest @MethodSource("parameters") @Disabled - public void testQueryDefaultGraph(IsolationLevel level) throws Exception { + public void testQueryDefaultGraph(IsolationLevel level) { // ignore - schema caching inferencer uses different context handling } @@ -158,7 +158,7 @@ public void testQueryDefaultGraph(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Disabled - public void testDeleteDefaultGraph(IsolationLevel level) throws Exception { + public void testDeleteDefaultGraph(IsolationLevel level) { // ignore - schema caching inferencer uses different context handling } @@ -166,7 +166,7 @@ public void testDeleteDefaultGraph(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Disabled - public void testContextStatementsNotDuplicated(IsolationLevel level) throws Exception { + public void testContextStatementsNotDuplicated(IsolationLevel level) { // ignore - schema caching inferencer uses different context handling } @@ -174,7 +174,7 @@ public void testContextStatementsNotDuplicated(IsolationLevel level) throws Exce @ParameterizedTest @MethodSource("parameters") @Disabled - public void testContextStatementsNotDuplicated2(IsolationLevel level) throws Exception { + public void testContextStatementsNotDuplicated2(IsolationLevel level) { // ignore - schema caching inferencer uses different context handling } @@ -182,7 +182,7 @@ public void testContextStatementsNotDuplicated2(IsolationLevel level) throws Exc @MethodSource("parameters") @Override @Disabled("See SES-1833") - public void testAddMalformedLiteralsStrictConfig(IsolationLevel level) throws Exception { + public void testAddMalformedLiteralsStrictConfig(IsolationLevel level) { System.err.println("SES-1833: temporarily disabled testAddMalformedLiteralsStrictConfig() for HTTPRepository"); } diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManagerIntegrationTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManagerIntegrationTest.java index 08659ddceff..63822645f3b 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManagerIntegrationTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManagerIntegrationTest.java @@ -11,17 +11,17 @@ package org.eclipse.rdf4j.repository.manager; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.fail; import java.io.File; -import java.io.IOException; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.InputStream; import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.util.Configurations; +import org.eclipse.rdf4j.model.vocabulary.CONFIG; import org.eclipse.rdf4j.model.vocabulary.OWL; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.repository.Repository; @@ -56,11 +56,10 @@ public class LocalRepositoryManagerIntegrationTest extends RepositoryManagerInte private static final String PROXY_ID = "proxy"; /** - * @throws java.lang.Exception */ @BeforeEach @Override - public void setUp() throws Exception { + public void setUp() { subject = new LocalRepositoryManager(datadir); subject.init(); @@ -74,10 +73,9 @@ public void setUp() throws Exception { } /** - * @throws IOException if a problem occurs deleting temporary resources */ @AfterEach - public void tearDown() throws IOException { + public void tearDown() { subject.shutDown(); } @@ -90,22 +88,22 @@ public void tearDown() throws IOException { @Test public void testGetRepository() throws RepositoryConfigException, RepositoryException { Repository rep = subject.getRepository(TEST_REPO); - assertNotNull("Expected repository to exist.", rep); - assertTrue("Expected repository to be initialized.", rep.isInitialized()); + assertThat(rep).isNotNull(); + assertThat(rep.isInitialized()).isTrue(); rep.shutDown(); rep = subject.getRepository(TEST_REPO); - assertNotNull("Expected repository to exist.", rep); - assertTrue("Expected repository to be initialized.", rep.isInitialized()); + assertThat(rep).isNotNull(); + assertThat(rep.isInitialized()).isTrue(); } @Test - public void testRestartManagerWithoutTransaction() throws Exception { + public void testRestartManagerWithoutTransaction() { Repository rep = subject.getRepository(TEST_REPO); - assertNotNull("Expected repository to exist.", rep); - assertTrue("Expected repository to be initialized.", rep.isInitialized()); + assertThat(rep).isNotNull(); + assertThat(rep.isInitialized()).isTrue(); try (RepositoryConnection conn = rep.getConnection()) { conn.add(conn.getValueFactory().createIRI("urn:sesame:test:subject"), RDF.TYPE, OWL.ONTOLOGY); - assertEquals(1, conn.size()); + assertThat(conn.size()).isEqualTo(1); } finally { rep.shutDown(); subject.shutDown(); @@ -114,10 +112,10 @@ public void testRestartManagerWithoutTransaction() throws Exception { subject = new LocalRepositoryManager(datadir); subject.init(); Repository rep2 = subject.getRepository(TEST_REPO); - assertNotNull("Expected repository to exist.", rep2); - assertTrue("Expected repository to be initialized.", rep2.isInitialized()); + assertThat(rep2).isNotNull(); + assertThat(rep2.isInitialized()).isTrue(); try (RepositoryConnection conn2 = rep2.getConnection()) { - assertEquals(1, conn2.size()); + assertThat(conn2.size()).isEqualTo(1); } finally { rep2.shutDown(); subject.shutDown(); @@ -126,15 +124,15 @@ public void testRestartManagerWithoutTransaction() throws Exception { } @Test - public void testRestartManagerWithTransaction() throws Exception { + public void testRestartManagerWithTransaction() { Repository rep = subject.getRepository(TEST_REPO); - assertNotNull("Expected repository to exist.", rep); - assertTrue("Expected repository to be initialized.", rep.isInitialized()); + assertThat(rep).isNotNull(); + assertThat(rep.isInitialized()).isTrue(); try (RepositoryConnection conn = rep.getConnection()) { conn.begin(); conn.add(conn.getValueFactory().createIRI("urn:sesame:test:subject"), RDF.TYPE, OWL.ONTOLOGY); conn.commit(); - assertEquals(1, conn.size()); + assertThat(conn.size()).isEqualTo(1); } finally { rep.shutDown(); subject.shutDown(); @@ -143,10 +141,10 @@ public void testRestartManagerWithTransaction() throws Exception { subject = new LocalRepositoryManager(datadir); subject.init(); Repository rep2 = subject.getRepository(TEST_REPO); - assertNotNull("Expected repository to exist.", rep2); - assertTrue("Expected repository to be initialized.", rep2.isInitialized()); + assertThat(rep2).isNotNull(); + assertThat(rep2.isInitialized()).isTrue(); try (RepositoryConnection conn2 = rep2.getConnection()) { - assertEquals(1, conn2.size()); + assertThat(conn2.size()).isEqualTo(1); } finally { rep2.shutDown(); subject.shutDown(); @@ -185,12 +183,60 @@ public void testAddWithExistingSysRepository() { } } + @Test + public void testGetRepositoryConfig_Legacy() throws Exception { + // set up legacy configuration + new File(datadir, "repositories/legacy").mkdir(); + InputStream in = getClass().getResourceAsStream("/fixtures/memory-legacy.ttl"); + Model model = Rio.parse(in, RDFFormat.TURTLE); + Rio.write(model, new FileOutputStream(new File(datadir, "repositories/legacy/config.ttl")), + RDFFormat.TURTLE); + + RepositoryConfig config = subject.getRepositoryConfig("legacy"); + assertThat(config).isNotNull(); + assertThat(config.getTitle()).isEqualTo("Legacy Test Repository"); + + // verify manager has converted the config file. + File convertedConfig = new File(datadir, "repositories/legacy/config.ttl"); + + Model convertedModel = Rio.parse(new FileInputStream(convertedConfig), convertedConfig.toURI().toString(), + RDFFormat.TURTLE); + assertThat(convertedModel.getNamespaces()).contains(CONFIG.NS); + assertThat(Configurations.hasLegacyConfiguration(convertedModel)).isFalse(); + } + + @Test + public void testGetRepositoryConfig_Legacy_useLegacy() throws Exception { + // set up legacy configuration + new File(datadir, "repositories/legacy").mkdir(); + InputStream in = getClass().getResourceAsStream("/fixtures/memory-legacy.ttl"); + Model model = Rio.parse(in, RDFFormat.TURTLE); + Rio.write(model, new FileOutputStream(new File(datadir, "repositories/legacy/config.ttl")), + RDFFormat.TURTLE); + + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + RepositoryConfig config = subject.getRepositoryConfig("legacy"); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + + assertThat(config).isNotNull(); + assertThat(config.getTitle()).isEqualTo("Legacy Test Repository"); + + // verify manager has NOT converted the config file. + File convertedConfig = new File(datadir, "repositories/legacy/config.ttl"); + + Model convertedModel = Rio.parse(new FileInputStream(convertedConfig), convertedConfig.toURI().toString(), + RDFFormat.TURTLE); + assertThat(convertedModel.getNamespaces()).doesNotContain(CONFIG.NS); + assertThat(Configurations.hasLegacyConfiguration(convertedModel)).isTrue(); + } + @Test public void testAddConfig_validation() throws Exception { InputStream in = getClass().getResourceAsStream("/fixtures/memory-invalid.ttl"); Model model = Rio.parse(in, RDFFormat.TURTLE); - assertThrows(RepositoryConfigException.class, () -> RepositoryConfigUtil.getRepositoryConfig(model, "Test")); + assertThatExceptionOfType(RepositoryConfigException.class) + .isThrownBy(() -> RepositoryConfigUtil.getRepositoryConfig(model, "Test")); } } diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/manager/RepositoryManagerIntegrationTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/manager/RepositoryManagerIntegrationTest.java index d9e60313300..1c1fc756d16 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/manager/RepositoryManagerIntegrationTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/manager/RepositoryManagerIntegrationTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.repository.manager; -import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; @@ -26,7 +25,7 @@ public class RepositoryManagerIntegrationTest { protected RepositoryManager subject; @BeforeEach - public void setUp() throws Exception { + public void setUp() { subject = new RepositoryManager() { @Override @@ -36,7 +35,7 @@ public void setHttpClient(HttpClient httpClient) { } @Override - public URL getLocation() throws MalformedURLException { + public URL getLocation() { return null; } diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLGraphQueryResultTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLGraphQueryResultTest.java index 7c282077a1c..ce00e457a9b 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLGraphQueryResultTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLGraphQueryResultTest.java @@ -42,7 +42,7 @@ public static void stopServer() throws Exception { } @Override - protected Repository newRepository() throws Exception { + protected Repository newRepository() { return new SPARQLRepository(HTTPMemServer.REPOSITORY_URL, Protocol.getStatementsLocation(HTTPMemServer.REPOSITORY_URL)); diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLRepositoryTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLRepositoryTest.java index edae8e4ad5d..4e4140920ef 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLRepositoryTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLRepositoryTest.java @@ -56,7 +56,7 @@ public static void stopServer() throws Exception { } @Override - protected Repository createRepository() throws Exception { + protected Repository createRepository() { return new SPARQLRepository(HTTPMemServer.REPOSITORY_URL, Protocol.getStatementsLocation(HTTPMemServer.REPOSITORY_URL)); diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLStoreConnectionTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLStoreConnectionTest.java index 4dd72cc17a9..d23d25184f7 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLStoreConnectionTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLStoreConnectionTest.java @@ -86,7 +86,7 @@ protected Repository createRepository(File dataDir) { @MethodSource("parameters") @Override @Disabled - public void testDuplicateFilter(IsolationLevel level) throws Exception { + public void testDuplicateFilter(IsolationLevel level) { System.err.println("temporarily disabled testDuplicateFilter() for SPARQLRepository"); } @@ -110,7 +110,7 @@ public void testAddRemoveInsert(IsolationLevel level) throws RDF4JException { @MethodSource("parameters") @Override @Disabled("relies on pending updates being visible in own connection") - public void testSizeRollback(IsolationLevel level) throws Exception { + public void testSizeRollback(IsolationLevel level) { System.err.println("temporarily disabled testSizeRollback() for SPARQLRepository"); } @@ -118,7 +118,7 @@ public void testSizeRollback(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled("relies on pending updates being visible in own connection") - public void testAutoCommit(IsolationLevel level) throws Exception { + public void testAutoCommit(IsolationLevel level) { System.err.println("temporarily disabled testAutoCommit() for SPARQLRepository"); } @@ -126,7 +126,7 @@ public void testAutoCommit(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled("relies on pending updates being visible in own connection") - public void testRollback(IsolationLevel level) throws Exception { + public void testRollback(IsolationLevel level) { System.err.println("temporarily disabled testRollback() for SPARQLRepository"); } @@ -134,7 +134,7 @@ public void testRollback(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled("relies on pending updates being visible in own connection") - public void testEmptyRollback(IsolationLevel level) throws Exception { + public void testEmptyRollback(IsolationLevel level) { System.err.println("temporarily disabled testEmptyRollback() for SPARQLRepository"); } @@ -142,7 +142,7 @@ public void testEmptyRollback(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled("relies on pending updates being visible in own connection") - public void testEmptyCommit(IsolationLevel level) throws Exception { + public void testEmptyCommit(IsolationLevel level) { System.err.println("temporarily disabled testEmptyCommit() for SPARQLRepository"); } @@ -150,7 +150,7 @@ public void testEmptyCommit(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled - public void testSizeCommit(IsolationLevel level) throws Exception { + public void testSizeCommit(IsolationLevel level) { System.err.println("temporarily disabled testSizeCommit() for SPARQLRepository"); } @@ -158,7 +158,7 @@ public void testSizeCommit(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled - public void testGetStatementsInMultipleContexts(IsolationLevel level) throws Exception { + public void testGetStatementsInMultipleContexts(IsolationLevel level) { System.err.println( "temporarily disabled testGetStatementsInMultipleContexts() for SPARQLRepository: implementation of statement context using SPARQL not yet complete"); // TODO see SES-1776 @@ -214,7 +214,7 @@ private void enableQuadModeOnConnection(SPARQLConnection con) throws Exception { @MethodSource("parameters") @Override @Disabled - public void testGetStatementsInSingleContext(IsolationLevel level) throws Exception { + public void testGetStatementsInSingleContext(IsolationLevel level) { System.err.println( "temporarily disabled testGetStatementsInSingleContext() for SPARQLRepository: implementation of statement context using SPARQL not yet complete"); // TODO see SES-1776 @@ -224,14 +224,14 @@ public void testGetStatementsInSingleContext(IsolationLevel level) throws Except @MethodSource("parameters") @Override @Disabled("can not execute test because required data add results in illegal SPARQL syntax") - public void testGetStatementsMalformedLanguageLiteral(IsolationLevel level) throws Exception { + public void testGetStatementsMalformedLanguageLiteral(IsolationLevel level) { System.err.println("temporarily disabled testGetStatementsMalformedLanguageLiteral() for SPARQLRepository"); } @ParameterizedTest @MethodSource("parameters") @Override - public void testPreparedTupleQuery(IsolationLevel level) throws Exception { + public void testPreparedTupleQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -273,7 +273,7 @@ public void testPreparedTupleQuery(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled - public void testGetNamespaces(IsolationLevel level) throws Exception { + public void testGetNamespaces(IsolationLevel level) { System.err.println("disabled testGetNamespaces() as namespace retrieval is not supported by SPARQL"); } @@ -281,7 +281,7 @@ public void testGetNamespaces(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled - public void testGetNamespace(IsolationLevel level) throws Exception { + public void testGetNamespace(IsolationLevel level) { System.err.println("disabled testGetNamespace() as namespace retrieval is not supported by SPARQL"); } @@ -289,7 +289,7 @@ public void testGetNamespace(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled - public void testImportNamespacesFromIterable(IsolationLevel level) throws Exception { + public void testImportNamespacesFromIterable(IsolationLevel level) { System.err .println("disabled testImportNamespacesFromIterable() as namespace setting is not supported by SPARQL"); } @@ -298,14 +298,14 @@ public void testImportNamespacesFromIterable(IsolationLevel level) throws Except @MethodSource("parameters") @Override @Disabled - public void testTransactionIsolation(IsolationLevel level) throws Exception { + public void testTransactionIsolation(IsolationLevel level) { System.err.println("temporarily disabled testTransactionIsolation() for SPARQLRepository"); } @ParameterizedTest @MethodSource("parameters") @Override - public void testPreparedTupleQueryUnicode(IsolationLevel level) throws Exception { + public void testPreparedTupleQueryUnicode(IsolationLevel level) { setupTest(level); testCon.add(alexander, name, Александър); @@ -333,7 +333,7 @@ public void testPreparedTupleQueryUnicode(IsolationLevel level) throws Exception @ParameterizedTest @MethodSource("parameters") @Override - public void testSimpleGraphQuery(IsolationLevel level) throws Exception { + public void testSimpleGraphQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -370,7 +370,7 @@ public void testSimpleGraphQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testPreparedGraphQuery(IsolationLevel level) throws Exception { + public void testPreparedGraphQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -412,7 +412,7 @@ public void testPreparedGraphQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testSimpleTupleQuery(IsolationLevel level) throws Exception { + public void testSimpleTupleQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -451,7 +451,7 @@ public void testSimpleTupleQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Override - public void testSimpleTupleQueryUnicode(IsolationLevel level) throws Exception { + public void testSimpleTupleQueryUnicode(IsolationLevel level) { setupTest(level); testCon.add(alexander, name, Александър); @@ -478,13 +478,13 @@ public void testSimpleTupleQueryUnicode(IsolationLevel level) throws Exception { @MethodSource("parameters") @Override @Disabled - public void testBNodeSerialization(IsolationLevel level) throws Exception { + public void testBNodeSerialization(IsolationLevel level) { System.err.println("temporarily disabled testBNodeSerialization() for SPARQLRepository"); } @ParameterizedTest @MethodSource("parameters") - public void testUpdateExecution(IsolationLevel level) throws Exception { + public void testUpdateExecution(IsolationLevel level) { setupTest(level); IRI foobar = vf.createIRI("foo:bar"); diff --git a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedServiceIntegrationTest.java b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedServiceIntegrationTest.java index 9e2bf2e1b1e..763d3c2a6d2 100644 --- a/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedServiceIntegrationTest.java +++ b/compliance/repository/src/test/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedServiceIntegrationTest.java @@ -82,7 +82,7 @@ public void after() { } @Test - public void test() throws Exception { + public void test() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")))); @@ -92,7 +92,7 @@ public void test() throws Exception { } @Test - public void test2() throws Exception { + public void test2() { addData(serviceRepo, Lists.newArrayList( vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")), @@ -105,7 +105,7 @@ public void test2() throws Exception { } @Test - public void test3() throws Exception { + public void test3() { addData(serviceRepo, Lists.newArrayList( vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")), @@ -118,7 +118,7 @@ public void test3() throws Exception { } @Test - public void test3a() throws Exception { + public void test3a() { addData(serviceRepo, Lists.newArrayList( vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")), @@ -133,7 +133,7 @@ public void test3a() throws Exception { } @Test - public void test4() throws Exception { + public void test4() { addData(serviceRepo, Lists.newArrayList( vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")), @@ -146,7 +146,7 @@ public void test4() throws Exception { } @Test - public void test4a() throws Exception { + public void test4a() { addData(serviceRepo, Lists.newArrayList( vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")), @@ -160,7 +160,7 @@ public void test4a() throws Exception { } @Test - public void test4b() throws Exception { + public void test4b() { addData(serviceRepo, Lists.newArrayList( vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")), @@ -173,7 +173,7 @@ public void test4b() throws Exception { } @Test - public void test5() throws Exception { + public void test5() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")))); @@ -185,7 +185,7 @@ public void test5() throws Exception { } @Test - public void test5a() throws Exception { + public void test5a() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")))); addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s2"), RDFS.LABEL, l("val2")))); @@ -199,7 +199,7 @@ public void test5a() throws Exception { } @Test - public void test5b() throws Exception { + public void test5b() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")))); addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s2"), RDFS.LABEL, l("val2")))); @@ -212,7 +212,7 @@ public void test5b() throws Exception { } @Test - public void test6() throws Exception { + public void test6() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")))); addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s2"), RDFS.LABEL, l("val2")))); @@ -228,7 +228,7 @@ public void test6() throws Exception { } @Test - public void test6b() throws Exception { + public void test6b() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")))); addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s2"), RDFS.LABEL, l("val2")))); @@ -244,7 +244,7 @@ public void test6b() throws Exception { } @Test - public void test7_CrossProduct() throws Exception { + public void test7_CrossProduct() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("serviceVal")))); @@ -256,7 +256,7 @@ public void test7_CrossProduct() throws Exception { } @Test - public void test8_subSelectAll() throws Exception { + public void test8_subSelectAll() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")))); @@ -266,7 +266,7 @@ public void test8_subSelectAll() throws Exception { } @Test - public void test8a_subSelectAll() throws Exception { + public void test8a_subSelectAll() { addData(serviceRepo, Lists.newArrayList(vf.createStatement(iri("s1"), RDFS.LABEL, l("val1")))); @@ -313,7 +313,7 @@ public void test9_connectionHandling() throws Exception { } @Test - public void test10_consumePartially() throws Exception { + public void test10_consumePartially() { /* * The purpose of this test is validate that connections are closed properly, even if a result is consume only diff --git a/compliance/repository/src/test/resources/fixtures/memory-legacy.ttl b/compliance/repository/src/test/resources/fixtures/memory-legacy.ttl new file mode 100644 index 00000000000..a4d10cfb50a --- /dev/null +++ b/compliance/repository/src/test/resources/fixtures/memory-legacy.ttl @@ -0,0 +1,23 @@ +# +# 'Test' main-memory repository config - legacy configuration +# +@prefix rdfs: . +@prefix rep: . +@prefix sr: . +@prefix sail: . +@prefix ms: . +@prefix sb: . + +[] a rep:Repository ; + rep:repositoryID "legacy" ; + rdfs:label "Legacy Test Repository" ; + rep:repositoryImpl [ + rep:repositoryType "openrdf:SailRepository" ; + sr:sailImpl [ + sail:sailType "openrdf:MemoryStore" ; + sail:iterationCacheSyncThreshold "1000"; + ms:persist false ; + ms:syncDelay 0 ; + sb:evaluationStrategyFactory "org.eclipse.rdf4j.query.algebra.evaluation.impl.StrictEvaluationStrategyFactory" + ] + ]. diff --git a/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrIndexTest.java b/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrIndexTest.java index 40c7e3a71de..af57bfb2784 100644 --- a/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrIndexTest.java +++ b/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrIndexTest.java @@ -105,7 +105,7 @@ public static void setUpClass() throws Exception { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { System.setProperty("solr.solr.home", toRestoreSolrHome == null ? "" : toRestoreSolrHome); toRestoreSolrHome = null; } diff --git a/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailGeoSPARQLTest.java b/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailGeoSPARQLTest.java index 2189f12bfff..c85ebf15edd 100644 --- a/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailGeoSPARQLTest.java +++ b/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailGeoSPARQLTest.java @@ -39,7 +39,7 @@ public static void setUpClass() throws Exception { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { System.setProperty("solr.solr.home", toRestoreSolrHome == null ? "" : toRestoreSolrHome); toRestoreSolrHome = null; } diff --git a/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailIndexedPropertiesTest.java b/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailIndexedPropertiesTest.java index 65c37e0a7d1..6c3cf54c00c 100644 --- a/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailIndexedPropertiesTest.java +++ b/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailIndexedPropertiesTest.java @@ -36,7 +36,7 @@ public static void setUpClass() throws Exception { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { System.setProperty("solr.solr.home", toRestoreSolrHome == null ? "" : toRestoreSolrHome); toRestoreSolrHome = null; } diff --git a/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailTest.java b/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailTest.java index 2f286c68434..f6c95d9808a 100644 --- a/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailTest.java +++ b/compliance/solr/src/test/java/org/eclipse/rdf4j/sail/solr/SolrSailTest.java @@ -37,7 +37,7 @@ public static void setUpClass() throws Exception { } @AfterAll - public static void tearDownClass() throws Exception { + public static void tearDownClass() { System.setProperty("solr.solr.home", toRestoreSolrHome == null ? "" : toRestoreSolrHome); toRestoreSolrHome = null; } diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/ArbitraryLengthPathTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/ArbitraryLengthPathTest.java index 96e48069462..3bc317da732 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/ArbitraryLengthPathTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/ArbitraryLengthPathTest.java @@ -35,54 +35,54 @@ public class ArbitraryLengthPathTest { private RepositoryConnection con; @BeforeEach - public void setUp() throws Exception { + public void setUp() { repo = new SailRepository(new MemoryStore()); con = repo.getConnection(); } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { con.close(); repo.shutDown(); } @Test - public void test10() throws Exception { + public void test10() { populate(10); String sparql = "ASK { * }"; assertTrue(con.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate()); } @Test - public void test100() throws Exception { + public void test100() { populate(100); String sparql = "ASK { * }"; assertTrue(con.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate()); } @Test - public void test1000() throws Exception { + public void test1000() { populate(1000); String sparql = "ASK { * }"; assertTrue(con.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate()); } @Test - public void test10000() throws Exception { + public void test10000() { populate(10000); String sparql = "ASK { * }"; assertTrue(con.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate()); } @Test - public void test100000() throws Exception { + public void test100000() { populate(100000); String sparql = "ASK { * }"; assertTrue(con.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate()); } @Test - public void testDirection() throws Exception { + public void testDirection() { ValueFactory vf = con.getValueFactory(); con.add(vf.createIRI("urn:test:a"), vf.createIRI("urn:test:rel"), vf.createIRI("urn:test:b")); con.add(vf.createIRI("urn:test:b"), vf.createIRI("urn:test:rel"), vf.createIRI("urn:test:a")); @@ -91,7 +91,7 @@ public void testDirection() throws Exception { } @Test - public void testSimilarPatterns() throws Exception { + public void testSimilarPatterns() { ValueFactory vf = con.getValueFactory(); con.add(vf.createIRI("urn:test:a"), RDF.TYPE, vf.createIRI("urn:test:c")); con.add(vf.createIRI("urn:test:b"), RDF.TYPE, vf.createIRI("urn:test:d")); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/HTTPSparqlUpdateTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/HTTPSparqlUpdateTest.java index bcddb35ee09..115c3f4bc25 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/HTTPSparqlUpdateTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/HTTPSparqlUpdateTest.java @@ -54,7 +54,7 @@ public static void stopServer() throws Exception { } @Override - protected Repository newRepository() throws Exception { + protected Repository newRepository() { return new HTTPRepository(server.getRepositoryUrl(repositoryId)); } @@ -68,7 +68,7 @@ public void testAutoCommitHandling() { } @Test - public void testBindingsInUpdateTransaction() throws Exception { + public void testBindingsInUpdateTransaction() { // See issue SES-1889 logger.debug("executing test testBindingsInUpdateTransaction"); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/SPARQLServiceEvaluationTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/SPARQLServiceEvaluationTest.java index c21d2c01ad0..503a79b27e7 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/SPARQLServiceEvaluationTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/SPARQLServiceEvaluationTest.java @@ -226,7 +226,7 @@ public void tearDown() throws Exception { * @see #646 */ @Test - public void testValuesBindClauseHandling() throws Exception { + public void testValuesBindClauseHandling() { String query = "select * { service <" + getRepositoryUrl(1) + "> { Bind(1 as ?val) . VALUES ?x {1 2} . } }"; try (RepositoryConnection conn = localRepository.getConnection()) { @@ -566,10 +566,9 @@ private Set readExpectedGraphQueryResult(String resultFile) throws Ex * @param queryResult * @param expectedResult * @param checkOrder - * @throws Exception */ private void compareTupleQueryResults(TupleQueryResult queryResult, TupleQueryResult expectedResult, - boolean checkOrder) throws Exception { + boolean checkOrder) { // Create MutableTupleQueryResult to be able to re-iterate over the // results MutableTupleQueryResult queryResultTable = new MutableTupleQueryResult(queryResult); @@ -688,9 +687,8 @@ private void compareTupleQueryResults(TupleQueryResult queryResult, TupleQueryRe * * @param queryResult * @param expectedResult - * @throws Exception */ - private void compareGraphs(Set queryResult, Set expectedResult) throws Exception { + private void compareGraphs(Set queryResult, Set expectedResult) { if (!Models.isomorphic(expectedResult, queryResult)) { // Don't use RepositoryUtil.difference, it reports incorrect diffs /* diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11UpdateTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11UpdateTest.java index 1587ba3e4e1..96700874565 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11UpdateTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11UpdateTest.java @@ -34,7 +34,7 @@ public W3CApprovedSPARQL11UpdateTest(String displayName, String testURI, String } @Override - protected Repository newRepository() throws Exception { + protected Repository newRepository() { SailRepository repo = new SailRepository(new MemoryStore()); return repo; diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/federation/FedXSPARQL11QueryComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/federation/FedXSPARQL11QueryComplianceTest.java index e6fd1aef390..efb4c30a8bb 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/federation/FedXSPARQL11QueryComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/federation/FedXSPARQL11QueryComplianceTest.java @@ -60,7 +60,7 @@ private void initManager() { } @Override - protected Repository newRepository() throws Exception { + protected Repository newRepository() { initManager(); addMemoryStore("repo1"); @@ -75,7 +75,7 @@ protected Repository newRepository() throws Exception { return new DatasetRepository(repo); } - private void addMemoryStore(String repoId) throws RepositoryConfigException, RepositoryException, IOException { + private void addMemoryStore(String repoId) throws RepositoryConfigException, RepositoryException { RepositoryImplConfig implConfig = new SailRepositoryConfig(new MemoryStoreConfig()); RepositoryConfig config = new RepositoryConfig(repoId, implConfig); manager.addRepositoryConfig(config); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11QueryComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11QueryComplianceTest.java index 8e6dfac2768..4c6728fa658 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11QueryComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11QueryComplianceTest.java @@ -29,7 +29,7 @@ public MemorySPARQL11QueryComplianceTest(String displayName, String testURI, Str } @Override - protected Repository newRepository() throws Exception { + protected Repository newRepository() { return new DatasetRepository(new SailRepository(new MemoryStore())); } } diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11UpdateComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11UpdateComplianceTest.java index 27d7ba9bb65..3df69511d07 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11UpdateComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11UpdateComplianceTest.java @@ -33,7 +33,7 @@ public MemorySPARQL11UpdateComplianceTest(String displayName, String testURI, St } @Override - protected Repository newRepository() throws Exception { + protected Repository newRepository() { return new SailRepository(new MemoryStore()); } diff --git a/core/client/pom.xml b/core/client/pom.xml index 0adb19c758a..dcc6771feb5 100644 --- a/core/client/pom.xml +++ b/core/client/pom.xml @@ -216,11 +216,6 @@ rdf4j-common-transaction ${project.version} - - org.eclipse.rdf4j - rdf4j-common-util - ${project.version} - org.eclipse.rdf4j rdf4j-common-xml diff --git a/core/collection-factory/api/pom.xml b/core/collection-factory/api/pom.xml index 464f40e2052..e39337fb961 100644 --- a/core/collection-factory/api/pom.xml +++ b/core/collection-factory/api/pom.xml @@ -30,10 +30,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/collection-factory/api/src/main/java/org/eclipse/rdf4j/collection/factory/api/CollectionFactory.java b/core/collection-factory/api/src/main/java/org/eclipse/rdf4j/collection/factory/api/CollectionFactory.java index fb7f581bb22..27e5bdf324d 100644 --- a/core/collection-factory/api/src/main/java/org/eclipse/rdf4j/collection/factory/api/CollectionFactory.java +++ b/core/collection-factory/api/src/main/java/org/eclipse/rdf4j/collection/factory/api/CollectionFactory.java @@ -19,7 +19,10 @@ import java.util.Map; import java.util.Queue; import java.util.Set; +import java.util.function.BiConsumer; import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.function.ToIntBiFunction; import java.util.function.ToIntFunction; @@ -28,6 +31,8 @@ import org.eclipse.rdf4j.common.exception.RDF4JException; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.MutableBindingSet; +import org.eclipse.rdf4j.query.impl.MapBindingSet; /** * A Factory that may generate optimised and/or disk based collections @@ -61,7 +66,26 @@ public interface CollectionFactory extends AutoCloseable { /** * @return a set that may be optimised and/or disk based */ - public Set createSetOfBindingSets(); + public default Set createSetOfBindingSets() { + // note the odd lambda returning a lambda + Function> gethas = (n) -> (b) -> b.hasBinding(n); + Function> getget = (n) -> (b) -> b.getValue(n); + Function> getSet = (n) -> (v, b) -> b.setBinding(n, v); + return createSetOfBindingSets(MapBindingSet::new, gethas, getget, getSet); + } + + /** + * Allows optimizations beyond what would otherwise be possible, regarding disk access and storage. + * + * @param create a supplier that makes bindingsets + * @param a supplier used to create prebound hasBinding predicates + * @param a supplier used to create prebound getValue functions + * @param a supplier used to create prebound setValue functions + * @return a set that may be optimised and/or disk based + */ + public Set createSetOfBindingSets(Supplier create, + Function> getHas, Function> getget, + Function> getSet); /** * @return a set that may be optimised and/or disk based for Values diff --git a/core/collection-factory/api/src/main/java/org/eclipse/rdf4j/collection/factory/impl/DefaultCollectionFactory.java b/core/collection-factory/api/src/main/java/org/eclipse/rdf4j/collection/factory/impl/DefaultCollectionFactory.java index e22e8587856..87acf1deb2a 100644 --- a/core/collection-factory/api/src/main/java/org/eclipse/rdf4j/collection/factory/impl/DefaultCollectionFactory.java +++ b/core/collection-factory/api/src/main/java/org/eclipse/rdf4j/collection/factory/impl/DefaultCollectionFactory.java @@ -19,7 +19,10 @@ import java.util.Map; import java.util.Queue; import java.util.Set; +import java.util.function.BiConsumer; import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.function.ToIntFunction; import org.eclipse.rdf4j.collection.factory.api.BindingSetKey; @@ -27,6 +30,7 @@ import org.eclipse.rdf4j.common.exception.RDF4JException; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.MutableBindingSet; /** * A DefaultCollectionFactory that provides lists/sets/maps using standard common java in memory types @@ -54,7 +58,9 @@ public Set createValueSet() { } @Override - public Set createSetOfBindingSets() { + public Set createSetOfBindingSets(Supplier create, + Function> getHas, Function> getget, + Function> getSet) { return new HashSet<>(); } @@ -97,5 +103,4 @@ public BindingSetKey createBindingSetKey(BindingSet bindingSet, List org.mapdb mapdb + 1.0.8 org.openjdk.jmh @@ -46,10 +47,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/collection-factory/mapdb/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDbCollectionFactory.java b/core/collection-factory/mapdb/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDbCollectionFactory.java index 3b757a67a40..c77a1a9cf92 100644 --- a/core/collection-factory/mapdb/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDbCollectionFactory.java +++ b/core/collection-factory/mapdb/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDbCollectionFactory.java @@ -21,7 +21,10 @@ import java.util.Map; import java.util.Queue; import java.util.Set; +import java.util.function.BiConsumer; import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.function.ToIntFunction; import org.eclipse.rdf4j.collection.factory.api.BindingSetKey; @@ -30,6 +33,7 @@ import org.eclipse.rdf4j.common.exception.RDF4JException; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.MutableBindingSet; import org.mapdb.DB; import org.mapdb.DBMaker; @@ -89,6 +93,14 @@ public List createValueList() { return delegate.createValueList(); } + @Override + public Set createSetOfBindingSets(Supplier create, + Function> getHas, Function> getget, + Function> getSet) { + // No optimizations here + return createSetOfBindingSets(); + } + @Override public Set createSetOfBindingSets() { if (iterationCacheSyncThreshold > 0) { diff --git a/core/collection-factory/mapdb/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/benchmark/BindingSetMapBenchmark.java b/core/collection-factory/mapdb/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/benchmark/BindingSetMapBenchmark.java new file mode 100644 index 00000000000..82abf7012f4 --- /dev/null +++ b/core/collection-factory/mapdb/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/benchmark/BindingSetMapBenchmark.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb.benchmark; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.eclipse.rdf4j.collection.factory.api.CollectionFactory; +import org.eclipse.rdf4j.collection.factory.mapdb.MapDbCollectionFactory; +import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.MutableBindingSet; +import org.eclipse.rdf4j.query.impl.MapBindingSet; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +@State(Scope.Benchmark) +@Warmup(iterations = 5) +@BenchmarkMode({ Mode.AverageTime }) +@Fork(value = 1, jvmArgs = { "-Xms1G", "-Xmx1G" }) +@Measurement(iterations = 5) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +public class BindingSetMapBenchmark { + private static final ValueFactory vf = SimpleValueFactory.getInstance(); + @Param(value = { "1000", "10000" }) + public int size; + + @Param(value = { "1", "129" }) + public int bsSize; + + @Benchmark + public long saveBindingSets() { + + try (CollectionFactory cf = new MapDbCollectionFactory(1000)) { + final Set sbs = cf.createSetOfBindingSets(); + addBindingSetOfSizeX(sbs, bsSize); + return sbs.size(); + } + } + + private void addBindingSetOfSizeX(final Set sbs, int bsSize) { + for (int i = 0; i < size; i++) { + MutableBindingSet bs = new MapBindingSet(); + for (int j = 0; j < bsSize; j++) { + bs.addBinding(Integer.toString(j), vf.createLiteral(i)); + } + sbs.add(bs); + } + } +} diff --git a/core/common/util/pom.xml b/core/collection-factory/mapdb3/pom.xml similarity index 69% rename from core/common/util/pom.xml rename to core/collection-factory/mapdb3/pom.xml index 119d738a85d..de753e98014 100644 --- a/core/common/util/pom.xml +++ b/core/collection-factory/mapdb3/pom.xml @@ -3,22 +3,32 @@ 4.0.0 org.eclipse.rdf4j - rdf4j-common + rdf4j-collection-factory 5.0.0-SNAPSHOT - rdf4j-common-util - RDF4J: common utilities - RDF4J common utility classes + rdf4j-collection-factory-mapdb3 + RDF4J: Collection Factory - Map DB v3 backed + Evaluation ${project.groupId} - rdf4j-model-api + rdf4j-collection-factory-api + ${project.version} + + + ${project.groupId} + rdf4j-model ${project.version} org.slf4j slf4j-api + + org.mapdb + mapdb + 3.0.9 + org.openjdk.jmh jmh-core diff --git a/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetKeySerializer.java b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetKeySerializer.java new file mode 100644 index 00000000000..3e94235690f --- /dev/null +++ b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetKeySerializer.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb; + +import java.io.IOException; + +import org.eclipse.rdf4j.collection.factory.api.BindingSetKey; +import org.eclipse.rdf4j.collection.factory.mapdb.MapDb3CollectionFactory.RDF4jMapDB3Exception; +import org.eclipse.rdf4j.model.Value; +import org.mapdb.DataInput2; +import org.mapdb.DataOutput2; +import org.mapdb.Serializer; +import org.mapdb.serializer.SerializerBoolean; +import org.mapdb.serializer.SerializerIntegerPacked; + +class BindingSetKeySerializer implements Serializer { + + private final SerializerBoolean sb = new SerializerBoolean(); + private final SerializerIntegerPacked si = new SerializerIntegerPacked(); + private final Serializer vs; + + public BindingSetKeySerializer(Serializer vs) { + this.vs = vs; + } + + @Override + public void serialize(DataOutput2 out, BindingSetKey value) throws IOException { + if (value == null) { + sb.serialize(out, true); + } else { + sb.serialize(out, false); + try { + MapDb3BindingSetKey k = (MapDb3BindingSetKey) value; + si.serialize(out, k.hashCode()); + si.serialize(out, k.values.length); + for (int i = 0; i < k.values.length; i++) { + vs.serialize(out, k.values[i]); + } + } catch (ClassCastException e) { + throw new RDF4jMapDB3Exception("Collection factory overriden in an non conformat way", e); + } + } + + } + + @Override + public BindingSetKey deserialize(DataInput2 input, int available) throws IOException { + if (sb.deserialize(input, available)) { + return null; + } else { + int hashCode = si.deserialize(input, available); + int length = si.deserialize(input, available); + Value[] values = new Value[length]; + for (int i = 0; i < length; i++) { + values[i] = vs.deserialize(input, available); + } + return new MapDb3BindingSetKey(values, hashCode); + } + } + +} diff --git a/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetSerializer.java b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetSerializer.java new file mode 100644 index 00000000000..25cbcc62186 --- /dev/null +++ b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetSerializer.java @@ -0,0 +1,101 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; + +import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.MutableBindingSet; +import org.mapdb.DataInput2; +import org.mapdb.DataOutput2; +import org.mapdb.Serializer; +import org.mapdb.serializer.SerializerBoolean; +import org.mapdb.serializer.SerializerIntegerPacked; + +class BindingSetSerializer implements Serializer { + + // Insertion order is very important + private final LinkedHashSet names = new LinkedHashSet(); + private final List> has = new ArrayList<>(); + private final List> get = new ArrayList<>(); + private final List> set = new ArrayList<>(); + private final Serializer vs; + private final SerializerBoolean sb = new SerializerBoolean(); + private final SerializerIntegerPacked si = new SerializerIntegerPacked(); + private final Supplier create; + private final Function> getHas; + private final Function> getGet; + private final Function> getSet; + + public BindingSetSerializer(Serializer valueSerializer, Supplier create, + Function> getHas, Function> getGet, + Function> getSet) { + this.vs = valueSerializer; + this.create = create; + this.getHas = getHas; + this.getGet = getGet; + this.getSet = getSet; + } + + @Override + public void serialize(DataOutput2 out, BindingSet bs) throws IOException { + + final Set bindingNames = bs.getBindingNames(); + if (names.addAll(bindingNames)) { + // new name found + int i = has.size(); + final Iterator nameI = names.iterator(); + // Don't get setters that we already got. + while (nameI.hasNext() && i > 0) { + i--; + } + while (nameI.hasNext()) { + String name = nameI.next(); + has.add(getHas.apply(name)); + get.add(getGet.apply(name)); + set.add(getSet.apply(name)); + } + } + // all binding names where present + for (int i = 0; i < has.size(); i++) { + if (has.get(i).test(bs)) { + sb.serialize(out, true); + si.serialize(out, i); + vs.serialize(out, get.get(i).apply(bs)); + } + } + sb.serialize(out, false); // marks the end + } + + @Override + public BindingSet deserialize(DataInput2 input, int available) throws IOException { + boolean hasMore = sb.deserialize(input, available); + MutableBindingSet bs = create.get(); + while (hasMore) { + int nextName = si.deserialize(input, available); + Value nextValue = vs.deserialize(input, available); + set.get(nextName).accept(nextValue, bs); + hasMore = sb.deserialize(input, available); + } + return bs; + } + +} diff --git a/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDb3BindingSetKey.java b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDb3BindingSetKey.java new file mode 100644 index 00000000000..adde1d26dff --- /dev/null +++ b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDb3BindingSetKey.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb; + +import java.util.Arrays; +import java.util.List; + +import org.eclipse.rdf4j.collection.factory.api.BindingSetKey; +import org.eclipse.rdf4j.model.Value; + +class MapDb3BindingSetKey implements BindingSetKey { + final Value[] values; + + private final int hash; + + public MapDb3BindingSetKey(List values, int hash) { + this.values = values.toArray(new Value[0]); + this.hash = hash; + } + + public MapDb3BindingSetKey(Value[] values, int hash) { + this.values = values; + this.hash = hash; + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(Object other) { + if (other instanceof MapDb3BindingSetKey && other.hashCode() == hash) { + return Arrays.deepEquals(values, ((MapDb3BindingSetKey) other).values); + } + return false; + } +} diff --git a/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDb3CollectionFactory.java b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDb3CollectionFactory.java new file mode 100644 index 00000000000..ef1a94956e1 --- /dev/null +++ b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/MapDb3CollectionFactory.java @@ -0,0 +1,410 @@ +/******************************************************************************* + * Copyright (c) 2022 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb; + +import java.util.AbstractMap; +import java.util.AbstractSet; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.function.ToIntFunction; + +import org.eclipse.rdf4j.collection.factory.api.BindingSetKey; +import org.eclipse.rdf4j.collection.factory.api.CollectionFactory; +import org.eclipse.rdf4j.collection.factory.impl.DefaultCollectionFactory; +import org.eclipse.rdf4j.common.exception.RDF4JException; +import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.MutableBindingSet; +import org.mapdb.DB; +import org.mapdb.DB.HashMapMaker; +import org.mapdb.DBException; +import org.mapdb.DBMaker; +import org.mapdb.DBMaker.Maker; +import org.mapdb.HTreeMap; +import org.mapdb.Serializer; +import org.mapdb.serializer.SerializerJava; + +public class MapDb3CollectionFactory implements CollectionFactory { + // The size 16 seems like a nice starting value but others could well + // be better. + private static final int SWITCH_TO_DISK_BASED_SET_AT_SIZE = 16; + protected volatile DB db; + protected volatile long colectionId = 0; + protected final long iterationCacheSyncThreshold; + private final CollectionFactory delegate; + // The chances that someone would run a 32bit non "sun" vm are just miniscule + // So I am not going to worry about this. + private static final boolean ON_32_BIT_VM = "32".equals(System.getProperty("sun.arch.data.model")); + + protected static final class RDF4jMapDB3Exception extends RDF4JException { + + private static final long serialVersionUID = 1L; + + public RDF4jMapDB3Exception(String string, Exception e) { + super(string, e); + } + + } + + public MapDb3CollectionFactory(long iterationCacheSyncThreshold) { + this(iterationCacheSyncThreshold, new DefaultCollectionFactory()); + } + + public MapDb3CollectionFactory(long iterationCacheSyncThreshold, CollectionFactory delegate) { + + this.iterationCacheSyncThreshold = iterationCacheSyncThreshold; + this.delegate = delegate; + } + + protected void init() { + if (this.db == null) { + synchronized (this) { + if (this.db == null) { + try { + final Maker dbmaker = DBMaker.tempFileDB().closeOnJvmShutdown(); + // On 32 bit machines this may fail to often so guard it. + if (!ON_32_BIT_VM) { + // mmap is much faster than random access file. + dbmaker.fileMmapEnable(); + } + this.db = dbmaker.make(); + } catch (DBException e) { + throw new RDF4jMapDB3Exception("could not initialize temp db", e); + } + } + } + } + } + + @Override + public List createList() { + return delegate.createList(); + } + + @Override + public List createValueList() { + return delegate.createValueList(); + } + + @Override + public Set createSetOfBindingSets(Supplier create, + Function> getHas, Function> getget, + Function> getSet) { + if (iterationCacheSyncThreshold > 0) { + init(); + Serializer serializer = createBindingSetSerializer(create, getHas, getget, getSet); + MemoryTillSizeXSet set = new MemoryTillSizeXSet<>(colectionId++, + delegate.createSetOfBindingSets(), serializer); + return new CommitingSet<>(set, iterationCacheSyncThreshold, db); + } else { + return delegate.createSetOfBindingSets(); + } + } + + @Override + public Set createSet() { + if (iterationCacheSyncThreshold > 0) { + init(); + Serializer serializer = createAnySerializer(); + MemoryTillSizeXSet set = new MemoryTillSizeXSet(colectionId++, delegate.createSet(), serializer); + return new CommitingSet(set, iterationCacheSyncThreshold, db); + } else { + return delegate.createSet(); + } + } + + @Override + public Set createValueSet() { + if (iterationCacheSyncThreshold > 0) { + init(); + Serializer serializer = createValueSerializer(); + Set set = new MemoryTillSizeXSet<>(colectionId++, delegate.createValueSet(), serializer); + return new CommitingSet(set, iterationCacheSyncThreshold, db); + } else { + return delegate.createValueSet(); + } + } + + @Override + public Map createMap() { + if (iterationCacheSyncThreshold > 0) { + init(); + Serializer keySerializer = createAnySerializer(); + Serializer valueSerializer = createAnySerializer(); + HashMapMaker hashMap = db.hashMap(Long.toHexString(colectionId++), keySerializer, valueSerializer); + HTreeMap create = hashMap.create(); + return new CommitingMap<>(create, iterationCacheSyncThreshold, db); + } else { + return delegate.createMap(); + } + } + + @Override + public Map createValueKeyedMap() { + if (iterationCacheSyncThreshold > 0) { + init(); + Serializer keySerializer = createValueSerializer(); + Serializer valueSerializer = createAnySerializer(); + return new CommitingMap<>( + db.hashMap(Long.toHexString(colectionId++), keySerializer, valueSerializer).create(), + iterationCacheSyncThreshold, db); + } else { + return delegate.createValueKeyedMap(); + } + } + + @Override + public Queue createQueue() { + return delegate.createQueue(); + } + + @Override + public Queue createValueQueue() { + return delegate.createValueQueue(); + } + + @Override + public void close() throws RDF4JException { + if (db != null) { + db.close(); + } + } + + @Override + public Map createGroupByMap() { + if (iterationCacheSyncThreshold > 0) { + init(); + Serializer keySerializer = createBindingSetKeySerializer(); + Serializer valueSerializer = createAnySerializer(); + return new CommitingMap<>( + db.hashMap(Long.toHexString(colectionId++), keySerializer, valueSerializer).create(), + iterationCacheSyncThreshold, db); + } else { + return delegate.createGroupByMap(); + } + } + + @Override + public final BindingSetKey createBindingSetKey(BindingSet bindingSet, List> getValues, + ToIntFunction hashOfBindingSetCalculator) { + List values = new ArrayList<>(getValues.size()); + for (int i = 0; i < getValues.size(); i++) { + values.add(getValues.get(i).apply(bindingSet)); + } + return new MapDb3BindingSetKey(values, hashOfBindingSetCalculator.applyAsInt(bindingSet)); + } + + protected static final class CommitingSet extends AbstractSet { + private final Set wrapped; + private final long iterationCacheSyncThreshold; + private final DB db; + private long iterationCount; + + public CommitingSet(Set wrapped, long iterationCacheSyncThreshold, DB db) { + super(); + this.wrapped = wrapped; + this.iterationCacheSyncThreshold = iterationCacheSyncThreshold; + this.db = db; + } + + @Override + public boolean add(T e) { + + boolean res = wrapped.add(e); + if (iterationCount++ % iterationCacheSyncThreshold == 0) { + // write to disk every $iterationCacheSyncThreshold items + db.commit(); + } + return res; + + } + + @Override + public boolean addAll(Collection c) { + boolean res = wrapped.addAll(c); + if (iterationCount + c.size() % iterationCacheSyncThreshold == 0) { + // write to disk every $iterationCacheSyncThreshold items + db.commit(); + } + return res; + } + + @Override + public Iterator iterator() { + return wrapped.iterator(); + } + + @Override + public int size() { + return wrapped.size(); + } + } + + protected static final class CommitingMap extends AbstractMap { + private final Map wrapped; + private final long iterationCacheSyncThreshold; + private final DB db; + private long iterationCount; + + public CommitingMap(Map wrapped, long iterationCacheSyncThreshold, DB db) { + super(); + this.wrapped = wrapped; + this.iterationCacheSyncThreshold = iterationCacheSyncThreshold; + this.db = db; + } + + @Override + public V put(K k, V v) { + + V res = wrapped.put(k, v); + if (iterationCount++ % iterationCacheSyncThreshold == 0) { + // write to disk every $iterationCacheSyncThreshold items + db.commit(); + } + return res; + + } + + @Override + public int size() { + return wrapped.size(); + } + + @Override + public Set> entrySet() { + return wrapped.entrySet(); + } + } + + /** + * Only create a disk based set once the contents are large enough that it starts to pay off. + * + * @param of the contents of the set. + */ + protected class MemoryTillSizeXSet extends AbstractSet { + private Set wrapped; + private final long setName; + private final Serializer valueSerializer; + + public MemoryTillSizeXSet(long setName, Set wrapped, Serializer valueSerializer) { + super(); + this.setName = setName; + this.wrapped = wrapped; + this.valueSerializer = valueSerializer; + } + + @Override + public boolean add(V e) { + if (wrapped instanceof HashSet && wrapped.size() > SWITCH_TO_DISK_BASED_SET_AT_SIZE) { + Set disk = db.hashSet(Long.toHexString(setName), valueSerializer).create(); + disk.addAll(wrapped); + wrapped = disk; + } + return wrapped.add(e); + } + + @Override + public boolean addAll(Collection arg0) { + if (wrapped instanceof HashSet && arg0.size() > SWITCH_TO_DISK_BASED_SET_AT_SIZE) { + Set disk = db.hashSet(Long.toHexString(setName), valueSerializer).create(); + disk.addAll(wrapped); + wrapped = disk; + } + return wrapped.addAll(arg0); + } + + @Override + public void clear() { + wrapped.clear(); + } + + @Override + public boolean contains(Object o) { + return wrapped.contains(o); + } + + @Override + public boolean containsAll(Collection arg0) { + return wrapped.containsAll(arg0); + } + + @Override + public boolean isEmpty() { + return wrapped.isEmpty(); + } + + @Override + public boolean remove(Object o) { + return wrapped.remove(o); + } + + @Override + public boolean retainAll(Collection c) { + return wrapped.retainAll(c); + } + + @Override + public Object[] toArray() { + return wrapped.toArray(); + } + + @Override + public T[] toArray(T[] arg0) { + return wrapped.toArray(arg0); + } + + @Override + public Iterator iterator() { + return wrapped.iterator(); + } + + @Override + public int size() { + return wrapped.size(); + } + + } + + /** + * These methods should be overriding in case a store can deliver a better serialization protocol. + * + * @param getGet + * @param getHas + * @param create + */ + protected Serializer createBindingSetSerializer(Supplier create, + Function> getHas, Function> getGet, + Function> getSet) { + return new BindingSetSerializer(createValueSerializer(), create, getHas, getGet, getSet); + } + + protected Serializer createAnySerializer() { + return new SerializerJava(); + } + + protected Serializer createValueSerializer() { + return new ValueSerializer(); + } + + protected final Serializer createBindingSetKeySerializer() { + return new BindingSetKeySerializer(createValueSerializer()); + } +} diff --git a/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/ValueSerializer.java b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/ValueSerializer.java new file mode 100644 index 00000000000..c371b4a1549 --- /dev/null +++ b/core/collection-factory/mapdb3/src/main/java/org/eclipse/rdf4j/collection/factory/mapdb/ValueSerializer.java @@ -0,0 +1,194 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb; + +import java.io.IOException; +import java.util.Optional; + +import org.eclipse.rdf4j.model.BNode; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Literal; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.Triple; +import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; +import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.mapdb.DataInput2; +import org.mapdb.DataOutput2; +import org.mapdb.Serializer; +import org.mapdb.serializer.SerializerIntegerPacked; +import org.mapdb.serializer.SerializerString; + +/** + * A minimally optimized serializer for values. + * + * @author Jerven Bolleman + */ +class ValueSerializer implements Serializer { + private static final int IS_NEW_COREDATATYPE = 5; + private static final int IS_RDF_DATATYPE = 4; + private static final int IS_GEO_DATATYPE = 3; + private static final int IS_XSD_DATATYPE = 2; + private static final int NOT_COREDATYPE = 1; + private static final int IS_LANGUAGE = 0; + private static final int IS_BNODE = 0; + private static final int IS_IRI = 1; + private static final int IS_LITERAL = 2; + private static final int IS_TRIPLE = 3; + private static final int IS_NULL = 4; + private final SerializerIntegerPacked si = new SerializerIntegerPacked(); + private final SerializerString ss = new SerializerString(); + private final ValueFactory vf; + + public ValueSerializer() { + this(SimpleValueFactory.getInstance()); + } + + public ValueSerializer(ValueFactory vf) { + super(); + this.vf = vf; + } + + @Override + public void serialize(DataOutput2 out, Value value) throws IOException { + if (value instanceof BNode) { + si.serialize(out, IS_BNODE); + serializeBNode(out, (BNode) value); + } else if (value instanceof IRI) { + si.serialize(out, IS_IRI); + serializeIRI(out, (IRI) value); + } else if (value instanceof Literal) { + si.serialize(out, IS_LITERAL); + serializeLiteral(out, (Literal) value); + } else if (value instanceof Triple) { + si.serialize(out, IS_TRIPLE); + serializeTriple(out, (Triple) value); + } else { + si.serialize(out, IS_NULL); + } + } + + private void serializeBNode(DataOutput2 out, BNode bnode) throws IOException { + ss.serialize(out, bnode.getID()); + } + + private void serializeLiteral(DataOutput2 out, Literal value) throws IOException { + final Optional language = value.getLanguage(); + if (language.isPresent()) { + si.serialize(out, IS_LANGUAGE); + ss.serialize(out, value.stringValue()); + ss.serialize(out, language.get()); + } else { + final CoreDatatype cd = value.getCoreDatatype(); + if (cd == null) { + si.serialize(out, NOT_COREDATYPE); + serializeIRI(out, value.getDatatype()); + } else if (cd.isXSDDatatype()) { + si.serialize(out, IS_XSD_DATATYPE); + si.serialize(out, ((CoreDatatype.XSD) cd).ordinal()); + // TODO optimize the storage of valid pure int etc. + // without needing to parse strings + } else if (cd.isGEODatatype()) { + si.serialize(out, IS_GEO_DATATYPE); + si.serialize(out, ((CoreDatatype.GEO) cd).ordinal()); + } else if (cd.isRDFDatatype()) { + si.serialize(out, IS_RDF_DATATYPE); + si.serialize(out, ((CoreDatatype.RDF) cd).ordinal()); + } else { + si.serialize(out, IS_NEW_COREDATATYPE); + serializeIRI(out, value.getDatatype()); + } + ss.serialize(out, value.stringValue()); + } + } + + private void serializeIRI(DataOutput2 out, IRI value) throws IOException { + ss.serialize(out, value.stringValue()); + } + + private void serializeTriple(DataOutput2 out, Triple value) throws IOException { + serialize(out, value.getSubject()); + serialize(out, value.getPredicate()); + serialize(out, value.getObject()); + } + + @Override + public Value deserialize(DataInput2 input, int available) throws IOException { + int t = si.deserialize(input, available); + switch (t) { + case IS_BNODE: + return deserializeBnode(input, available); + case IS_IRI: + return deserializeIRI(input, available); + case IS_LITERAL: + return deserializeLiteral(input, available); + case IS_TRIPLE: + return deserializeTriple(input, available); + case IS_NULL: + default: + return null; + } + } + + private Value deserializeTriple(DataInput2 input, int available) throws IOException { + final Resource subj = (Resource) deserialize(input, available); + final IRI pred = (IRI) deserialize(input, available); + final Value obj = deserialize(input, available); + return vf.createTriple(subj, pred, obj); + } + + private Value deserializeLiteral(DataInput2 input, int available) throws IOException { + int t = si.deserialize(input, available); + switch (t) { + case IS_LANGUAGE: { + String language = ss.deserialize(input, available); + String value = ss.deserialize(input, available); + return vf.createLiteral(value, language); + } + case NOT_COREDATYPE: { + IRI datatype = deserializeIRI(input, available); + String value = ss.deserialize(input, available); + return vf.createLiteral(value, datatype); + } + case IS_XSD_DATATYPE: { + CoreDatatype.XSD datatype = CoreDatatype.XSD.values()[si.deserialize(input, available)]; + String value = ss.deserialize(input, available); + return vf.createLiteral(value, datatype); + } + case IS_GEO_DATATYPE: { + CoreDatatype.GEO datatype = CoreDatatype.GEO.values()[si.deserialize(input, available)]; + String value = ss.deserialize(input, available); + return vf.createLiteral(value, datatype); + } + case IS_RDF_DATATYPE: { + CoreDatatype.RDF datatype = CoreDatatype.RDF.values()[si.deserialize(input, available)]; + String value = ss.deserialize(input, available); + return vf.createLiteral(value, datatype); + } + case IS_NEW_COREDATATYPE: { + IRI datatype = deserializeIRI(input, available); + String value = ss.deserialize(input, available); + return vf.createLiteral(value, datatype); + } + } + return null; + } + + private IRI deserializeIRI(DataInput2 input, int available) throws IOException { + return vf.createIRI(ss.deserialize(input, available)); + } + + private BNode deserializeBnode(DataInput2 input, int available) throws IOException { + return vf.createBNode(ss.deserialize(input, available)); + } + +} diff --git a/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetSerializerTest.java b/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetSerializerTest.java new file mode 100644 index 00000000000..bcd3c179ac3 --- /dev/null +++ b/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/BindingSetSerializerTest.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Predicate; + +import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.MutableBindingSet; +import org.eclipse.rdf4j.query.impl.MapBindingSet; +import org.junit.jupiter.api.Test; +import org.mapdb.DataInput2; +import org.mapdb.DataOutput2; + +public class BindingSetSerializerTest { + private static final ValueFactory vf = SimpleValueFactory.getInstance(); + + @Test + void noBinding() throws IOException { + BindingSet toSerialize = new MapBindingSet(); + final BindingSetSerializer valueSerializer = createSerializer(); + final BindingSet deserialized = serializeDeserialize(toSerialize, valueSerializer); + assertEquals(toSerialize, deserialized); + } + + @Test + void oneBinding() throws IOException { + MapBindingSet toSerialize = new MapBindingSet(); + toSerialize.setBinding("a", vf.createLiteral(1)); + final BindingSetSerializer valueSerializer = createSerializer(); + final BindingSet deserialized = serializeDeserialize(toSerialize, valueSerializer); + assertEquals(toSerialize, deserialized); + } + + @Test + void twoBinding() throws IOException { + MapBindingSet toSerialize = new MapBindingSet(); + toSerialize.setBinding("a", vf.createLiteral(1)); + toSerialize.setBinding("v", vf.createLiteral(1)); + final BindingSetSerializer valueSerializer = createSerializer(); + final BindingSet deserialized = serializeDeserialize(toSerialize, valueSerializer); + assertEquals(toSerialize, deserialized); + } + + @Test + void secondBindingIri() throws IOException { + final BindingSetSerializer valueSerializer = createSerializer(); + + MapBindingSet toSerialize = new MapBindingSet(); + toSerialize.setBinding("a", vf.createLiteral(1)); + toSerialize.setBinding("v", vf.createIRI("http://example.org/lala")); + BindingSet deserialized = serializeDeserialize(toSerialize, valueSerializer); + assertEquals(toSerialize, deserialized); + } + + @Test + void multipleNumbersOfBindingsIri() throws IOException { + final BindingSetSerializer valueSerializer = createSerializer(); + + MapBindingSet toSerialize = new MapBindingSet(); + toSerialize.setBinding("a", vf.createLiteral(1)); + toSerialize.setBinding("v", vf.createIRI("http://example.org/lala")); + BindingSet deserialized = serializeDeserialize(toSerialize, valueSerializer); + assertEquals(toSerialize, deserialized); + + toSerialize = new MapBindingSet(); + toSerialize.setBinding("a", vf.createLiteral(2)); + deserialized = serializeDeserialize(toSerialize, valueSerializer); + assertEquals(toSerialize, deserialized); + + toSerialize = new MapBindingSet(); + toSerialize.setBinding("a", vf.createLiteral(1)); + toSerialize.setBinding("b", vf.createLiteral(4)); + toSerialize.setBinding("c", vf.createLiteral(1)); + deserialized = serializeDeserialize(toSerialize, valueSerializer); + assertEquals(toSerialize, deserialized); + } + + private BindingSet serializeDeserialize(BindingSet oneInt, BindingSetSerializer valueSerializer) + throws IOException { + + final DataOutput2 dataOutput2 = new DataOutput2(); + valueSerializer.serialize(dataOutput2, oneInt); + + final DataInput2 input = new DataInput2.ByteArray(dataOutput2.copyBytes()); + BindingSet doneInt = valueSerializer.deserialize(input, 0); + return doneInt; + } + + private BindingSetSerializer createSerializer() { + Function> getHas = (n) -> { + return (b) -> b.hasBinding(n); + }; + Function> getGet = (n) -> { + return (b) -> b.getValue(n); + }; + Function> getSet = (n) -> { + return (v, b) -> b.setBinding(n, v); + }; + final BindingSetSerializer valueSerializer = new BindingSetSerializer(new ValueSerializer(vf), + MapBindingSet::new, getHas, getGet, getSet); + return valueSerializer; + } +} diff --git a/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/ValueSerializerTest.java b/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/ValueSerializerTest.java new file mode 100644 index 00000000000..46e35e10f03 --- /dev/null +++ b/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/ValueSerializerTest.java @@ -0,0 +1,127 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Literal; +import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; +import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.junit.jupiter.api.Test; +import org.mapdb.DataInput2; +import org.mapdb.DataOutput2; + +public class ValueSerializerTest { + private static final ValueFactory vf = SimpleValueFactory.getInstance(); + + @Test + void literalOneInt() throws IOException { + Literal oneInt = vf.createLiteral(1); + Value doneInt = serializeDeserialize(oneInt); + assertEquals(oneInt, doneInt); + } + + @Test + void literalOneIntCoreDatatype() throws IOException { + Literal oneInt = vf.createLiteral("1", CoreDatatype.XSD.INT); + Value doneInt = serializeDeserialize(oneInt); + assertEquals(oneInt, doneInt); + } + + @Test + void literalTwoInt() throws IOException { + Literal twoInt = vf.createLiteral(2); + Value dTwoInt = serializeDeserialize(twoInt); + assertEquals(twoInt, dTwoInt); + } + + @Test + void literalTwoFloat() throws IOException { + Literal toSerialize = vf.createLiteral(2.0f); + Value deserialized = serializeDeserialize(toSerialize); + assertEquals(toSerialize, deserialized); + } + + @Test + void literalTwoDouble() throws IOException { + Literal toSerialize = vf.createLiteral(2.0d); + Value deserialized = serializeDeserialize(toSerialize); + assertEquals(toSerialize, deserialized); + } + + @Test + void literalTwoBigInteger() throws IOException { + Literal toSerialize = vf.createLiteral(BigInteger.valueOf(20000000)); + Value deserialized = serializeDeserialize(toSerialize); + assertEquals(toSerialize, deserialized); + } + + @Test + void literalTwoBigDecimal() throws IOException { + Literal toSerialize = vf.createLiteral(BigDecimal.valueOf(20000030.3443)); + Value deserialized = serializeDeserialize(toSerialize); + assertEquals(toSerialize, deserialized); + } + + @Test + void iriExampleOrg() throws IOException { + Value toSerialize = vf.createIRI("https://example.org/lala"); + Value deserialized = serializeDeserialize(toSerialize); + assertEquals(toSerialize, deserialized); + } + + @Test + void tripleOfExampleOrg() throws IOException { + final IRI iri = vf.createIRI("https://example.org/lala"); + Value toSerialize = vf.createTriple(iri, iri, iri); + Value deserialized = serializeDeserialize(toSerialize); + assertEquals(toSerialize, deserialized); + } + + @Test + void bnode() throws IOException { + Value toSerialize = vf.createBNode("111"); + Value deserialized = serializeDeserialize(toSerialize); + assertEquals(toSerialize, deserialized); + } + + @Test + void newCoreDatatype() throws IOException { + CoreDatatype n = new CoreDatatype() { + + @Override + public IRI getIri() { + return vf.createIRI("https://example.org/lala"); + } + + }; + Value toSerialize = vf.createLiteral("111", n); + Value deserialized = serializeDeserialize(toSerialize); + assertEquals(toSerialize, deserialized); + } + + private Value serializeDeserialize(Value oneInt) throws IOException { + final ValueSerializer valueSerializer = new ValueSerializer(vf); + final DataOutput2 dataOutput2 = new DataOutput2(); + valueSerializer.serialize(dataOutput2, oneInt); + + final DataInput2 input = new DataInput2.ByteArray(dataOutput2.copyBytes()); + Value doneInt = valueSerializer.deserialize(input, 0); + return doneInt; + } +} diff --git a/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/benchmark/BindingSetMapBenchmark.java b/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/benchmark/BindingSetMapBenchmark.java new file mode 100644 index 00000000000..26135eaade5 --- /dev/null +++ b/core/collection-factory/mapdb3/src/test/java/org/eclipse/rdf4j/collection/factory/mapdb/benchmark/BindingSetMapBenchmark.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.collection.factory.mapdb.benchmark; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.eclipse.rdf4j.collection.factory.api.CollectionFactory; +import org.eclipse.rdf4j.collection.factory.mapdb.MapDb3CollectionFactory; +import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.MutableBindingSet; +import org.eclipse.rdf4j.query.impl.MapBindingSet; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +@State(Scope.Benchmark) +@Warmup(iterations = 5) +@BenchmarkMode({ Mode.AverageTime }) +@Fork(value = 1, jvmArgs = { "-Xms1G", "-Xmx1G" }) +@Measurement(iterations = 5) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +public class BindingSetMapBenchmark { + private static final ValueFactory vf = SimpleValueFactory.getInstance(); + @Param(value = { "1000", "10000" }) + public int size; + + @Param(value = { "1", "129" }) + public int bsSize; + + @Benchmark + public long saveBindingSets() { + + try (CollectionFactory cf = new MapDb3CollectionFactory(1000)) { + final Set sbs = cf.createSetOfBindingSets(); + addBindingSetOfSizeX(sbs, bsSize); + return sbs.size(); + } + } + + private void addBindingSetOfSizeX(final Set sbs, int bsSize) { + for (int i = 0; i < size; i++) { + MutableBindingSet bs = new MapBindingSet(); + for (int j = 0; j < bsSize; j++) { + bs.addBinding(Integer.toString(j), vf.createLiteral(i)); + } + sbs.add(bs); + } + } +} diff --git a/core/collection-factory/pom.xml b/core/collection-factory/pom.xml index 830295ba9af..2309b0ce29b 100644 --- a/core/collection-factory/pom.xml +++ b/core/collection-factory/pom.xml @@ -11,6 +11,7 @@ api mapdb + mapdb3 RDF4J: Collection Factory that may be shared Collection Factories that may be reused for RDF4J diff --git a/core/common/annotation/pom.xml b/core/common/annotation/pom.xml index 34f82702201..b3c8df98930 100644 --- a/core/common/annotation/pom.xml +++ b/core/common/annotation/pom.xml @@ -14,10 +14,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/common/exception/pom.xml b/core/common/exception/pom.xml index 7956636e262..9b6dd2b2976 100644 --- a/core/common/exception/pom.xml +++ b/core/common/exception/pom.xml @@ -26,10 +26,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/common/io/pom.xml b/core/common/io/pom.xml index 54789b47e21..4bbf5246908 100644 --- a/core/common/io/pom.xml +++ b/core/common/io/pom.xml @@ -15,11 +15,6 @@ rdf4j-model-api ${project.version} - - ${project.groupId} - rdf4j-common-util - ${project.version} - org.slf4j slf4j-api @@ -42,10 +37,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/common/io/src/main/java/org/eclipse/rdf4j/common/lang/ObjectUtil.java b/core/common/io/src/main/java/org/eclipse/rdf4j/common/lang/ObjectUtil.java index a4a10db2582..ef1c6884c18 100644 --- a/core/common/io/src/main/java/org/eclipse/rdf4j/common/lang/ObjectUtil.java +++ b/core/common/io/src/main/java/org/eclipse/rdf4j/common/lang/ObjectUtil.java @@ -20,20 +20,6 @@ */ public class ObjectUtil { - /** - * Compares two objects or null references. - * - * @param o1 The first object. - * @param o2 The second object - * @return true if both objects are null, if the object references are identical, or if the - * objects are equal according to the {@link Object#equals} method of the first object; false in - * all other situations. - */ - @Deprecated(since = "4.0.0", forRemoval = true) - public static boolean nullEquals(Object o1, Object o2) { - return Objects.equals(o1, o2); - } - /** * Returns the hash code of the supplied object, or 0 if a null reference is supplied. * diff --git a/core/common/io/src/test/java/org/eclipse/rdf4j/common/net/ParsedIRITest.java b/core/common/io/src/test/java/org/eclipse/rdf4j/common/net/ParsedIRITest.java index 2fa71a554bd..5c9c9053241 100644 --- a/core/common/io/src/test/java/org/eclipse/rdf4j/common/net/ParsedIRITest.java +++ b/core/common/io/src/test/java/org/eclipse/rdf4j/common/net/ParsedIRITest.java @@ -19,7 +19,6 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -60,7 +59,7 @@ public void hostWithLeadingDigit() { } @Test - public void testIncorrectIPv4() throws URISyntaxException { + public void testIncorrectIPv4() { assertThrows(URISyntaxException.class, () -> new ParsedIRI("http://127.0.0.256/")); } @@ -74,7 +73,7 @@ public void testUnknownSchemeHostProcessing() throws URISyntaxException { } @Test - public void testHttpSchemeHostProcessing() throws URISyntaxException { + public void testHttpSchemeHostProcessing() { assertThrows(URISyntaxException.class, () -> new ParsedIRI("http://385.fwk19480900/test.ttl")); } @@ -471,7 +470,7 @@ public void testSubDelimInPath() throws Exception { } @Test - public void testIllegalInPath() throws Exception { + public void testIllegalInPath() { for (char g : ILLEGAL.toCharArray()) { try { new ParsedIRI(BASE + g); @@ -499,7 +498,7 @@ public void testSubDelimsInQuery() throws Exception { } @Test - public void testIllegalInQuery() throws Exception { + public void testIllegalInQuery() { for (char g : ILLEGAL.toCharArray()) { try { new ParsedIRI(QUERY + g); @@ -527,7 +526,7 @@ public void testSubDelimsInFragment() throws Exception { } @Test - public void testIllegalInFragment() throws Exception { + public void testIllegalInFragment() { for (char g : ILLEGAL.toCharArray()) { try { new ParsedIRI(FRAGMENT + g); @@ -538,7 +537,7 @@ public void testIllegalInFragment() throws Exception { } } - private String encode(Character chr) throws UnsupportedEncodingException { + private String encode(Character chr) { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] source = Character.toString(chr).getBytes(StandardCharsets.UTF_8); for (byte c : source) { diff --git a/core/common/io/src/test/java/org/eclipse/rdf4j/common/net/ParsedURITest.java b/core/common/io/src/test/java/org/eclipse/rdf4j/common/net/ParsedURITest.java index 9fb18fd9474..338066b7433 100644 --- a/core/common/io/src/test/java/org/eclipse/rdf4j/common/net/ParsedURITest.java +++ b/core/common/io/src/test/java/org/eclipse/rdf4j/common/net/ParsedURITest.java @@ -15,8 +15,6 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.net.URISyntaxException; - import org.junit.jupiter.api.Test; /** @@ -86,150 +84,150 @@ public void resolvesAPathAbsoluteUriRelativeToABaseJarUri() { } @Test - public void testRoundTripQueryString() throws Exception { + public void testRoundTripQueryString() { assertRoundTrip( "http://localhost:8080/callimachus/pipelines/render-html.xpl?result&template=http%3A%2F%2Flocalhost%3A8080%2Fcallimachus%2Fconcept-view.xhtml%3Ftemplate%26realm%3Dhttp%3A%2F%2Flocalhost%3A8080%2F&this=http%3A%2F%2Flocalhost%3A8080%2Fsun&query=view"); } - private void assertRoundTrip(String uri) throws URISyntaxException { + private void assertRoundTrip(String uri) { assertResolves(uri, "http://example.com/", uri); } @Test - public void testParentFile() throws URISyntaxException { + public void testParentFile() { assertResolves("../dir", "http://example.com/dir/dir/file", "http://example.com/dir/dir"); } @Test - public void testRootFile() throws URISyntaxException { + public void testRootFile() { assertResolves("/dir", "http://example.com/dir/dir", "http://example.com/dir"); } @Test - public void testFrag() throws URISyntaxException { + public void testFrag() { assertResolves("#frag", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir/dir/file?qs#frag"); } @Test - public void testIdentity() throws URISyntaxException { + public void testIdentity() { assertResolves("", "http://example.com/dir/dir/file?qs", "http://example.com/dir/dir/file?qs"); } @Test - public void testOpaque() throws URISyntaxException { + public void testOpaque() { assertResolves("urn:test", "http://example.com/dir/dir/file?qs#frag", "urn:test"); } @Test - public void testFragment() throws URISyntaxException { + public void testFragment() { assertResolves("#frag2", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir/dir/file?qs#frag2"); } @Test - public void testQueryString() throws URISyntaxException { + public void testQueryString() { assertResolves("?qs2#frag", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir/dir/file?qs2#frag"); } @Test - public void testDirectory() throws URISyntaxException { + public void testDirectory() { assertResolves(".", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir/dir/"); } @Test - public void testSameDirectory() throws URISyntaxException { + public void testSameDirectory() { assertResolves("file2?qs#frag", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir/dir/file2?qs#frag"); } @Test - public void testNestedDirectory() throws URISyntaxException { + public void testNestedDirectory() { assertResolves("nested/file?qs#frag", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir/dir/nested/file?qs#frag"); } @Test - public void testParentDirectory() throws URISyntaxException { + public void testParentDirectory() { assertResolves("../file?qs#frag", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir/file?qs#frag"); } @Test - public void testOtherDirectory() throws URISyntaxException { + public void testOtherDirectory() { assertResolves("../dir2/file?qs#frag", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir/dir2/file?qs#frag"); } @Test - public void testSameAuthority() throws URISyntaxException { + public void testSameAuthority() { assertResolves("/dir2/dir/file?qs#frag", "http://example.com/dir/dir/file?qs#frag", "http://example.com/dir2/dir/file?qs#frag"); } @Test - public void testIdentityDir() throws URISyntaxException { + public void testIdentityDir() { assertResolves("", "http://example.com/dir/dir/", "http://example.com/dir/dir/"); } @Test - public void testOpaqueDir() throws URISyntaxException { + public void testOpaqueDir() { assertResolves("urn:test", "http://example.com/dir/dir/", "urn:test"); } @Test - public void testFragmentDir() throws URISyntaxException { + public void testFragmentDir() { assertResolves("#frag2", "http://example.com/dir/dir/", "http://example.com/dir/dir/#frag2"); } @Test - public void testQueryStringDir() throws URISyntaxException { + public void testQueryStringDir() { assertResolves("?qs2", "http://example.com/dir/dir/", "http://example.com/dir/dir/?qs2"); } @Test - public void testDirectoryDir() throws URISyntaxException { + public void testDirectoryDir() { assertResolves("file", "http://example.com/dir/dir/", "http://example.com/dir/dir/file"); } @Test - public void testSameDirectoryDir() throws URISyntaxException { + public void testSameDirectoryDir() { assertResolves("file2?qs#frag", "http://example.com/dir/dir/", "http://example.com/dir/dir/file2?qs#frag"); } @Test - public void testNestedDirectoryDir() throws URISyntaxException { + public void testNestedDirectoryDir() { assertResolves("nested/", "http://example.com/dir/dir/", "http://example.com/dir/dir/nested/"); } @Test - public void testNestedDirectoryFileDir() throws URISyntaxException { + public void testNestedDirectoryFileDir() { assertResolves("nested/file?qs#frag", "http://example.com/dir/dir/", "http://example.com/dir/dir/nested/file?qs#frag"); } @Test - public void testParentDirectoryDir() throws URISyntaxException { + public void testParentDirectoryDir() { assertResolves("../file?qs#frag", "http://example.com/dir/dir/", "http://example.com/dir/file?qs#frag"); } @Test - public void testOtherDirectoryDir() throws URISyntaxException { + public void testOtherDirectoryDir() { assertResolves("../dir2/", "http://example.com/dir/dir/", "http://example.com/dir/dir2/"); } @Test - public void testOtherDirectoryFileDir() throws URISyntaxException { + public void testOtherDirectoryFileDir() { assertResolves("../dir2/file?qs#frag", "http://example.com/dir/dir/", "http://example.com/dir/dir2/file?qs#frag"); } @Test - public void testSameAuthorityDir() throws URISyntaxException { + public void testSameAuthorityDir() { assertResolves("/dir2/dir/file?qs#frag", "http://example.com/dir/dir/", "http://example.com/dir2/dir/file?qs#frag"); } - private void assertResolves(String relative, String base, String absolute) throws URISyntaxException { + private void assertResolves(String relative, String base, String absolute) { assertEquals(absolute, new ParsedURI(base).resolve(relative).toString()); } diff --git a/core/common/iterator/pom.xml b/core/common/iterator/pom.xml index 664bce3ecc6..c2e21734002 100644 --- a/core/common/iterator/pom.xml +++ b/core/common/iterator/pom.xml @@ -37,10 +37,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/AbstractCloseableIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/AbstractCloseableIteration.java index 7c0162491b9..ab86f83225e 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/AbstractCloseableIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/AbstractCloseableIteration.java @@ -18,7 +18,7 @@ * Instances of this class is not safe to be accessed from multiple threads at the same time. */ @Deprecated(since = "4.1.0") -public abstract class AbstractCloseableIteration implements CloseableIteration { +public abstract class AbstractCloseableIteration implements CloseableIteration { /*-----------* * Variables * @@ -46,7 +46,7 @@ public final boolean isClosed() { * Calls {@link #handleClose()} upon first call and makes sure the resource closures are only executed once. */ @Override - public final void close() throws X { + public final void close() { if (!closed) { closed = true; handleClose(); @@ -59,6 +59,6 @@ public final void close() throws X { * * @throws X */ - protected void handleClose() throws X { + protected void handleClose() { } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIteration.java index a9cf2cf9285..c270ae65115 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIteration.java @@ -11,13 +11,14 @@ package org.eclipse.rdf4j.common.iteration; +import java.util.Iterator; import java.util.stream.Stream; /** - * An {@link Iteration} that can be closed to free resources that it is holding. CloseableIterations automatically free - * their resources when exhausted. If not read until exhaustion or if you want to make sure the iteration is properly - * closed, any code using the iterator should be placed in a try-with-resources block, closing the iteration - * automatically, e.g.: + * An {@link CloseableIteration} that can be closed to free resources that it is holding. CloseableIterations + * automatically free their resources when exhausted. If not read until exhaustion or if you want to make sure the + * iteration is properly closed, any code using the iterator should be placed in a try-with-resources block, closing the + * iteration automatically, e.g.: * *
  *
@@ -29,13 +30,13 @@
  * }
  * 
* - * @deprecated In the future this interface will stop extending {@link Iteration} and instead declare the same interface - * methods directly. The interface will also stop requiring implementations to automatically close when - * exhausted, instead making this an optional feature and requiring the user to always call close. This + * @deprecated In the future this interface will stop extending {@link CloseableIteration} and instead declare the same + * interface methods directly. The interface will also stop requiring implementations to automatically close + * when exhausted, instead making this an optional feature and requiring the user to always call close. This * interface may also be removed. */ @Deprecated(since = "4.1.0") -public interface CloseableIteration extends Iteration, AutoCloseable { +public interface CloseableIteration extends Iterator, AutoCloseable { /** * Convert the results to a Java 8 Stream. @@ -51,6 +52,6 @@ default Stream stream() { * invoking this method has no effect. */ @Override - void close() throws X; + void close(); } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIterationSpliterator.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIterationSpliterator.java index ea80e62105b..38dc7b3003d 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIterationSpliterator.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIterationSpliterator.java @@ -19,9 +19,9 @@ /** * A {@link Spliterator} implementation that wraps a {@link CloseableIteration}. */ -class CloseableIterationSpliterator extends Spliterators.AbstractSpliterator { +class CloseableIterationSpliterator extends Spliterators.AbstractSpliterator { - private final CloseableIteration iteration; + private final CloseableIteration iteration; /** * Creates a {@link Spliterator} implementation that wraps the supplied {@link CloseableIteration}. It handles @@ -30,7 +30,7 @@ class CloseableIterationSpliterator extends Spliterators * * @param iteration the iteration to wrap */ - public CloseableIterationSpliterator(CloseableIteration iteration) { + public CloseableIterationSpliterator(CloseableIteration iteration) { super(Long.MAX_VALUE, Spliterator.IMMUTABLE | Spliterator.NONNULL); this.iteration = iteration; } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIteratorIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIteratorIteration.java index b07d142c225..fa3bb0ad987 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIteratorIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/CloseableIteratorIteration.java @@ -19,7 +19,7 @@ * An Iteration that can convert an {@link Iterator} to a {@link CloseableIteration}. */ @Deprecated(since = "4.1.0") -public class CloseableIteratorIteration extends AbstractCloseableIteration { +public class CloseableIteratorIteration extends AbstractCloseableIteration { private Iterator iter; @@ -46,7 +46,7 @@ protected boolean hasIterator() { } @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (isClosed()) { return false; } @@ -59,7 +59,7 @@ public boolean hasNext() throws X { } @Override - public E next() throws X { + public E next() { if (isClosed()) { throw new NoSuchElementException("Iteration has been closed"); } @@ -68,7 +68,7 @@ public E next() throws X { } @Override - public void remove() throws X { + public void remove() { if (isClosed()) { throw new IllegalStateException("Iteration has been closed"); } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ConvertingIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ConvertingIteration.java index eace1cd3e35..6fbf65bc55f 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ConvertingIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ConvertingIteration.java @@ -19,7 +19,7 @@ * over objects of type T (the target type). */ @Deprecated(since = "4.1.0") -public abstract class ConvertingIteration extends AbstractCloseableIteration { +public abstract class ConvertingIteration extends AbstractCloseableIteration { /*-----------* * Variables * @@ -28,7 +28,7 @@ public abstract class ConvertingIteration extends Abs /** * The source type iteration. */ - private final Iteration iter; + private final CloseableIteration iter; /*--------------* * Constructors * @@ -39,7 +39,7 @@ public abstract class ConvertingIteration extends Abs * * @param iter The source type iteration for this ConvertingIteration, must not be null. */ - protected ConvertingIteration(Iteration iter) { + protected ConvertingIteration(CloseableIteration iter) { this.iter = Objects.requireNonNull(iter, "The iterator was null"); } @@ -50,16 +50,16 @@ protected ConvertingIteration(Iteration iter) { /** * Converts a source type object to a target type object. */ - protected abstract T convert(S sourceObject) throws X; + protected abstract T convert(S sourceObject); /** * Checks whether the source type iteration contains more elements. * * @return true if the source type iteration contains more elements, false otherwise. - * @throws X + * */ @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (isClosed()) { return false; } @@ -73,12 +73,12 @@ public boolean hasNext() throws X { /** * Returns the next element from the source type iteration. * - * @throws X + * * @throws java.util.NoSuchElementException If all elements have been returned. * @throws IllegalStateException If the iteration has been closed. */ @Override - public T next() throws X { + public T next() { if (isClosed()) { throw new NoSuchElementException("The iteration has been closed."); } @@ -94,7 +94,7 @@ public T next() throws X { * {@link #next}. */ @Override - public void remove() throws X { + public void remove() { if (isClosed()) { throw new IllegalStateException("The iteration has been closed."); } @@ -105,11 +105,11 @@ public void remove() throws X { * Closes this iteration as well as the wrapped iteration if it is a {@link CloseableIteration}. */ @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { - Iterations.closeCloseable(iter); + iter.close(); } } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DelayedIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DelayedIteration.java index 715c5cd7a52..012c31fe2ac 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DelayedIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DelayedIteration.java @@ -20,13 +20,13 @@ * createIteration method, which is called once when the iteration is first needed. */ @Deprecated(since = "4.1.0") -public abstract class DelayedIteration extends AbstractCloseableIteration { +public abstract class DelayedIteration extends AbstractCloseableIteration { /*-----------* * Variables * *-----------*/ - private Iteration iter; + private CloseableIteration iter; /*--------------* * Constructors * @@ -47,17 +47,17 @@ protected DelayedIteration() { * Creates the iteration that should be iterated over. This method is called only once, when the iteration is first * needed. */ - protected abstract Iteration createIteration() throws X; + protected abstract CloseableIteration createIteration(); /** * Calls the hasNext method of the underlying iteration. */ @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (isClosed()) { return false; } - Iteration resultIter = iter; + CloseableIteration resultIter = iter; if (resultIter == null) { // Underlying iterator has not yet been initialized resultIter = iter; @@ -73,11 +73,11 @@ public boolean hasNext() throws X { * Calls the next method of the underlying iteration. */ @Override - public E next() throws X { + public E next() { if (isClosed()) { throw new NoSuchElementException("Iteration has been closed"); } - Iteration resultIter = iter; + CloseableIteration resultIter = iter; if (resultIter == null) { // Underlying iterator has not yet been initialized resultIter = iter; @@ -93,11 +93,11 @@ public E next() throws X { * Calls the remove method of the underlying iteration. */ @Override - public void remove() throws X { + public void remove() { if (isClosed()) { throw new IllegalStateException("The iteration has been closed."); } - Iteration resultIter = iter; + CloseableIteration resultIter = iter; if (resultIter == null) { throw new IllegalStateException("Underlying iteration was null"); } @@ -110,13 +110,12 @@ public void remove() throws X { * {@link CloseableIteration}. */ @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { - Iteration toClose = iter; - if (toClose != null) { - Iterations.closeCloseable(toClose); + if (iter != null) { + iter.close(); } } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DistinctIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DistinctIteration.java index a66c1c15df9..c065273e45a 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DistinctIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DistinctIteration.java @@ -19,7 +19,7 @@ * An Iteration that filters any duplicate elements from an underlying iterator. */ @Deprecated(since = "4.1.0") -public class DistinctIteration extends FilterIteration { +public class DistinctIteration extends FilterIteration { /*-----------* * Variables * @@ -39,13 +39,13 @@ public class DistinctIteration extends FilterIteration iter) { + public DistinctIteration(CloseableIteration iter) { super(iter); excludeSet = makeSet(); } - public DistinctIteration(Iteration iter, Supplier> setMaker) { + public DistinctIteration(CloseableIteration iter, Supplier> setMaker) { super(iter); excludeSet = setMaker.get(); } @@ -58,7 +58,7 @@ public DistinctIteration(Iteration iter, Suppliertrue if the specified object hasn't been seen before. */ @Override - protected boolean accept(E object) throws X { + protected boolean accept(E object) { if (inExcludeSet(object)) { // object has already been returned return false; @@ -79,7 +79,7 @@ private boolean inExcludeSet(E object) { /** * @param object to put into the set */ - protected boolean add(E object) throws X { + protected boolean add(E object) { return excludeSet.add(object); } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DualUnionIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DualUnionIteration.java index 1a252992ad2..e8db59efdfb 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DualUnionIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/DualUnionIteration.java @@ -17,24 +17,24 @@ * Provides a bag union of the two provided iterations. */ @Deprecated(since = "4.1.0") -public class DualUnionIteration implements CloseableIteration { +public class DualUnionIteration implements CloseableIteration { - private CloseableIteration iteration1; - private CloseableIteration iteration2; + private CloseableIteration iteration1; + private CloseableIteration iteration2; private E nextElement; /** * Flag indicating whether this iteration has been closed. */ private boolean closed = false; - private DualUnionIteration(CloseableIteration iteration1, - CloseableIteration iteration2) { + private DualUnionIteration(CloseableIteration iteration1, + CloseableIteration iteration2) { this.iteration1 = iteration1; this.iteration2 = iteration2; } - public static CloseableIteration getWildcardInstance( - CloseableIteration leftIteration, CloseableIteration rightIteration) { + public static CloseableIteration getWildcardInstance( + CloseableIteration leftIteration, CloseableIteration rightIteration) { if (rightIteration instanceof EmptyIteration) { return leftIteration; @@ -45,8 +45,8 @@ public static CloseableIteration getWil } } - public static CloseableIteration getInstance(CloseableIteration leftIteration, - CloseableIteration rightIteration) { + public static CloseableIteration getInstance(CloseableIteration leftIteration, + CloseableIteration rightIteration) { if (rightIteration instanceof EmptyIteration) { return leftIteration; @@ -57,7 +57,7 @@ public static CloseableIteration getInstance(Clos } } - public E getNextElement() throws X { + public E getNextElement() { if (iteration1 == null && iteration2 != null) { if (iteration2.hasNext()) { return iteration2.next(); @@ -84,7 +84,7 @@ public E getNextElement() throws X { } @Override - public final boolean hasNext() throws X { + public final boolean hasNext() { if (closed) { return false; } @@ -93,7 +93,7 @@ public final boolean hasNext() throws X { } @Override - public final E next() throws X { + public final E next() { if (closed) { throw new NoSuchElementException("The iteration has been closed."); } @@ -113,7 +113,7 @@ public final E next() throws X { * @return The next element, or null if there are no more results. * @throws X If there is an issue getting the next element or closing the iteration. */ - private E lookAhead() throws X { + private E lookAhead() { if (nextElement == null) { nextElement = getNextElement(); @@ -133,7 +133,7 @@ public void remove() { } @Override - public final void close() throws X { + public final void close() { if (!closed) { closed = true; nextElement = null; diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/EmptyIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/EmptyIteration.java index e7c452c9ea9..f8c6961e781 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/EmptyIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/EmptyIteration.java @@ -21,7 +21,7 @@ * CloseableIteration directly. */ @Deprecated(since = "4.1.0") -public final class EmptyIteration extends AbstractCloseableIteration { +public final class EmptyIteration extends AbstractCloseableIteration { /*--------------* * Constructors * diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ExceptionConvertingIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ExceptionConvertingIteration.java index 29dfc421a5d..de3459baab1 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ExceptionConvertingIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ExceptionConvertingIteration.java @@ -19,7 +19,8 @@ * Subclasses need to override {@link #convert(Exception)} to do the conversion. */ @Deprecated(since = "4.1.0") -public abstract class ExceptionConvertingIteration extends AbstractCloseableIteration { +public abstract class ExceptionConvertingIteration + extends AbstractCloseableIteration { /*-----------* * Variables * @@ -28,7 +29,7 @@ public abstract class ExceptionConvertingIteration exten /** * The underlying Iteration. */ - private final Iteration iter; + private final CloseableIteration iter; /*--------------* * Constructors * @@ -40,7 +41,7 @@ public abstract class ExceptionConvertingIteration exten * @param iter The Iteration that this ExceptionConvertingIteration operates on, must not be * null. */ - protected ExceptionConvertingIteration(Iteration iter) { + protected ExceptionConvertingIteration(CloseableIteration iter) { this.iter = Objects.requireNonNull(iter, "The iterator was null"); } @@ -51,7 +52,7 @@ protected ExceptionConvertingIteration(IterationX. */ - protected abstract X convert(Exception e); + protected abstract X convert(RuntimeException e); /** * Checks whether the underlying Iteration contains more elements. @@ -60,7 +61,7 @@ protected ExceptionConvertingIteration(Iterationaccept method to indicate which objects should be returned. */ @Deprecated(since = "4.1.0") -public abstract class FilterIteration extends IterationWrapper { +public abstract class FilterIteration extends IterationWrapper { /*-----------* * Variables * @@ -33,7 +33,7 @@ public abstract class FilterIteration extends IterationW /** * @param iter */ - protected FilterIteration(Iteration iter) { + protected FilterIteration(CloseableIteration iter) { super(iter); } @@ -42,7 +42,7 @@ protected FilterIteration(Iteration iter) { *---------*/ @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (isClosed()) { return false; } @@ -56,7 +56,7 @@ public boolean hasNext() throws X { } @Override - public E next() throws X { + public E next() { if (isClosed()) { throw new NoSuchElementException("The iteration has been closed."); } @@ -73,7 +73,7 @@ public E next() throws X { } } - private void findNextElement() throws X { + private void findNextElement() { try { while (!isClosed() && nextElement == null && super.hasNext()) { E candidate = super.next(); @@ -97,10 +97,10 @@ private void findNextElement() throws X { * @return true if the object should be returned, false otherwise. * @throws X */ - protected abstract boolean accept(E object) throws X; + protected abstract boolean accept(E object); @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/InterruptTask.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/InterruptTask.java index 5db2fc53447..51c958f1a5d 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/InterruptTask.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/InterruptTask.java @@ -18,17 +18,17 @@ * * @author Jeen Broekstra */ -class InterruptTask extends TimerTask { +class InterruptTask extends TimerTask { - private final WeakReference> iterationRef; + private final WeakReference> iterationRef; - public InterruptTask(TimeLimitIteration iteration) { + public InterruptTask(TimeLimitIteration iteration) { this.iterationRef = new WeakReference<>(iteration); } @Override public void run() { - TimeLimitIteration iteration = iterationRef.get(); + TimeLimitIteration iteration = iterationRef.get(); if (iteration != null) { iteration.interrupt(); } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IntersectIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IntersectIteration.java index dda74c1f478..55b495908b8 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IntersectIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IntersectIteration.java @@ -23,13 +23,13 @@ * bit more overhead as it adds a second hash table lookup. */ @Deprecated(since = "4.1.0") -public class IntersectIteration extends FilterIteration { +public class IntersectIteration extends FilterIteration { /*-----------* * Variables * *-----------*/ - protected final Iteration arg2; + protected final CloseableIteration arg2; private final boolean distinct; @@ -50,11 +50,11 @@ public class IntersectIteration extends FilterIteration< * @param arg1 An Iteration containing the first set of elements. * @param arg2 An Iteration containing the second set of elements. */ - public IntersectIteration(Iteration arg1, Iteration arg2) { + public IntersectIteration(CloseableIteration arg1, CloseableIteration arg2) { this(arg1, arg2, false); } - public IntersectIteration(Iteration arg1, Iteration arg2, + public IntersectIteration(CloseableIteration arg1, CloseableIteration arg2, Supplier> setMaker) { this(arg1, arg2, false, setMaker); } @@ -66,7 +66,7 @@ public IntersectIteration(Iteration arg1, Iteration arg1, Iteration arg2, + public IntersectIteration(CloseableIteration arg1, CloseableIteration arg2, boolean distinct) { super(arg1); @@ -85,7 +85,7 @@ public IntersectIteration(Iteration arg1, Iteration arg1, Iteration arg2, + public IntersectIteration(CloseableIteration arg1, CloseableIteration arg2, boolean distinct, Supplier> setMaker) { super(arg1); @@ -105,7 +105,7 @@ public IntersectIteration(Iteration arg1, Iterationtrue if the object is in the set of elements of the second argument. */ @Override - protected boolean accept(E object) throws X { + protected boolean accept(E object) { if (!initialized) { // Build set of elements-to-include from second argument includeSet = Iterations.asSet(arg2); @@ -128,7 +128,7 @@ protected boolean accept(E object) throws X { } // this method does not seem to "addSecondSet" since the second set seems to be ignored - public Set addSecondSet(Iteration arg2, Set set) throws X { + public Set addSecondSet(CloseableIteration arg2, Set set) { return Iterations.addAll(arg2, setMaker.get()); } @@ -145,11 +145,13 @@ protected Set makeSet() { } @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { - Iterations.closeCloseable(arg2); + if (arg2 != null) { + arg2.close(); + } } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/Iteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/Iteration.java deleted file mode 100644 index 0768f40662a..00000000000 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/Iteration.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ - -package org.eclipse.rdf4j.common.iteration; - -import java.util.NoSuchElementException; -import java.util.stream.Stream; - -/** - * An Iteration is a typed Iterator-like object that can throw (typed) Exceptions while iterating. This is used in cases - * where the iteration is lazy and evaluates over a (remote) connection, for example accessing a database. In such cases - * an error can occur at any time and needs to be communicated through a checked exception, something - * {@link java.util.Iterator} can not do (it can only throw {@link RuntimeException}s. - * - * @param Object type of objects contained in the iteration. - * @param Exception type that is thrown when a problem occurs during iteration. - * @author jeen - * @author Herko ter Horst - * @see java.util.Iterator - * @deprecated For performance and simplification the Iteration interface is deprecated and will be removed in 5.0.0. - * Use CloseableIteration instead, even if your iteration doesn't require AutoCloseable. - */ -@Deprecated(since = "4.1.0", forRemoval = true) -public interface Iteration { - - /** - * Returns true if the iteration has more elements. (In other words, returns true if - * {@link #next} would return an element rather than throwing a NoSuchElementException.) - * - * @return true if the iteration has more elements. - * @throws X - */ - boolean hasNext() throws X; - - /** - * Returns the next element in the iteration. - * - * @return the next element in the iteration. - * @throws NoSuchElementException if the iteration has no more elements or if it has been closed. - */ - E next() throws X; - - /** - * Removes from the underlying collection the last element returned by the iteration (optional operation). This - * method can be called only once per call to next. - * - * @throws UnsupportedOperationException if the remove operation is not supported by this Iteration. - * @throws IllegalStateException If the Iteration has been closed, or if next() has not yet been - * called, or remove() has already been called after the last call - * to next(). - */ - void remove() throws X; - - /** - * Convert the results to a Java 8 Stream. If this iteration implements CloseableIteration it should be closed (by - * calling Stream#close() or using try-with-resource) if it is not fully consumed. - * - * @return stream - */ - default Stream stream() { - return Iterations.stream(this); - } -} diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IterationSpliterator.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IterationSpliterator.java index 65ec8eee032..c4ef42ca008 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IterationSpliterator.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IterationSpliterator.java @@ -16,25 +16,25 @@ import java.util.function.Consumer; /** - * A {@link Spliterator} implementation that wraps an {@link Iteration}. It handles occurrence of checked exceptions by - * wrapping them in RuntimeExceptions, and in addition ensures that the wrapped Iteration is closed when exhausted (if - * it's a {@link CloseableIteration}). + * A {@link Spliterator} implementation that wraps an {@link CloseableIteration}. It handles occurrence of checked + * exceptions by wrapping them in RuntimeExceptions, and in addition ensures that the wrapped Iteration is closed when + * exhausted (if it's a {@link CloseableIteration}). * * @author Jeen Broekstra */ @Deprecated(since = "4.1.0") public class IterationSpliterator extends Spliterators.AbstractSpliterator { - private final Iteration iteration; + private final CloseableIteration iteration; /** - * Creates a {@link Spliterator} implementation that wraps the supplied {@link Iteration}. It handles occurrence of - * checked exceptions by wrapping them in RuntimeExceptions, and in addition ensures that the wrapped Iteration is - * closed when exhausted (if it's a {@link CloseableIteration}). + * Creates a {@link Spliterator} implementation that wraps the supplied {@link CloseableIteration}. It handles + * occurrence of checked exceptions by wrapping them in RuntimeExceptions, and in addition ensures that the wrapped + * Iteration is closed when exhausted (if it's a {@link CloseableIteration}). * * @param iteration the iteration to wrap */ - public IterationSpliterator(final Iteration iteration) { + public IterationSpliterator(final CloseableIteration iteration) { super(Long.MAX_VALUE, Spliterator.IMMUTABLE | Spliterator.NONNULL); this.iteration = iteration; } @@ -54,18 +54,11 @@ public boolean tryAdvance(Consumer action) { return true; } return false; - } catch (Exception e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } - throw new RuntimeException(e); } finally { if (needsToBeClosed) { try { - Iterations.closeCloseable(iteration); + if (iteration != null) + iteration.close(); } catch (Exception ignored) { } } @@ -79,17 +72,10 @@ public void forEachRemaining(final Consumer action) { while (iteration.hasNext()) { action.accept(iteration.next()); } - } catch (Exception e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } - throw new RuntimeException(e); } finally { try { - Iterations.closeCloseable(iteration); + if (iteration != null) + iteration.close(); } catch (Exception ignored) { } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IterationWrapper.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IterationWrapper.java index 4c3243e0833..504acb4a8f4 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IterationWrapper.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IterationWrapper.java @@ -19,7 +19,7 @@ * IterationWrapper should override some of these methods and may also provide additional methods and fields. */ @Deprecated(since = "4.1.0") -public class IterationWrapper extends AbstractCloseableIteration { +public class IterationWrapper extends AbstractCloseableIteration { /*-----------* * Variables * @@ -31,7 +31,7 @@ public class IterationWrapper extends AbstractCloseableI * @deprecated This will be changed to private, possibly with an accessor in future. Do not rely on it. */ @Deprecated(since = "4.1.0") - protected final Iteration wrappedIter; + protected final CloseableIteration wrappedIter; /*--------------* * Constructors * @@ -42,7 +42,7 @@ public class IterationWrapper extends AbstractCloseableI * * @param iter The wrapped Iteration for this IterationWrapper, must not be null. */ - protected IterationWrapper(Iteration iter) { + protected IterationWrapper(CloseableIteration iter) { assert iter != null; wrappedIter = iter; } @@ -57,7 +57,7 @@ protected IterationWrapper(Iteration iter) { * @return true if the wrapped Iteration contains more elements, false otherwise. */ @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (isClosed()) { return false; } else if (Thread.currentThread().isInterrupted()) { @@ -77,7 +77,7 @@ public boolean hasNext() throws X { * @throws java.util.NoSuchElementException If all elements have been returned or it has been closed. */ @Override - public E next() throws X { + public E next() { if (isClosed()) { throw new NoSuchElementException("The iteration has been closed."); } else if (Thread.currentThread().isInterrupted()) { @@ -101,7 +101,7 @@ public E next() throws X { * {@link #next}. */ @Override - public void remove() throws X { + public void remove() { if (isClosed()) { throw new IllegalStateException("The iteration has been closed."); } else if (Thread.currentThread().isInterrupted()) { @@ -120,11 +120,11 @@ public void remove() throws X { * Closes this Iteration and also closes the wrapped Iteration if it is a {@link CloseableIteration}. */ @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { - Iterations.closeCloseable(wrappedIter); + wrappedIter.close(); } } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/Iterations.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/Iterations.java index 14d5ea67611..28562e8246e 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/Iterations.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/Iterations.java @@ -15,7 +15,6 @@ import java.util.Collection; import java.util.List; import java.util.Set; -import java.util.Spliterator; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -28,28 +27,13 @@ @Deprecated(since = "4.1.0") public class Iterations { - /** - * Get a List containing all elements obtained from the specified iteration. - * - * @param iter the iteration to get the elements from - * @return a List containing all elements obtained from the specified iteration. - */ - @Deprecated(since = "4.1.0", forRemoval = true) - public static List asList(Iteration iter) throws X { - // stream.collect is slightly slower than addAll for lists - List list = new ArrayList<>(); - - // addAll closes the iteration - return addAll(iter, list); - } - /** * Get a List containing all elements obtained from the specified iteration. * * @param iter the {@link CloseableIteration} to get the elements from * @return a List containing all elements obtained from the specified iteration. */ - public static List asList(CloseableIteration iter) throws X { + public static List asList(CloseableIteration iter) { try (iter) { // stream.collect is slightly slower than addAll for lists List list = new ArrayList<>(); @@ -59,54 +43,18 @@ public static List asList(CloseableIteration Set asSet(Iteration iter) throws X { - try (Stream stream = iter.stream()) { - return stream.collect(Collectors.toSet()); - } - } - /** * Get a Set containing all elements obtained from the specified iteration. * * @param iter the {@link CloseableIteration} to get the elements from * @return a Set containing all elements obtained from the specified iteration. */ - public static Set asSet(CloseableIteration iter) throws X { + public static Set asSet(CloseableIteration iter) { try (Stream stream = iter.stream()) { return stream.collect(Collectors.toSet()); } } - /** - * Adds all elements from the supplied iteration to the specified collection. If the supplied iteration is an - * instance of {@link CloseableIteration} it is automatically closed after consumption. - * - * @param iter An iteration containing elements to add to the container. If the iteration is an instance of - * {@link CloseableIteration} it is automatically closed after consumption. - * @param collection The collection to add the elements to. - * @return The collection object that was supplied to this method. - */ - @Deprecated(since = "4.1.0", forRemoval = true) - public static > C addAll(Iteration iter, - C collection) throws X { - try { - while (iter.hasNext()) { - collection.add(iter.next()); - } - } finally { - closeCloseable(iter); - } - - return collection; - } - /** * Adds all elements from the supplied {@link CloseableIteration} to the specified collection then closes the * {@link CloseableIteration}. @@ -115,40 +63,15 @@ public static > C addAll(Iterati * @param collection The collection to add the elements to. * @return The collection object that was supplied to this method. */ - public static > C addAll(CloseableIteration iter, - C collection) throws X { + public static > C addAll(CloseableIteration iter, + C collection) { try (iter) { while (iter.hasNext()) { collection.add(iter.next()); } - return collection; } - } - - /** - * Get a sequential {@link Stream} with the supplied {@link Iteration} as its source. If the source iteration is a - * {@link CloseableIteration}, it will be automatically closed by the stream when done. Any checked exceptions - * thrown at any point during stream processing will be propagated wrapped in a {@link RuntimeException}. - * - * @param iteration a source {@link Iteration} for the stream. - * @return a sequential {@link Stream} object which can be used to process the data from the source iteration. - */ - @Deprecated(since = "4.1.0", forRemoval = true) - public static Stream stream(Iteration iteration) { - Spliterator spliterator = new IterationSpliterator<>(iteration); - return StreamSupport.stream(spliterator, false).onClose(() -> { - try { - Iterations.closeCloseable(iteration); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - throw new RuntimeException(e); - } - }); + return collection; } /** @@ -159,7 +82,7 @@ public static Stream stream(Iteration iteration) * @param iteration a source {@link CloseableIteration} for the stream. * @return a sequential {@link Stream} object which can be used to process the data from the source iteration. */ - public static Stream stream(CloseableIteration iteration) { + public static Stream stream(CloseableIteration iteration) { return StreamSupport .stream(new CloseableIterationSpliterator<>(iteration), false) .onClose(() -> { @@ -176,34 +99,6 @@ public static Stream stream(CloseableIteration it }); } - /** - * Closes the supplied iteration if it is an instance of {@link CloseableIteration}, otherwise the request is - * ignored. - * - * @param iteration The iteration that should be closed. - */ - @Deprecated(since = "4.1.0", forRemoval = true) - public static void closeCloseable(Iteration iteration) throws X { - if (iteration instanceof CloseableIteration) { - ((CloseableIteration) iteration).close(); - } - } - - /** - * Converts an iteration to a string by concatenating all of the string representations of objects in the Iteration, - * divided by a separator. - * - * @param iteration An iteration over arbitrary objects that are expected to implement {@link Object#toString()}. - * @param separator The separator to insert between the object strings. - * @return A String representation of the objects provided by the supplied iteration. - */ - @Deprecated(since = "4.1.0", forRemoval = true) - public static String toString(Iteration iteration, String separator) throws X { - StringBuilder sb = new StringBuilder(); - toString(iteration, separator, sb); - return sb.toString(); - } - /** * Converts a {@link CloseableIteration} to a string by concatenating all the string representations of objects in * the iteration, divided by a separator. @@ -213,7 +108,7 @@ public static String toString(Iteration iteration, S * @param separator The separator to insert between the object strings. * @return A String representation of the objects provided by the supplied iteration. */ - public static String toString(CloseableIteration iteration, String separator) throws X { + public static String toString(CloseableIteration iteration, String separator) { try (iteration) { StringBuilder sb = new StringBuilder(); toString(iteration, separator, sb); @@ -221,27 +116,6 @@ public static String toString(CloseableIteration ite } } - /** - * Converts an iteration to a string by concatenating all the string representations of objects in the Iteration, - * divided by a separator. - * - * @param iteration An iteration over arbitrary objects that are expected to implement {@link Object#toString()}. - * @param separator The separator to insert between the object strings. - * @param sb A StringBuilder to append the iteration string to. - */ - @Deprecated(since = "4.1.0", forRemoval = true) - public static void toString(Iteration iteration, String separator, StringBuilder sb) - throws X { - while (iteration.hasNext()) { - sb.append(iteration.next()); - - if (iteration.hasNext()) { - sb.append(separator); - } - } - - } - /** * Converts a {@link CloseableIteration} to a string by concatenating all the string representations of objects in * the iteration, divided by a separator. @@ -251,7 +125,7 @@ public static void toString(Iteration iteration, Str * @param separator The separator to insert between the object strings. * @param sb A StringBuilder to append the iteration string to. */ - public static void toString(CloseableIteration iteration, String separator, + public static void toString(CloseableIteration iteration, String separator, StringBuilder sb) throws X { try (iteration) { @@ -273,25 +147,8 @@ public static void toString(CloseableIteration itera * @param setMaker the Supplier that constructs a new set * @return a Set containing all elements obtained from the specified iteration. */ - @Deprecated(since = "4.1.0", forRemoval = true) - public static Set asSet(Iteration iteration, - Supplier> setMaker) throws X { - Set set = setMaker.get(); - while (iteration.hasNext()) { - set.add(iteration.next()); - } - return set; - } - - /** - * Get a Set containing all elements obtained from the specified iteration. - * - * @param iteration the iteration to get the elements from - * @param setMaker the Supplier that constructs a new set - * @return a Set containing all elements obtained from the specified iteration. - */ - public static Set asSet(CloseableIteration iteration, - Supplier> setMaker) throws X { + public static Set asSet(CloseableIteration iteration, + Supplier> setMaker) { Set set = setMaker.get(); while (iteration.hasNext()) { set.add(iteration.next()); diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IteratorIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IteratorIteration.java index 0fab8146c31..9a5e45e6b46 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IteratorIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/IteratorIteration.java @@ -14,10 +14,10 @@ import java.util.Iterator; /** - * An Iteration that can convert an {@link Iterator} to a {@link Iteration}. + * An Iteration that can convert an {@link Iterator} to a {@link CloseableIteration}. */ @Deprecated(since = "4.1.0") -public class IteratorIteration implements Iteration { +public class IteratorIteration implements CloseableIteration { private final Iterator iter; @@ -40,4 +40,9 @@ public E next() { public void remove() { iter.remove(); } + + @Override + public void close() { + + } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/LimitIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/LimitIteration.java index 164e4b3c8d0..e3280077856 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/LimitIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/LimitIteration.java @@ -18,7 +18,7 @@ * class returns the first limit elements from the underlying Iteration and drops the rest. */ @Deprecated(since = "4.1.0") -public class LimitIteration extends IterationWrapper { +public class LimitIteration extends IterationWrapper { /*-----------* * Variables * @@ -44,7 +44,7 @@ public class LimitIteration extends IterationWrappernull. * @param limit The number of query answers to return, must be >= 0. */ - public LimitIteration(Iteration iter, long limit) { + public LimitIteration(CloseableIteration iter, long limit) { super(iter); assert iter != null; @@ -59,7 +59,7 @@ public LimitIteration(Iteration iter, long limit) { *---------*/ @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (isClosed()) { return false; } @@ -72,7 +72,7 @@ public boolean hasNext() throws X { } @Override - public E next() throws X { + public E next() { if (isClosed()) { throw new NoSuchElementException("The iteration has been closed."); } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/LookAheadIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/LookAheadIteration.java index f860ed3f0c2..03b14dbed0b 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/LookAheadIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/LookAheadIteration.java @@ -19,7 +19,7 @@ * the java.util.Iteration interface. */ @Deprecated(since = "4.1.0") -public abstract class LookAheadIteration extends AbstractCloseableIteration { +public abstract class LookAheadIteration extends AbstractCloseableIteration { /*-----------* * Variables * @@ -43,10 +43,10 @@ protected LookAheadIteration() { * * @return The next element, or null if no more elements are available. */ - protected abstract E getNextElement() throws X; + protected abstract E getNextElement(); @Override - public final boolean hasNext() throws X { + public final boolean hasNext() { if (isClosed()) { return false; } @@ -55,7 +55,7 @@ public final boolean hasNext() throws X { } @Override - public final E next() throws X { + public final E next() { if (isClosed()) { throw new NoSuchElementException("The iteration has been closed."); } @@ -75,7 +75,7 @@ public final E next() throws X { * @return The next element, or null if there are no more results. * @throws X If there is an issue getting the next element or closing the iteration. */ - private E lookAhead() throws X { + private E lookAhead() { if (nextElement == null) { nextElement = getNextElement(); @@ -95,7 +95,7 @@ public void remove() { } @Override - protected void handleClose() throws X { + protected void handleClose() { nextElement = null; } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/MinusIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/MinusIteration.java index 13058e3749c..1df41bdddbc 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/MinusIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/MinusIteration.java @@ -23,13 +23,13 @@ * bit more overhead as it adds a second hash table lookup. */ @Deprecated(since = "4.1.0") -public class MinusIteration extends FilterIteration { +public class MinusIteration extends FilterIteration { /*-----------* * Variables * *-----------*/ - private final Iteration rightArg; + private final CloseableIteration rightArg; private final boolean distinct; @@ -50,7 +50,7 @@ public class MinusIteration extends FilterIteration leftArg, Iteration rightArg) { + public MinusIteration(CloseableIteration leftArg, CloseableIteration rightArg) { this(leftArg, rightArg, false); } @@ -62,7 +62,8 @@ public MinusIteration(Iteration leftArg, Iteration leftArg, Iteration rightArg, boolean distinct) { + public MinusIteration(CloseableIteration leftArg, CloseableIteration rightArg, + boolean distinct) { super(leftArg); assert rightArg != null; @@ -81,7 +82,8 @@ public MinusIteration(Iteration leftArg, Iteration leftArg, Iteration rightArg, boolean distinct, + public MinusIteration(CloseableIteration leftArg, CloseableIteration rightArg, + boolean distinct, Supplier> setMaker) { super(leftArg); @@ -98,7 +100,7 @@ public MinusIteration(Iteration leftArg, Iterationoffset elements from an underlying Iteration. */ @Deprecated(since = "4.1.0") -public class OffsetIteration extends FilterIteration { +public class OffsetIteration extends FilterIteration { /*-----------* * Variables * @@ -41,7 +41,7 @@ public class OffsetIteration extends FilterIterationnull. * @param offset The number of elements to skip, must be larger than or equal to 0. */ - public OffsetIteration(Iteration iter, long offset) { + public OffsetIteration(CloseableIteration iter, long offset) { super(iter); assert offset >= 0; diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/QueueIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/QueueIteration.java index 87a51e129d5..b3b11a59ea0 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/QueueIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/QueueIteration.java @@ -25,7 +25,7 @@ * @author James Leigh */ @Deprecated(since = "4.1.0") -public abstract class QueueIteration extends LookAheadIteration { +public abstract class QueueIteration extends LookAheadIteration { private final AtomicBoolean done = new AtomicBoolean(false); @@ -44,36 +44,6 @@ protected QueueIteration(int capacity) { this(capacity, false); } - /** - * Creates an QueueIteration with the given (fixed) capacity and default access policy. - * - * @param capacity the capacity of this queue - * @deprecated WeakReference is no longer supported as a way to automatically close this iteration. The recommended - * approach to automatically closing an iteration on garbage collection is to use a - * {@link java.lang.ref.Cleaner}. - */ - @Deprecated(since = "4.1.2", forRemoval = true) - protected QueueIteration(int capacity, WeakReference callerRef) { - this(capacity, false, callerRef); - } - - /** - * Creates an QueueIteration with the given (fixed) capacity and the specified access policy. - * - * @param capacity the capacity of this queue - * @param fair if true then queue accesses for threads blocked on insertion or removal, are processed - * in FIFO order; if false the access order is unspecified. - * @deprecated WeakReference is no longer supported as a way to automatically close this iteration. The recommended - * approach to automatically closing an iteration on garbage collection is to use a - * {@link java.lang.ref.Cleaner}. - */ - @Deprecated(since = "4.1.2", forRemoval = true) - protected QueueIteration(int capacity, boolean fair, WeakReference callerRef) { - super(); - assert callerRef == null; - this.queue = new ArrayBlockingQueue<>(capacity, fair); - } - /** * Creates an QueueIteration with the given (fixed) capacity and the specified access policy. * @@ -86,23 +56,6 @@ protected QueueIteration(int capacity, boolean fair) { this.queue = new ArrayBlockingQueue<>(capacity, fair); } - /** - * Creates an QueueIteration with the given {@link BlockingQueue} as its backing queue.
- * It may not be threadsafe to modify or access the given {@link BlockingQueue} from other locations. This method - * only enables the default {@link ArrayBlockingQueue} to be overridden. - * - * @param queue A BlockingQueue that is not used in other locations, but will be used as the backing Queue - * implementation for this cursor. - * @deprecated WeakReference is no longer supported as a way to automatically close this iteration. The recommended - * approach to automatically closing an iteration on garbage collection is to use a - * {@link java.lang.ref.Cleaner}. - */ - @Deprecated(since = "4.1.2", forRemoval = true) - protected QueueIteration(BlockingQueue queue, WeakReference callerRef) { - assert callerRef == null; - this.queue = queue; - } - /** * Creates an QueueIteration with the given {@link BlockingQueue} as its backing queue.
* It may not be threadsafe to modify or access the given {@link BlockingQueue} from other locations. This method @@ -165,7 +118,7 @@ public void done() { * Returns the next item in the queue, which may be null, or throws an exception. */ @Override - public E getNextElement() throws T { + public E getNextElement() { if (isClosed()) { return null; } @@ -202,7 +155,7 @@ public E getNextElement() throws T { } @Override - public void handleClose() throws T { + public void handleClose() { try { super.handleClose(); } finally { diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ReducedIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ReducedIteration.java index 17aa702f3eb..5e62199dfc4 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ReducedIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/ReducedIteration.java @@ -16,11 +16,11 @@ * @author Arjohn Kampman */ @Deprecated(since = "4.1.0") -public class ReducedIteration extends FilterIteration { +public class ReducedIteration extends FilterIteration { private E previousObject; - public ReducedIteration(Iteration delegate) { + public ReducedIteration(CloseableIteration delegate) { super(delegate); } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/SilentIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/SilentIteration.java index dab6af1d70c..36b9d03d0c8 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/SilentIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/SilentIteration.java @@ -22,22 +22,19 @@ * @author Jeen Broekstra */ @Deprecated(since = "4.1.0") -public class SilentIteration extends IterationWrapper { +public class SilentIteration extends IterationWrapper { private static final Logger logger = LoggerFactory.getLogger(SilentIteration.class); - public SilentIteration(CloseableIteration iter) { + public SilentIteration(CloseableIteration iter) { super(iter); } @Override - public boolean hasNext() throws E { + public boolean hasNext() { try { return super.hasNext(); } catch (Exception e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } if (logger.isTraceEnabled()) { logger.trace("Suppressed error in SILENT iteration: " + e.getMessage(), e); } @@ -46,16 +43,13 @@ public boolean hasNext() throws E { } @Override - public T next() throws E { + public T next() { try { return super.next(); } catch (NoSuchElementException e) { // pass through throw e; } catch (Exception e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } if (logger.isTraceEnabled()) { logger.trace("Converted error in SILENT iteration: " + e.getMessage(), e); } @@ -64,13 +58,10 @@ public T next() throws E { } @Override - protected void handleClose() throws E { + protected void handleClose() { try { super.handleClose(); } catch (Exception e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } if (logger.isTraceEnabled()) { logger.trace("Suppressed error in SILENT iteration: " + e.getMessage(), e); } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/SingletonIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/SingletonIteration.java index 53e99a6ebb5..154551cfffa 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/SingletonIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/SingletonIteration.java @@ -17,7 +17,7 @@ * An Iteration that contains exactly one element. */ @Deprecated(since = "4.1.0") -public class SingletonIteration extends AbstractCloseableIteration { +public class SingletonIteration extends AbstractCloseableIteration { /*-----------* * Variables * @@ -46,7 +46,7 @@ public boolean hasNext() { } @Override - public E next() throws X { + public E next() { E result = value; value = null; if (result == null) { @@ -62,7 +62,7 @@ public void remove() { } @Override - protected void handleClose() throws X { + protected void handleClose() { value = null; } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/TimeLimitIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/TimeLimitIteration.java index 760fcf5f476..f7f3a043383 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/TimeLimitIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/TimeLimitIteration.java @@ -21,17 +21,17 @@ * @author Arjohn Kampman */ @Deprecated(since = "4.1.0") -public abstract class TimeLimitIteration extends IterationWrapper { +public abstract class TimeLimitIteration extends IterationWrapper { private static final Timer timer = new Timer("TimeLimitIteration", true); private final Logger logger = LoggerFactory.getLogger(this.getClass()); - private final InterruptTask interruptTask; + private final InterruptTask interruptTask; private final AtomicBoolean isInterrupted = new AtomicBoolean(false); - protected TimeLimitIteration(Iteration iter, long timeLimit) { + protected TimeLimitIteration(CloseableIteration iter, long timeLimit) { super(iter); assert timeLimit > 0 : "time limit must be a positive number, is: " + timeLimit; @@ -42,7 +42,7 @@ protected TimeLimitIteration(Iteration iter, long time } @Override - public boolean hasNext() throws X { + public boolean hasNext() { checkInterrupted(); if (isClosed()) { return false; @@ -60,7 +60,7 @@ public boolean hasNext() throws X { } @Override - public E next() throws X { + public E next() { checkInterrupted(); if (isClosed()) { throw new NoSuchElementException("The iteration has been closed."); @@ -76,7 +76,7 @@ public E next() throws X { } @Override - public void remove() throws X { + public void remove() { checkInterrupted(); if (isClosed()) { throw new IllegalStateException("The iteration has been closed."); @@ -92,7 +92,7 @@ public void remove() throws X { } @Override - protected void handleClose() throws X { + protected void handleClose() { try { interruptTask.cancel(); } finally { @@ -100,7 +100,7 @@ protected void handleClose() throws X { } } - private void checkInterrupted() throws X { + private void checkInterrupted() { if (isInterrupted.get()) { try { throwInterruptedException(); @@ -121,9 +121,8 @@ private void checkInterrupted() throws X { * If the iteration is interrupted by its time limit, this method is called to generate and throw the appropriate * exception. * - * @throws X The generic class of exceptions thrown by this method. */ - protected abstract void throwInterruptedException() throws X; + protected abstract void throwInterruptedException(); /** * Users of this class must call this method to interrupt the execution at the next available point. It does not diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/UnionIteration.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/UnionIteration.java index db2aecbc685..334cfa0ad7a 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/UnionIteration.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iteration/UnionIteration.java @@ -22,15 +22,15 @@ * UnionIteration does not filter duplicate objects. */ @Deprecated(since = "4.1.0") -public class UnionIteration extends LookAheadIteration { +public class UnionIteration extends LookAheadIteration { /*-----------* * Variables * *-----------*/ - private final Iterator> argIter; + private final Iterator> argIter; - private Iteration currentIter; + private CloseableIteration currentIter; /*--------------* * Constructors * @@ -42,7 +42,7 @@ public class UnionIteration extends LookAheadIteration... args) { + public UnionIteration(CloseableIteration... args) { this(Arrays.asList(args)); } @@ -51,7 +51,7 @@ public UnionIteration(Iteration... args) { * * @param args The Iterations containing the elements to iterate over. */ - public UnionIteration(Iterable> args) { + public UnionIteration(Iterable> args) { argIter = args.iterator(); // Initialize with empty iteration @@ -63,20 +63,22 @@ public UnionIteration(Iterable> args) { *--------------*/ @Override - protected E getNextElement() throws X { + protected E getNextElement() { if (isClosed()) { return null; } while (true) { - Iteration nextCurrentIter = currentIter; + CloseableIteration nextCurrentIter = currentIter; if (nextCurrentIter != null && nextCurrentIter.hasNext()) { return nextCurrentIter.next(); } // Current Iteration exhausted, continue with the next one - Iterations.closeCloseable(nextCurrentIter); + if (nextCurrentIter != null) { + nextCurrentIter.close(); + } if (argIter.hasNext()) { currentIter = argIter.next(); @@ -88,7 +90,7 @@ protected E getNextElement() throws X { } @Override - protected void handleClose() throws X { + protected void handleClose() { try { // Close this iteration, this will prevent lookAhead() from calling // getNextElement() again @@ -98,11 +100,11 @@ protected void handleClose() throws X { List collectedExceptions = new ArrayList<>(); while (argIter.hasNext()) { try { - Iterations.closeCloseable(argIter.next()); - } catch (Throwable e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); + CloseableIteration next = argIter.next(); + if (next != null) { + next.close(); } + } catch (Throwable e) { collectedExceptions.add(e); } } @@ -110,7 +112,9 @@ protected void handleClose() throws X { throw new UndeclaredThrowableException(collectedExceptions.get(0)); } } finally { - Iterations.closeCloseable(currentIter); + if (currentIter != null) { + currentIter.close(); + } } } } diff --git a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iterator/CloseableIterationIterator.java b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iterator/CloseableIterationIterator.java index 45458ddbe5e..8aa4d36c618 100644 --- a/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iterator/CloseableIterationIterator.java +++ b/core/common/iterator/src/main/java/org/eclipse/rdf4j/common/iterator/CloseableIterationIterator.java @@ -11,11 +11,9 @@ package org.eclipse.rdf4j.common.iterator; import java.io.Closeable; -import java.io.IOException; import java.util.Iterator; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; /** * Wraps a {@link CloseableIteration} as an {@link Iterator}. @@ -24,33 +22,9 @@ */ public class CloseableIterationIterator implements Iterator, Closeable { - private final CloseableIteration iteration; + private final CloseableIteration iteration; - @Deprecated(since = "4.1.0", forRemoval = true) - public CloseableIterationIterator(Iteration iteration) { - this.iteration = new CloseableIteration<>() { - @Override - public boolean hasNext() throws RuntimeException { - return iteration.hasNext(); - } - - @Override - public E next() throws RuntimeException { - return iteration.next(); - } - - @Override - public void remove() throws RuntimeException { - iteration.remove(); - } - - @Override - public void close() throws RuntimeException { - } - }; - } - - public CloseableIterationIterator(CloseableIteration iteration) { + public CloseableIterationIterator(CloseableIteration iteration) { this.iteration = iteration; } @@ -58,11 +32,8 @@ public CloseableIterationIterator(CloseableIteration List asList(Iterator iter) { - List result = new ArrayList<>(); - addAll(iter, result); - return result; - } - - /** - * Adds all elements from the supplied iterator to the specified collection. - * - * @param iter An iterator containing elements to add to the container. - * @param collection The collection to add the elements to. - * @return The collection object that was supplied to this method. - */ - public static > C addAll(Iterator iter, C collection) { - while (iter.hasNext()) { - collection.add(iter.next()); - } - - return collection; - } - - /** - * Converts an iterator to a string by concatenating all of the string representations of objects in the iterator, - * divided by a separator. - * - * @param iter An iterator over arbitrary objects that are expected to implement {@link Object#toString()}. - * @param separator The separator to insert between the object strings. - * @return A String representation of the objects provided by the supplied iterator. - */ - public static String toString(Iterator iter, String separator) { - StringBuilder sb = new StringBuilder(); - toString(iter, separator, sb); - return sb.toString(); - } - - /** - * Converts an iterator to a string by concatenating all of the string representations of objects in the iterator, - * divided by a separator. - * - * @param iter An iterator over arbitrary objects that are expected to implement {@link Object#toString()}. - * @param separator The separator to insert between the object strings. - * @param sb A StringBuilder to append the iterator string to. - */ - public static void toString(Iterator iter, String separator, StringBuilder sb) { - while (iter.hasNext()) { - sb.append(iter.next()); - - if (iter.hasNext()) { - sb.append(separator); - } - } - } - - /** - * Closes the given iterator if it implements {@link java.io.Closeable} else do nothing. - * - * @param iter The iterator to close. - * @throws IOException If an underlying I/O error occurs. - */ - public static void close(Iterator iter) throws IOException { - if (iter instanceof Closeable) { - ((Closeable) iter).close(); - } - } - - /** - * Closes the given iterator, swallowing any IOExceptions, if it implements {@link java.io.Closeable} else do - * nothing. - * - * @param iter The iterator to close. - */ - public static void closeSilently(Iterator iter) { - if (iter instanceof Closeable) { - try { - ((Closeable) iter).close(); - } catch (IOException ioe) { - // ignore - } - } - } -} diff --git a/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/AutoClosingIterationTest.java b/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/AutoClosingIterationTest.java index 92f403d7927..6b14d982e53 100644 --- a/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/AutoClosingIterationTest.java +++ b/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/AutoClosingIterationTest.java @@ -57,7 +57,7 @@ public void testClosingStreamWithAssertionError() { } @Test - public void testClosingStreamWithAssertionErrorFinally() throws Exception { + public void testClosingStreamWithAssertionErrorFinally() { CloseableIterationForTesting iterator = getIterator(Arrays.asList("a", "b", "c")); @@ -81,7 +81,7 @@ private CloseableIterationForTesting getIterator(List list) { return new CloseableIterationForTesting(list); } - static class CloseableIterationForTesting implements CloseableIteration { + static class CloseableIterationForTesting implements CloseableIteration { public boolean closed = false; Iterator iterator; @@ -91,22 +91,22 @@ public CloseableIterationForTesting(List list) { } @Override - public void close() throws Exception { + public void close() { closed = true; } @Override - public boolean hasNext() throws Exception { + public boolean hasNext() { return iterator.hasNext(); } @Override - public String next() throws Exception { + public String next() { return iterator.next(); } @Override - public void remove() throws Exception { + public void remove() { } } diff --git a/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/SilentIterationTest.java b/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/SilentIterationTest.java index cfbe7bdbf40..93fa033deb1 100644 --- a/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/SilentIterationTest.java +++ b/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/SilentIterationTest.java @@ -26,19 +26,19 @@ public class SilentIterationTest { @Mock - private CloseableIteration delegate; + private CloseableIteration delegate; @InjectMocks - private SilentIteration subject; + private SilentIteration subject; @Test - public void hasNextSwallowsException() throws Exception { + public void hasNextSwallowsException() { when(delegate.hasNext()).thenThrow(new RuntimeException()); assertThat(subject.hasNext()).isFalse(); } @Test - public void nextConvertsException() throws Exception { + public void nextConvertsException() { when(delegate.next()).thenThrow(new RuntimeException()); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(subject::next); } diff --git a/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/benchmark/IterationBenchmarks.java b/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/benchmark/IterationBenchmarks.java index 4104450217b..6221dfc6d37 100644 --- a/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/benchmark/IterationBenchmarks.java +++ b/core/common/iterator/src/test/java/org/eclipse/rdf4j/common/iteration/benchmark/IterationBenchmarks.java @@ -167,7 +167,7 @@ public int getFirst() { .orElse(0); } - private CloseableIteration getIterator(List list) { + private CloseableIteration getIterator(List list) { return new CloseableIteration<>() { final Iterator iterator = list.iterator(); diff --git a/core/common/pom.xml b/core/common/pom.xml index ce2b332edf5..f8aa4c5e689 100644 --- a/core/common/pom.xml +++ b/core/common/pom.xml @@ -17,7 +17,6 @@ iterator text transaction - util xml diff --git a/core/common/text/pom.xml b/core/common/text/pom.xml index 2afdfcfe42b..3a1f7c034c1 100644 --- a/core/common/text/pom.xml +++ b/core/common/text/pom.xml @@ -43,10 +43,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/common/transaction/pom.xml b/core/common/transaction/pom.xml index 6670bf3d0cf..14c85825dca 100644 --- a/core/common/transaction/pom.xml +++ b/core/common/transaction/pom.xml @@ -15,11 +15,6 @@ rdf4j-model ${project.version} - - ${project.groupId} - rdf4j-common-util - ${project.version} - org.slf4j slf4j-api @@ -42,10 +37,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/common/util/src/main/java/org/eclipse/rdf4j/util/UUIDable.java b/core/common/util/src/main/java/org/eclipse/rdf4j/util/UUIDable.java deleted file mode 100644 index 238a5c28c8f..00000000000 --- a/core/common/util/src/main/java/org/eclipse/rdf4j/util/UUIDable.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.util; - -import java.util.UUID; - -/** - * Interface for any object that has a UUID. The UUID must be constant for the lifetime of the object. - */ -public interface UUIDable { - - /** - * Returns the UUID of this object. - * - * @return a non-null UUID. - */ - UUID getUUID(); -} diff --git a/core/common/xml/pom.xml b/core/common/xml/pom.xml index 46b6ca371c7..46160b4db67 100644 --- a/core/common/xml/pom.xml +++ b/core/common/xml/pom.xml @@ -47,10 +47,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/http/client/pom.xml b/core/http/client/pom.xml index 52d7cb41ec4..fb4d826a565 100644 --- a/core/http/client/pom.xml +++ b/core/http/client/pom.xml @@ -111,12 +111,4 @@ ${project.version} - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/http/client/src/main/java/org/eclipse/rdf4j/http/client/BackgroundResultExecutor.java b/core/http/client/src/main/java/org/eclipse/rdf4j/http/client/BackgroundResultExecutor.java index ae209ec6de5..bab677ef345 100644 --- a/core/http/client/src/main/java/org/eclipse/rdf4j/http/client/BackgroundResultExecutor.java +++ b/core/http/client/src/main/java/org/eclipse/rdf4j/http/client/BackgroundResultExecutor.java @@ -45,14 +45,14 @@ public BackgroundResultExecutor(ExecutorService executor) { } public TupleQueryResult parse(TupleQueryResultParser parser, InputStream in, WeakReference callerReference) { - BackgroundTupleResult result = new BackgroundTupleResult(parser, in, callerReference); + BackgroundTupleResult result = new BackgroundTupleResult(parser, in); autoCloseRunnable(result, result); return new CleanerTupleQueryResult(result, cleaner); } public GraphQueryResult parse(RDFParser parser, InputStream in, Charset charset, String baseURI, WeakReference callerReference) { - BackgroundGraphResult result = new BackgroundGraphResult(parser, in, charset, baseURI, callerReference); + BackgroundGraphResult result = new BackgroundGraphResult(parser, in, charset, baseURI); autoCloseRunnable(result, result); return new CleanerGraphQueryResult(result, cleaner); } diff --git a/core/http/client/src/test/java/org/eclipse/rdf4j/http/client/BackgroundGraphResultHangTest.java b/core/http/client/src/test/java/org/eclipse/rdf4j/http/client/BackgroundGraphResultHangTest.java index fecf1113a3a..bf237339b48 100644 --- a/core/http/client/src/test/java/org/eclipse/rdf4j/http/client/BackgroundGraphResultHangTest.java +++ b/core/http/client/src/test/java/org/eclipse/rdf4j/http/client/BackgroundGraphResultHangTest.java @@ -13,7 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayInputStream; -import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.charset.StandardCharsets; @@ -41,12 +40,12 @@ public RDFFormat getRDFFormat() { } @Override - public void parse(InputStream in, String baseURI) throws IOException, RDFParseException, RDFHandlerException { + public void parse(InputStream in, String baseURI) throws RDFParseException, RDFHandlerException { throw new RDFParseException("invalid RDF "); } @Override - public void parse(Reader reader, String baseURI) throws IOException, RDFParseException, RDFHandlerException { + public void parse(Reader reader, String baseURI) throws RDFParseException, RDFHandlerException { throw new RDFParseException("invalid RDF "); } @@ -59,7 +58,7 @@ public void testBGRHang() { Exception exception = assertThrows(QueryEvaluationException.class, () -> { BackgroundGraphResult gRes = new BackgroundGraphResult(new DummyParser(), new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8, - "http://example.org", null); + "http://example.org"); gRes.run(); gRes.getNamespaces(); gRes.hasNext(); diff --git a/core/http/client/src/test/java/org/eclipse/rdf4j/http/client/SPARQLProtocolSessionTest.java b/core/http/client/src/test/java/org/eclipse/rdf4j/http/client/SPARQLProtocolSessionTest.java index 69f81914546..adad04f3946 100644 --- a/core/http/client/src/test/java/org/eclipse/rdf4j/http/client/SPARQLProtocolSessionTest.java +++ b/core/http/client/src/test/java/org/eclipse/rdf4j/http/client/SPARQLProtocolSessionTest.java @@ -72,7 +72,7 @@ SPARQLProtocolSession createProtocolSession() { } @BeforeEach - public void setUp(MockServerClient client) throws Exception { + public void setUp(MockServerClient client) { serverURL = "http://localhost:" + client.getPort() + "/rdf4j-server"; sparqlSession = createProtocolSession(); } diff --git a/core/model-api/pom.xml b/core/model-api/pom.xml index e5ff2e7348d..75f807bf88b 100644 --- a/core/model-api/pom.xml +++ b/core/model-api/pom.xml @@ -29,10 +29,6 @@ - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/model-api/src/main/java/org/eclipse/rdf4j/model/base/CoreDatatype.java b/core/model-api/src/main/java/org/eclipse/rdf4j/model/base/CoreDatatype.java index 2503ddc3bab..50af84d1df3 100644 --- a/core/model-api/src/main/java/org/eclipse/rdf4j/model/base/CoreDatatype.java +++ b/core/model-api/src/main/java/org/eclipse/rdf4j/model/base/CoreDatatype.java @@ -50,6 +50,18 @@ default Optional asGEODatatype() { return Optional.empty(); } + default XSD asXSDDatatypeOrNull() { + return isXSDDatatype() ? ((XSD) this) : null; + } + + default RDF asRDFDatatypeOrNull() { + return isRDFDatatype() ? ((RDF) this) : null; + } + + default GEO asGEODatatypeOrNull() { + return isGEODatatype() ? ((GEO) this) : null; + } + IRI getIri(); static CoreDatatype from(IRI datatype) { diff --git a/core/model-vocabulary/pom.xml b/core/model-vocabulary/pom.xml index 2b0dd4f13b8..cd1a34790ac 100644 --- a/core/model-vocabulary/pom.xml +++ b/core/model-vocabulary/pom.xml @@ -16,12 +16,4 @@ ${project.version} - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/CONFIG.java b/core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/CONFIG.java index 1745ade12d3..852467d0d41 100644 --- a/core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/CONFIG.java +++ b/core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/CONFIG.java @@ -10,7 +10,8 @@ *******************************************************************************/ package org.eclipse.rdf4j.model.vocabulary; -import org.eclipse.rdf4j.common.annotation.Experimental; +import static org.eclipse.rdf4j.model.vocabulary.Vocabularies.createIRI; + import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Namespace; @@ -21,7 +22,6 @@ * * @since 4.3.0 */ -@Experimental public class CONFIG { /** @@ -48,7 +48,7 @@ public class CONFIG { * * tag:rdf4j.org,2023:config/delegate */ - public final static IRI delegate = Vocabularies.createIRI(NAMESPACE, "delegate"); + public final static IRI delegate = createIRI(NAMESPACE, "delegate"); /** * Repository config @@ -59,28 +59,28 @@ public static final class Rep { * * tag:rdf4j.org,2023:config/Repository */ - public final static IRI Repository = Vocabularies.createIRI(NAMESPACE, "Repository"); + public final static IRI Repository = createIRI(NAMESPACE, "Repository"); /** * Setting for the repository ID. * * tag:rdf4j.org,2023:config/rep.id */ - public final static IRI id = Vocabularies.createIRI(NAMESPACE, "rep.id"); + public final static IRI id = createIRI(NAMESPACE, "rep.id"); /** * Setting for the repository implementation-specific configuration. * * tag:rdf4j.org,2023:config/rep.impl */ - public final static IRI impl = Vocabularies.createIRI(NAMESPACE, "rep.impl"); + public final static IRI impl = createIRI(NAMESPACE, "rep.impl"); /** * Setting for the repository type. * * tag:rdf4j.org,2023:config/rep.type */ - public final static IRI type = Vocabularies.createIRI(NAMESPACE, "rep.type"); + public final static IRI type = createIRI(NAMESPACE, "rep.type"); } /** @@ -92,21 +92,21 @@ public static final class Http { * * tag:rdf4j.org,2023:config/http.url */ - public static final IRI url = Vocabularies.createIRI(NAMESPACE, "http.url"); + public static final IRI url = createIRI(NAMESPACE, "http.url"); /** * Setting for a username to use for authentication. * * tag:rdf4j.org,2023:config/http.username */ - public final static IRI username = Vocabularies.createIRI(NAMESPACE, "http.username"); + public final static IRI username = createIRI(NAMESPACE, "http.username"); /** * Setting for a password to use for authentication. * * tag:rdf4j.org,2023:config/http.password */ - public final static IRI password = Vocabularies.createIRI(NAMESPACE, "http.password"); + public final static IRI password = createIRI(NAMESPACE, "http.password"); } /** @@ -118,43 +118,43 @@ public static final class ContextAware { * * tag:rdf4j.org,2023:config/ca.includeInferred */ - public final static IRI includeInferred = Vocabularies.createIRI(NAMESPACE, "ca.includeInferred"); + public final static IRI includeInferred = createIRI(NAMESPACE, "ca.includeInferred"); /** * Setting for the max query time. * * tag:rdf4j.org,2023:config/ca.maxQueryTime */ - public final static IRI maxQueryTime = Vocabularies.createIRI(NAMESPACE, "ca.maxQueryTime"); + public final static IRI maxQueryTime = createIRI(NAMESPACE, "ca.maxQueryTime"); /** * Setting for the query language to be used. * * tag:rdf4j.org,2023:config/ca.queryLanguage */ - public final static IRI queryLanguage = Vocabularies.createIRI(NAMESPACE, "ca.queryLanguage"); + public final static IRI queryLanguage = createIRI(NAMESPACE, "ca.queryLanguage"); /** * * tag:rdf4j.org,2023:config/ca.readContext */ - public final static IRI readContext = Vocabularies.createIRI(NAMESPACE, "ca.readContext"); + public final static IRI readContext = createIRI(NAMESPACE, "ca.readContext"); /** * tag:rdf4j.org,2023:config/ca.removeContext */ - public final static IRI removeContext = Vocabularies.createIRI(NAMESPACE, "ca.removeContext"); + public final static IRI removeContext = createIRI(NAMESPACE, "ca.removeContext"); /** * tag:rdf4j.org,2023:config/ca.insertContext */ - public final static IRI insertContext = Vocabularies.createIRI(NAMESPACE, "ca.insertContext"); + public final static IRI insertContext = createIRI(NAMESPACE, "ca.insertContext"); /** * Setting for a base URI. * * tag:rdf4j.org,2023:config/ca.base */ - public final static IRI base = Vocabularies.createIRI(NAMESPACE, "ca.base"); + public final static IRI base = createIRI(NAMESPACE, "ca.base"); } @@ -166,7 +166,7 @@ public static final class Proxy { /** * tag:rdf4j.org,2023:config/proxy.proxiedID */ - public final static IRI proxiedID = Vocabularies.createIRI(NAMESPACE, "proxy.proxiedID"); + public final static IRI proxiedID = createIRI(NAMESPACE, "proxy.proxiedID"); } @@ -179,15 +179,14 @@ public static final class Sparql { * * tag:rdf4j.org,2023:config/sparql.queryEndpoint */ - public static final IRI queryEndpoint = Vocabularies.createIRI(NAMESPACE, "sparql.queryEndpoint"); + public static final IRI queryEndpoint = createIRI(NAMESPACE, "sparql.queryEndpoint"); /** * Configuration setting for the SPARQL update endpoint. * * tag:rdf4j.org,2023:config/sparql.updateEndpoint */ - public static final IRI updateEndpoint = Vocabularies - .createIRI(NAMESPACE, "sparql.updateEndpoint"); + public static final IRI updateEndpoint = createIRI(NAMESPACE, "sparql.updateEndpoint"); /** * Configuration setting for enabling/disabling direct result pass-through. @@ -196,7 +195,7 @@ public static final class Sparql { * * @see SPARQLProtocolSession#isPassThroughEnabled() */ - public static final IRI passThroughEnabled = Vocabularies.createIRI(NAMESPACE, "sparql.passThroughEnabled"); + public static final IRI passThroughEnabled = createIRI(NAMESPACE, "sparql.passThroughEnabled"); } /** @@ -206,30 +205,30 @@ public static final class Sail { /** * tag:rdf4j.org,2023:config/sail.type */ - public final static IRI type = Vocabularies.createIRI(NAMESPACE, "sail.type"); + public final static IRI type = createIRI(NAMESPACE, "sail.type"); /** * tag:rdf4j.org,2023:config/sail.impl */ - public final static IRI impl = Vocabularies.createIRI(NAMESPACE, "sail.impl"); + public final static IRI impl = createIRI(NAMESPACE, "sail.impl"); /** * tag:rdf4j.org,2023:config/sail.iterationCacheSyncTreshold */ - public final static IRI iterationCacheSyncThreshold = Vocabularies.createIRI(NAMESPACE, + public final static IRI iterationCacheSyncThreshold = createIRI(NAMESPACE, "sail.iterationCacheSyncThreshold"); /** * tag:rdf4j.org,2023:config/sail.connectionTimeOut */ - public final static IRI connectionTimeOut = Vocabularies.createIRI(NAMESPACE, "sail.connectionTimeOut"); + public final static IRI connectionTimeOut = createIRI(NAMESPACE, "sail.connectionTimeOut"); /** tag:rdf4j.org,2023:config/sail.evaluationStrategyFactory */ - public final static IRI evaluationStrategyFactory = Vocabularies.createIRI(NAMESPACE, + public final static IRI evaluationStrategyFactory = createIRI(NAMESPACE, "sail.evaluationStrategyFactory"); /** tag:rdf4j.org,2023:config/sail.defaultQueryEvaluationMode */ - public final static IRI defaultQueryEvaluationMode = Vocabularies.createIRI(NAMESPACE, + public final static IRI defaultQueryEvaluationMode = createIRI(NAMESPACE, "sail.defaultQueryEvaluationMode"); } @@ -238,10 +237,10 @@ public static final class Sail { */ public static final class Mem { /** tag:rdf4j.org,2023:config/mem.persist */ - public final static IRI persist = Vocabularies.createIRI(NAMESPACE, "mem.persist"); + public final static IRI persist = createIRI(NAMESPACE, "mem.persist"); /** tag:rdf4j.org,2023:config/mem.syncDelay */ - public final static IRI syncDelay = Vocabularies.createIRI(NAMESPACE, "mem.syncDelay"); + public final static IRI syncDelay = createIRI(NAMESPACE, "mem.syncDelay"); } /** @@ -251,32 +250,32 @@ public static final class Native { /** * tag:rdf4j.org,2023:config/native.tripleIndexes */ - public final static IRI tripleIndexes = Vocabularies.createIRI(NAMESPACE, "native.tripleIndexes"); + public final static IRI tripleIndexes = createIRI(NAMESPACE, "native.tripleIndexes"); /** * tag:rdf4j.org,2023:config/native.forceSync */ - public final static IRI forceSync = Vocabularies.createIRI(NAMESPACE, "native.forceSync"); + public final static IRI forceSync = createIRI(NAMESPACE, "native.forceSync"); /** * tag:rdf4j.org,2023:config/native.valueCacheSize */ - public final static IRI valueCacheSize = Vocabularies.createIRI(NAMESPACE, "native.valueCacheSize"); + public final static IRI valueCacheSize = createIRI(NAMESPACE, "native.valueCacheSize"); /** * tag:rdf4j.org,2023:config/native.valueIDCacheSize */ - public final static IRI valueIDCacheSize = Vocabularies.createIRI(NAMESPACE, "native.valueIDCacheSize"); + public final static IRI valueIDCacheSize = createIRI(NAMESPACE, "native.valueIDCacheSize"); /** * tag:rdf4j.org,2023:config/native.namespaceCacheSize */ - public final static IRI namespaceCacheSize = Vocabularies.createIRI(NAMESPACE, "native.namespaceCacheSize"); + public final static IRI namespaceCacheSize = createIRI(NAMESPACE, "native.namespaceCacheSize"); /** * tag:rdf4j.org,2023:config/native.namespaceIDCacheSize */ - public final static IRI namespaceIDCacheSize = Vocabularies.createIRI(NAMESPACE, "native.namespaceIDCacheSize"); + public final static IRI namespaceIDCacheSize = createIRI(NAMESPACE, "native.namespaceIDCacheSize"); } /** @@ -286,65 +285,65 @@ public static final class Shacl { /** * tag:rdf4j.org,2023:config/shacl.parallelValidation */ - public final static IRI parallelValidation = Vocabularies.createIRI(NAMESPACE, "shacl.parallelValidation"); + public final static IRI parallelValidation = createIRI(NAMESPACE, "shacl.parallelValidation"); /** * tag:rdf4j.org,2023:config/shacl.logValidationPlans */ - public final static IRI logValidationPlans = Vocabularies.createIRI(NAMESPACE, "shacl.logValidationPlans"); + public final static IRI logValidationPlans = createIRI(NAMESPACE, "shacl.logValidationPlans"); /** * tag:rdf4j.org,2023:config/shacl.logValidationViolations */ - public final static IRI logValidationViolations = Vocabularies.createIRI(NAMESPACE, + public final static IRI logValidationViolations = createIRI(NAMESPACE, "shacl.logValidationViolations"); /** * tag:rdf4j.org,2023:config/shacl.validationEnabled */ - public final static IRI validationEnabled = Vocabularies.createIRI(NAMESPACE, "shacl.validationEnabled"); + public final static IRI validationEnabled = createIRI(NAMESPACE, "shacl.validationEnabled"); /** * tag:rdf4j.org,2023:config/shacl.cacheSelectNodes */ - public final static IRI cacheSelectNodes = Vocabularies.createIRI(NAMESPACE, "shacl.cacheSelectNodes"); + public final static IRI cacheSelectNodes = createIRI(NAMESPACE, "shacl.cacheSelectNodes"); /** * tag:rdf4j.org,2023:config/shacl.globalLogValidationExecution */ - public final static IRI globalLogValidationExecution = Vocabularies.createIRI(NAMESPACE, + public final static IRI globalLogValidationExecution = createIRI(NAMESPACE, "shacl.globalLogValidationExecution"); /** * tag:rdf4j.org,2023:config/shacl.rdfsSubClassReasoning */ - public final static IRI rdfsSubClassReasoning = Vocabularies.createIRI(NAMESPACE, + public final static IRI rdfsSubClassReasoning = createIRI(NAMESPACE, "shacl.rdfsSubClassReasoning"); /** * tag:rdf4j.org,2023:config/shacl.performanceLogging */ - public final static IRI performanceLogging = Vocabularies.createIRI(NAMESPACE, "shacl.performanceLogging"); + public final static IRI performanceLogging = createIRI(NAMESPACE, "shacl.performanceLogging"); /** * tag:rdf4j.org,2023:config/shacl.serializableValidation */ - public final static IRI serializableValidation = Vocabularies.createIRI(NAMESPACE, + public final static IRI serializableValidation = createIRI(NAMESPACE, "shacl.serializableValidation"); - public final static IRI eclipseRdf4jShaclExtensions = Vocabularies.createIRI(NAMESPACE, + public final static IRI eclipseRdf4jShaclExtensions = createIRI(NAMESPACE, "shacl.eclipseRdf4jShaclExtensions"); - public final static IRI dashDataShapes = Vocabularies.createIRI(NAMESPACE, "shacl.dashDataShapes"); + public final static IRI dashDataShapes = createIRI(NAMESPACE, "shacl.dashDataShapes"); - public final static IRI validationResultsLimitTotal = Vocabularies.createIRI(NAMESPACE, + public final static IRI validationResultsLimitTotal = createIRI(NAMESPACE, "shacl.validationResultsLimitTotal"); - public final static IRI validationResultsLimitPerConstraint = Vocabularies.createIRI(NAMESPACE, + public final static IRI validationResultsLimitPerConstraint = createIRI(NAMESPACE, "shacl.validationResultsLimitPerConstraint"); - public final static IRI transactionalValidationLimit = Vocabularies.createIRI(NAMESPACE, + public final static IRI transactionalValidationLimit = createIRI(NAMESPACE, "shacl.transactionalValidationLimit"); - public final static IRI shapesGraph = Vocabularies.createIRI(NAMESPACE, "shacl.shapesGraph"); + public final static IRI shapesGraph = createIRI(NAMESPACE, "shacl.shapesGraph"); } /** @@ -352,7 +351,7 @@ public static final class Shacl { * */ public static final class Lucene { - public final static IRI indexDir = Vocabularies.createIRI(NAMESPACE, "lucene.indexDir"); + public final static IRI indexDir = createIRI(NAMESPACE, "lucene.indexDir"); } /** @@ -360,20 +359,21 @@ public static final class Lucene { */ public static final class Ess { - public final static IRI hostname = Vocabularies.createIRI(NAMESPACE, "ess.hostname"); - public final static IRI port = Vocabularies.createIRI(NAMESPACE, "ess.port"); - public final static IRI index = Vocabularies.createIRI(NAMESPACE, "ess.index"); - public final static IRI clusterName = Vocabularies.createIRI(NAMESPACE, "ess.clusterName"); + public final static IRI hostname = createIRI(NAMESPACE, "ess.hostname"); + public final static IRI port = createIRI(NAMESPACE, "ess.port"); + public final static IRI index = createIRI(NAMESPACE, "ess.index"); + public final static IRI clusterName = createIRI(NAMESPACE, "ess.clusterName"); } /** * Custom Graph Query Inferencer config */ public static final class Cgqi { - public final static IRI queryLanguage = Vocabularies.createIRI(NAMESPACE, "cgqi.queryLanguage"); + public final static IRI queryLanguage = createIRI(NAMESPACE, "cgqi.queryLanguage"); - public final static IRI ruleQuery = Vocabularies.createIRI(NAMESPACE, "cgqi.ruleQuery"); + public final static IRI ruleQuery = createIRI(NAMESPACE, "cgqi.ruleQuery"); - public final static IRI matcherQuery = Vocabularies.createIRI(NAMESPACE, "cgqi.matcherQuery"); + public final static IRI matcherQuery = createIRI(NAMESPACE, "cgqi.matcherQuery"); } + } diff --git a/core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/XSD.java b/core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/XSD.java index b29814bbc6c..e2921be26d6 100644 --- a/core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/XSD.java +++ b/core/model-vocabulary/src/main/java/org/eclipse/rdf4j/model/vocabulary/XSD.java @@ -197,6 +197,7 @@ private static IRI create(String localName) { return Vocabularies.createIRI(org.eclipse.rdf4j.model.vocabulary.XSD.NAMESPACE, localName); } + @Deprecated(since = "5.0.0", forRemoval = true) public enum Datatype { DURATION(CoreDatatype.XSD.DURATION.getIri(), true, true, false, false, false, false, false), diff --git a/core/model/pom.xml b/core/model/pom.xml index 87e36557259..4323289da0f 100644 --- a/core/model/pom.xml +++ b/core/model/pom.xml @@ -75,12 +75,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/datatypes/XMLDatatypeUtil.java b/core/model/src/main/java/org/eclipse/rdf4j/model/datatypes/XMLDatatypeUtil.java index eb721235190..2fd377f3d0a 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/datatypes/XMLDatatypeUtil.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/datatypes/XMLDatatypeUtil.java @@ -75,60 +75,60 @@ public class XMLDatatypeUtil { private final static Pattern P_GYEAR = Pattern.compile("-?\\d{4,}(Z|([+\\-])\\d\\d:\\d\\d)?"); private final static Pattern P_GYEARMONTH = Pattern.compile("-?\\d{4,}-\\d\\d(Z|([+\\-])\\d\\d:\\d\\d)?"); - private static final Set primitiveDatatypes = Set.of(org.eclipse.rdf4j.model.vocabulary.XSD.DURATION, - org.eclipse.rdf4j.model.vocabulary.XSD.DATETIME, org.eclipse.rdf4j.model.vocabulary.XSD.TIME, - org.eclipse.rdf4j.model.vocabulary.XSD.DATE, - org.eclipse.rdf4j.model.vocabulary.XSD.GYEARMONTH, org.eclipse.rdf4j.model.vocabulary.XSD.GYEAR, - org.eclipse.rdf4j.model.vocabulary.XSD.GMONTHDAY, org.eclipse.rdf4j.model.vocabulary.XSD.GDAY, - org.eclipse.rdf4j.model.vocabulary.XSD.GMONTH, org.eclipse.rdf4j.model.vocabulary.XSD.STRING, - org.eclipse.rdf4j.model.vocabulary.XSD.BOOLEAN, org.eclipse.rdf4j.model.vocabulary.XSD.BASE64BINARY, - org.eclipse.rdf4j.model.vocabulary.XSD.HEXBINARY, org.eclipse.rdf4j.model.vocabulary.XSD.FLOAT, - org.eclipse.rdf4j.model.vocabulary.XSD.DECIMAL, org.eclipse.rdf4j.model.vocabulary.XSD.DOUBLE, - org.eclipse.rdf4j.model.vocabulary.XSD.ANYURI, org.eclipse.rdf4j.model.vocabulary.XSD.QNAME, - org.eclipse.rdf4j.model.vocabulary.XSD.NOTATION); - - private static final Set derivedDatatypes = Set.of(org.eclipse.rdf4j.model.vocabulary.XSD.NORMALIZEDSTRING, - org.eclipse.rdf4j.model.vocabulary.XSD.TOKEN, org.eclipse.rdf4j.model.vocabulary.XSD.LANGUAGE, - org.eclipse.rdf4j.model.vocabulary.XSD.NMTOKEN, - org.eclipse.rdf4j.model.vocabulary.XSD.NMTOKENS, org.eclipse.rdf4j.model.vocabulary.XSD.NAME, - org.eclipse.rdf4j.model.vocabulary.XSD.NCNAME, org.eclipse.rdf4j.model.vocabulary.XSD.ID, - org.eclipse.rdf4j.model.vocabulary.XSD.IDREF, org.eclipse.rdf4j.model.vocabulary.XSD.IDREFS, - org.eclipse.rdf4j.model.vocabulary.XSD.ENTITY, org.eclipse.rdf4j.model.vocabulary.XSD.ENTITIES, - org.eclipse.rdf4j.model.vocabulary.XSD.INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.LONG, org.eclipse.rdf4j.model.vocabulary.XSD.INT, - org.eclipse.rdf4j.model.vocabulary.XSD.SHORT, org.eclipse.rdf4j.model.vocabulary.XSD.BYTE, - org.eclipse.rdf4j.model.vocabulary.XSD.NON_POSITIVE_INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.NEGATIVE_INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.NON_NEGATIVE_INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.POSITIVE_INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_LONG, org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_INT, - org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_SHORT, - org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_BYTE, - org.eclipse.rdf4j.model.vocabulary.XSD.DAYTIMEDURATION, - org.eclipse.rdf4j.model.vocabulary.XSD.YEARMONTHDURATION, - org.eclipse.rdf4j.model.vocabulary.XSD.DATETIMESTAMP); - - private static final Set integerDatatypes = Set.of(org.eclipse.rdf4j.model.vocabulary.XSD.INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.LONG, org.eclipse.rdf4j.model.vocabulary.XSD.INT, - org.eclipse.rdf4j.model.vocabulary.XSD.SHORT, org.eclipse.rdf4j.model.vocabulary.XSD.BYTE, - org.eclipse.rdf4j.model.vocabulary.XSD.NON_POSITIVE_INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.NEGATIVE_INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.NON_NEGATIVE_INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.POSITIVE_INTEGER, - org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_LONG, org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_INT, - org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_SHORT, - org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_BYTE); - - private static final Set calendarDatatypes = Set.of(org.eclipse.rdf4j.model.vocabulary.XSD.DATETIME, - org.eclipse.rdf4j.model.vocabulary.XSD.DATE, org.eclipse.rdf4j.model.vocabulary.XSD.TIME, - org.eclipse.rdf4j.model.vocabulary.XSD.GYEARMONTH, - org.eclipse.rdf4j.model.vocabulary.XSD.GMONTHDAY, org.eclipse.rdf4j.model.vocabulary.XSD.GYEAR, - org.eclipse.rdf4j.model.vocabulary.XSD.GMONTH, org.eclipse.rdf4j.model.vocabulary.XSD.GDAY, - org.eclipse.rdf4j.model.vocabulary.XSD.DATETIMESTAMP); - - private static final Set durationDatatypes = Set.of(org.eclipse.rdf4j.model.vocabulary.XSD.DURATION, - org.eclipse.rdf4j.model.vocabulary.XSD.DAYTIMEDURATION, - org.eclipse.rdf4j.model.vocabulary.XSD.YEARMONTHDURATION); + private static final Set primitiveDatatypes = Set.of(XSD.DURATION, + XSD.DATETIME, XSD.TIME, + XSD.DATE, + XSD.GYEARMONTH, XSD.GYEAR, + XSD.GMONTHDAY, XSD.GDAY, + XSD.GMONTH, XSD.STRING, + XSD.BOOLEAN, XSD.BASE64BINARY, + XSD.HEXBINARY, XSD.FLOAT, + XSD.DECIMAL, XSD.DOUBLE, + XSD.ANYURI, XSD.QNAME, + XSD.NOTATION); + + private static final Set derivedDatatypes = Set.of(XSD.NORMALIZEDSTRING, + XSD.TOKEN, XSD.LANGUAGE, + XSD.NMTOKEN, + XSD.NMTOKENS, XSD.NAME, + XSD.NCNAME, XSD.ID, + XSD.IDREF, XSD.IDREFS, + XSD.ENTITY, XSD.ENTITIES, + XSD.INTEGER, + XSD.LONG, XSD.INT, + XSD.SHORT, XSD.BYTE, + XSD.NON_POSITIVE_INTEGER, + XSD.NEGATIVE_INTEGER, + XSD.NON_NEGATIVE_INTEGER, + XSD.POSITIVE_INTEGER, + XSD.UNSIGNED_LONG, XSD.UNSIGNED_INT, + XSD.UNSIGNED_SHORT, + XSD.UNSIGNED_BYTE, + XSD.DAYTIMEDURATION, + XSD.YEARMONTHDURATION, + XSD.DATETIMESTAMP); + + private static final Set integerDatatypes = Set.of(XSD.INTEGER, + XSD.LONG, XSD.INT, + XSD.SHORT, XSD.BYTE, + XSD.NON_POSITIVE_INTEGER, + XSD.NEGATIVE_INTEGER, + XSD.NON_NEGATIVE_INTEGER, + XSD.POSITIVE_INTEGER, + XSD.UNSIGNED_LONG, XSD.UNSIGNED_INT, + XSD.UNSIGNED_SHORT, + XSD.UNSIGNED_BYTE); + + private static final Set calendarDatatypes = Set.of(XSD.DATETIME, + XSD.DATE, XSD.TIME, + XSD.GYEARMONTH, + XSD.GMONTHDAY, XSD.GYEAR, + XSD.GMONTH, XSD.GDAY, + XSD.DATETIMESTAMP); + + private static final Set durationDatatypes = Set.of(XSD.DURATION, + XSD.DAYTIMEDURATION, + XSD.YEARMONTHDURATION); /** * Checks whether the supplied datatype is a primitive XML Schema datatype. @@ -179,7 +179,7 @@ public static boolean isNumericDatatype(IRI datatype) { * @return true if it is a decimal datatype */ public static boolean isDecimalDatatype(IRI datatype) { - return datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DECIMAL) || isIntegerDatatype(datatype); + return datatype.equals(XSD.DECIMAL) || isIntegerDatatype(datatype); } /** @@ -200,8 +200,8 @@ public static boolean isIntegerDatatype(IRI datatype) { * @return true if it is a floating point type */ public static boolean isFloatingPointDatatype(IRI datatype) { - return datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.FLOAT) - || datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DOUBLE); + return datatype.equals(XSD.FLOAT) + || datatype.equals(XSD.DOUBLE); } /** @@ -251,69 +251,69 @@ public static boolean isOrderedDatatype(IRI datatype) { * @return true if the supplied lexical value is valid, false otherwise. */ public static boolean isValidValue(String value, IRI datatype) { - if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DECIMAL)) { + if (datatype.equals(XSD.DECIMAL)) { return isValidDecimal(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.INTEGER)) { + } else if (datatype.equals(XSD.INTEGER)) { return isValidInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NEGATIVE_INTEGER)) { + } else if (datatype.equals(XSD.NEGATIVE_INTEGER)) { return isValidNegativeInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NON_POSITIVE_INTEGER)) { + } else if (datatype.equals(XSD.NON_POSITIVE_INTEGER)) { return isValidNonPositiveInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NON_NEGATIVE_INTEGER)) { + } else if (datatype.equals(XSD.NON_NEGATIVE_INTEGER)) { return isValidNonNegativeInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.POSITIVE_INTEGER)) { + } else if (datatype.equals(XSD.POSITIVE_INTEGER)) { return isValidPositiveInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.LONG)) { + } else if (datatype.equals(XSD.LONG)) { return isValidLong(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.INT)) { + } else if (datatype.equals(XSD.INT)) { return isValidInt(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.SHORT)) { + } else if (datatype.equals(XSD.SHORT)) { return isValidShort(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.BYTE)) { + } else if (datatype.equals(XSD.BYTE)) { return isValidByte(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_LONG)) { + } else if (datatype.equals(XSD.UNSIGNED_LONG)) { return isValidUnsignedLong(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_INT)) { + } else if (datatype.equals(XSD.UNSIGNED_INT)) { return isValidUnsignedInt(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_SHORT)) { + } else if (datatype.equals(XSD.UNSIGNED_SHORT)) { return isValidUnsignedShort(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_BYTE)) { + } else if (datatype.equals(XSD.UNSIGNED_BYTE)) { return isValidUnsignedByte(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.FLOAT)) { + } else if (datatype.equals(XSD.FLOAT)) { return isValidFloat(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DOUBLE)) { + } else if (datatype.equals(XSD.DOUBLE)) { return isValidDouble(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.BOOLEAN)) { + } else if (datatype.equals(XSD.BOOLEAN)) { return isValidBoolean(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DATETIME)) { + } else if (datatype.equals(XSD.DATETIME)) { return isValidDateTime(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DATETIMESTAMP)) { + } else if (datatype.equals(XSD.DATETIMESTAMP)) { return isValidDateTimeStamp(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DATE)) { + } else if (datatype.equals(XSD.DATE)) { return isValidDate(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.TIME)) { + } else if (datatype.equals(XSD.TIME)) { return isValidTime(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.GDAY)) { + } else if (datatype.equals(XSD.GDAY)) { return isValidGDay(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.GMONTH)) { + } else if (datatype.equals(XSD.GMONTH)) { return isValidGMonth(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.GMONTHDAY)) { + } else if (datatype.equals(XSD.GMONTHDAY)) { return isValidGMonthDay(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.GYEAR)) { + } else if (datatype.equals(XSD.GYEAR)) { return isValidGYear(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.GYEARMONTH)) { + } else if (datatype.equals(XSD.GYEARMONTH)) { return isValidGYearMonth(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DURATION)) { + } else if (datatype.equals(XSD.DURATION)) { return isValidDuration(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DAYTIMEDURATION)) { + } else if (datatype.equals(XSD.DAYTIMEDURATION)) { return isValidDayTimeDuration(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.YEARMONTHDURATION)) { + } else if (datatype.equals(XSD.YEARMONTHDURATION)) { return isValidYearMonthDuration(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.QNAME)) { + } else if (datatype.equals(XSD.QNAME)) { return isValidQName(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.ANYURI)) { + } else if (datatype.equals(XSD.ANYURI)) { return isValidAnyURI(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.LANGUAGE)) { + } else if (datatype.equals(XSD.LANGUAGE)) { return Literals.isValidLanguageTag(value); } @@ -901,43 +901,43 @@ private static boolean isValidCalendarValue(String value) { * @throws IllegalArgumentException If the supplied value is illegal considering the supplied datatype. */ public static String normalize(String value, IRI datatype) { - if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DECIMAL)) { + if (datatype.equals(XSD.DECIMAL)) { return normalizeDecimal(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.INTEGER)) { + } else if (datatype.equals(XSD.INTEGER)) { return normalizeInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NEGATIVE_INTEGER)) { + } else if (datatype.equals(XSD.NEGATIVE_INTEGER)) { return normalizeNegativeInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NON_POSITIVE_INTEGER)) { + } else if (datatype.equals(XSD.NON_POSITIVE_INTEGER)) { return normalizeNonPositiveInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NON_NEGATIVE_INTEGER)) { + } else if (datatype.equals(XSD.NON_NEGATIVE_INTEGER)) { return normalizeNonNegativeInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.POSITIVE_INTEGER)) { + } else if (datatype.equals(XSD.POSITIVE_INTEGER)) { return normalizePositiveInteger(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.LONG)) { + } else if (datatype.equals(XSD.LONG)) { return normalizeLong(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.INT)) { + } else if (datatype.equals(XSD.INT)) { return normalizeInt(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.SHORT)) { + } else if (datatype.equals(XSD.SHORT)) { return normalizeShort(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.BYTE)) { + } else if (datatype.equals(XSD.BYTE)) { return normalizeByte(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_LONG)) { + } else if (datatype.equals(XSD.UNSIGNED_LONG)) { return normalizeUnsignedLong(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_INT)) { + } else if (datatype.equals(XSD.UNSIGNED_INT)) { return normalizeUnsignedInt(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_SHORT)) { + } else if (datatype.equals(XSD.UNSIGNED_SHORT)) { return normalizeUnsignedShort(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_BYTE)) { + } else if (datatype.equals(XSD.UNSIGNED_BYTE)) { return normalizeUnsignedByte(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.FLOAT)) { + } else if (datatype.equals(XSD.FLOAT)) { return normalizeFloat(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DOUBLE)) { + } else if (datatype.equals(XSD.DOUBLE)) { return normalizeDouble(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.BOOLEAN)) { + } else if (datatype.equals(XSD.BOOLEAN)) { return normalizeBoolean(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DATETIME)) { + } else if (datatype.equals(XSD.DATETIME)) { return normalizeDateTime(value); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.ANYURI)) { + } else if (datatype.equals(XSD.ANYURI)) { return collapseWhiteSpace(value); } @@ -1511,40 +1511,40 @@ public static String collapseWhiteSpace(String s) { *------------------*/ public static int compare(String value1, String value2, IRI datatype) { - if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DECIMAL)) { + if (datatype.equals(XSD.DECIMAL)) { return compareDecimals(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.INTEGER)) { + } else if (datatype.equals(XSD.INTEGER)) { return compareIntegers(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NEGATIVE_INTEGER)) { + } else if (datatype.equals(XSD.NEGATIVE_INTEGER)) { return compareNegativeIntegers(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NON_POSITIVE_INTEGER)) { + } else if (datatype.equals(XSD.NON_POSITIVE_INTEGER)) { return compareNonPositiveIntegers(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.NON_NEGATIVE_INTEGER)) { + } else if (datatype.equals(XSD.NON_NEGATIVE_INTEGER)) { return compareNonNegativeIntegers(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.POSITIVE_INTEGER)) { + } else if (datatype.equals(XSD.POSITIVE_INTEGER)) { return comparePositiveIntegers(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.LONG)) { + } else if (datatype.equals(XSD.LONG)) { return compareLongs(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.INT)) { + } else if (datatype.equals(XSD.INT)) { return compareInts(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.SHORT)) { + } else if (datatype.equals(XSD.SHORT)) { return compareShorts(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.BYTE)) { + } else if (datatype.equals(XSD.BYTE)) { return compareBytes(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_LONG)) { + } else if (datatype.equals(XSD.UNSIGNED_LONG)) { return compareUnsignedLongs(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_INT)) { + } else if (datatype.equals(XSD.UNSIGNED_INT)) { return compareUnsignedInts(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_SHORT)) { + } else if (datatype.equals(XSD.UNSIGNED_SHORT)) { return compareUnsignedShorts(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.UNSIGNED_BYTE)) { + } else if (datatype.equals(XSD.UNSIGNED_BYTE)) { return compareUnsignedBytes(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.FLOAT)) { + } else if (datatype.equals(XSD.FLOAT)) { return compareFloats(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DOUBLE)) { + } else if (datatype.equals(XSD.DOUBLE)) { return compareDoubles(value1, value2); - } else if (datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DATETIME) - || datatype.equals(org.eclipse.rdf4j.model.vocabulary.XSD.DATETIMESTAMP)) { + } else if (datatype.equals(XSD.DATETIME) + || datatype.equals(XSD.DATETIMESTAMP)) { return compareDateTime(value1, value2); } else { throw new IllegalArgumentException("datatype is not ordered"); diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/BooleanLiteral.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/BooleanLiteral.java index 5c904d7d167..56f6fa9d731 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/BooleanLiteral.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/BooleanLiteral.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.model.impl; import org.eclipse.rdf4j.model.base.CoreDatatype; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * An extension of {@link SimpleLiteral} that stores a boolean value to avoid parsing. @@ -45,7 +44,7 @@ public class BooleanLiteral extends SimpleLiteral { * Creates an xsd:boolean typed literal with the specified value. */ protected BooleanLiteral(boolean value) { - super(Boolean.toString(value), XSD.BOOLEAN); + super(Boolean.toString(value), CoreDatatype.XSD.BOOLEAN); this.value = value; } diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/ContextStatement.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/ContextStatement.java deleted file mode 100644 index 6aecbec2b3a..00000000000 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/ContextStatement.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.model.impl; - -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Value; - -/** - * An extension of {@link SimpleStatement} that adds a context field. - * - * @deprecated Use {@link GenericStatement instead} - */ -@Deprecated(since = "4.1.0", forRemoval = true) -public class ContextStatement extends SimpleStatement { - - /*-----------* - * Constants * - *-----------*/ - - private static final long serialVersionUID = -4747275587477906748L; - - /** - * The statement's context, if applicable. - */ - private final Resource context; - - /*--------------* - * Constructors * - *--------------*/ - - /** - * Creates a new Statement with the supplied subject, predicate and object for the specified associated context. - * - * @param subject The statement's subject, must not be null. - * @param predicate The statement's predicate, must not be null. - * @param object The statement's object, must not be null. - * @param context The statement's context, null to indicate no context is associated. - */ - protected ContextStatement(Resource subject, IRI predicate, Value object, Resource context) { - super(subject, predicate, object); - this.context = context; - } - - /*---------* - * Methods * - *---------*/ - - @Override - public Resource getContext() { - return context; - } - - public boolean exactSameContext(Resource context) { - return context == this.context; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(256); - - sb.append(super.toString()); - sb.append(" [").append(getContext()).append("]"); - - return sb.toString(); - } -} diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/DecimalLiteral.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/DecimalLiteral.java index 7c5e9dd3497..0236c41b94a 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/DecimalLiteral.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/DecimalLiteral.java @@ -44,12 +44,6 @@ protected DecimalLiteral(BigDecimal value, IRI datatype) { this.value = value; } - @Deprecated(since = "4.0.0", forRemoval = true) - protected DecimalLiteral(BigDecimal value, XSD.Datatype datatype) { - super(value.toPlainString(), datatype); - this.value = value; - } - protected DecimalLiteral(BigDecimal value, CoreDatatype datatype) { super(value.toPlainString(), datatype); this.value = value; diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/IntegerLiteral.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/IntegerLiteral.java index 05130d64e21..25a01fa67d4 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/IntegerLiteral.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/IntegerLiteral.java @@ -32,7 +32,7 @@ public class IntegerLiteral extends SimpleLiteral { * Creates an xsd:integer literal with the specified value. */ protected IntegerLiteral(BigInteger value) { - this(value, XSD.INTEGER); + this(value, CoreDatatype.XSD.INTEGER); } /** @@ -44,13 +44,6 @@ protected IntegerLiteral(BigInteger value, IRI datatype) { this.value = value; } - @Deprecated(since = "4.0.0", forRemoval = true) - protected IntegerLiteral(BigInteger value, XSD.Datatype datatype) { - // TODO: maybe IntegerLiteralImpl should not extend LiteralImpl? - super(value.toString(), datatype); - this.value = value; - } - protected IntegerLiteral(BigInteger value, CoreDatatype datatype) { // TODO: maybe IntegerLiteralImpl should not extend LiteralImpl? super(value.toString(), datatype); diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/LinkedHashModel.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/LinkedHashModel.java index a19976807d9..8cc4f086ab1 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/LinkedHashModel.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/LinkedHashModel.java @@ -360,7 +360,7 @@ public V getValue() { } } - public static class ModelStatement extends ContextStatement { + public static class ModelStatement extends GenericStatement { private static final long serialVersionUID = 2200404772364346279L; private Statement statement; @@ -373,7 +373,7 @@ public static class ModelStatement extends ContextStatement { ModelNode ctx; - public ModelStatement(ModelNode subj, ModelNode pred, ModelNode obj, + ModelStatement(ModelNode subj, ModelNode pred, ModelNode obj, ModelNode ctx) { super(subj.getValue(), pred.getValue(), obj.getValue(), ctx.getValue()); this.subj = subj; @@ -382,7 +382,7 @@ public ModelStatement(ModelNode subj, ModelNode pred, ModelNode subj, ModelNode pred, ModelNode obj, + ModelStatement(ModelNode subj, ModelNode pred, ModelNode obj, ModelNode ctx, Statement statement) { super(subj.getValue(), pred.getValue(), obj.getValue(), ctx.getValue()); this.subj = subj; @@ -445,7 +445,7 @@ private void writeObject(ObjectOutputStream s) throws IOException { IRI pred = st.getPredicate(); Value obj = st.getObject(); Resource ctx = st.getContext(); - s.writeObject(new ContextStatement(subj, pred, obj, ctx)); + s.writeObject(new GenericStatement<>(subj, pred, obj, ctx)); } } diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/NumericLiteral.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/NumericLiteral.java index 5fa64dc86ee..95cf834e32f 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/NumericLiteral.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/NumericLiteral.java @@ -44,11 +44,6 @@ protected NumericLiteral(Number number, IRI datatype) { this.number = number; } - @Deprecated(since = "4.0.0", forRemoval = true) - protected NumericLiteral(Number number, XSD.Datatype datatype) { - this(number, datatype.getCoreDatatype()); - } - protected NumericLiteral(Number number, CoreDatatype datatype) { this.datatype = datatype; this.number = number; diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleLiteral.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleLiteral.java index ce5ef840aa9..6035a2cc642 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleLiteral.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleLiteral.java @@ -78,7 +78,7 @@ protected SimpleLiteral() { */ protected SimpleLiteral(String label) { setLabel(label); - setDatatype(org.eclipse.rdf4j.model.vocabulary.XSD.STRING); + setDatatype(CoreDatatype.XSD.STRING); optionalLanguageCache = Optional.empty(); } @@ -132,19 +132,6 @@ protected SimpleLiteral(String label, IRI datatype, CoreDatatype coreDatatype) { optionalLanguageCache = Optional.empty(); } - @Deprecated(since = "4.0.0", forRemoval = true) - protected SimpleLiteral(String label, XSD.Datatype datatype) { - setLabel(label); - if (org.eclipse.rdf4j.model.vocabulary.RDF.LANGSTRING.equals(datatype.getIri())) { - throw new IllegalArgumentException("datatype rdf:langString requires a language tag"); - } else if (datatype == null) { - setDatatype(CoreDatatype.XSD.STRING); - } else { - setDatatype(datatype.getCoreDatatype()); - } - - } - protected SimpleLiteral(String label, CoreDatatype datatype) { setLabel(label); if (datatype == CoreDatatype.RDF.LANGSTRING) { @@ -203,12 +190,6 @@ protected void setDatatype(IRI datatype, CoreDatatype coreDatatype) { } - @Deprecated(since = "4.0.0", forRemoval = true) - protected void setDatatype(XSD.Datatype datatype) { - this.datatype = datatype.getIri(); - coreDatatype = datatype.getCoreDatatype(); - } - protected void setDatatype(CoreDatatype datatype) { Objects.requireNonNull(datatype); this.datatype = datatype.getIri(); @@ -220,17 +201,6 @@ public IRI getDatatype() { return datatype; } - /** - * @return - * @deprecated Use {@link #getCoreDatatype()} instead. - */ - @Deprecated(since = "4.0.0", forRemoval = true) - public Optional getXsdDatatype() { - CoreDatatype coreDatatype = getCoreDatatype(); - - return org.eclipse.rdf4j.model.vocabulary.XSD.Datatype.from(coreDatatype.asXSDDatatype().orElse(null)); - } - // Overrides Object.equals(Object), implements Literal.equals(Object) @Override public boolean equals(Object o) { diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleStatement.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleStatement.java deleted file mode 100644 index a1c2c028526..00000000000 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleStatement.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.model.impl; - -import java.util.Objects; - -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.base.AbstractStatement; - -/** - * A simple default implementation of the {@link Statement} interface for statements that don't have an associated - * context. For statements that do have an associated context, {@link ContextStatement} can be used. - * - * @see org.eclipse.rdf4j.model.impl.SimpleValueFactory - * @deprecated Use {@link GenericStatement instead} - */ -@Deprecated(since = "4.1.0", forRemoval = true) -public class SimpleStatement extends AbstractStatement { - - /*-----------* - * Constants * - *-----------*/ - - private static final long serialVersionUID = 8707542157460228077L; - - /** - * The statement's subject. - */ - private final Resource subject; - - /** - * The statement's predicate. - */ - private final IRI predicate; - - /** - * The statement's object. - */ - private final Value object; - - /*--------------* - * Constructors * - *--------------*/ - - /** - * Creates a new Statement with the supplied subject, predicate and object. * - *

- * Note that creating SimpleStatement objects directly via this constructor is not the recommended approach. - * Instead, use a {@link org.eclipse.rdf4j.model.ValueFactory ValueFactory} (obtained from your repository or by - * using {@link org.eclipse.rdf4j.model.impl.SimpleValueFactory#getInstance()}) to create new Statement objects. - * - * @param subject The statement's subject, must not be null. - * @param predicate The statement's predicate, must not be null. - * @param object The statement's object, must not be null. - * @see org.eclipse.rdf4j.model.impl.SimpleValueFactory#createStatement(Resource, IRI, Value) - */ - protected SimpleStatement(Resource subject, IRI predicate, Value object) { - this.subject = Objects.requireNonNull(subject, "subject must not be null"); - this.predicate = Objects.requireNonNull(predicate, "predicate must not be null"); - this.object = Objects.requireNonNull(object, "object must not be null"); - } - - /*---------* - * Methods * - *---------*/ - - // Implements Statement.getSubject() - @Override - public Resource getSubject() { - return subject; - } - - // Implements Statement.getPredicate() - @Override - public IRI getPredicate() { - return predicate; - } - - // Implements Statement.getObject() - @Override - public Value getObject() { - return object; - } - - public boolean exactSameSubject(Resource subject) { - return subject == this.subject; - } - - public boolean exactSamePredicate(IRI predicate) { - return predicate == this.predicate; - } - - public boolean exactSameObject(Value object) { - return object == this.object; - } - - // Implements Statement.getContext() - @Override - public Resource getContext() { - return null; - } - -} diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleValueFactory.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleValueFactory.java index 7492ebbd479..150f9ece156 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleValueFactory.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/SimpleValueFactory.java @@ -115,12 +115,12 @@ public Literal createLiteral(String value, IRI datatype) { @Override public Statement createStatement(Resource subject, IRI predicate, Value object) { - return new SimpleStatement(subject, predicate, object); + return new GenericStatement<>(subject, predicate, object, null); } @Override public Statement createStatement(Resource subject, IRI predicate, Value object, Resource context) { - return new ContextStatement(subject, predicate, object, context); + return new GenericStatement<>(subject, predicate, object, context); } @Override @@ -138,7 +138,7 @@ public BNode createBNode() { */ @Override public Literal createLiteral(byte value) { - return createIntegerLiteral(value, org.eclipse.rdf4j.model.vocabulary.XSD.Datatype.BYTE); + return createIntegerLiteral(value, CoreDatatype.XSD.BYTE); } /** @@ -146,7 +146,7 @@ public Literal createLiteral(byte value) { */ @Override public Literal createLiteral(short value) { - return createIntegerLiteral(value, org.eclipse.rdf4j.model.vocabulary.XSD.Datatype.SHORT); + return createIntegerLiteral(value, CoreDatatype.XSD.SHORT); } /** @@ -154,7 +154,7 @@ public Literal createLiteral(short value) { */ @Override public Literal createLiteral(int value) { - return createIntegerLiteral(value, org.eclipse.rdf4j.model.vocabulary.XSD.Datatype.INT); + return createIntegerLiteral(value, CoreDatatype.XSD.INT); } /** @@ -162,7 +162,7 @@ public Literal createLiteral(int value) { */ @Override public Literal createLiteral(long value) { - return createIntegerLiteral(value, org.eclipse.rdf4j.model.vocabulary.XSD.Datatype.LONG); + return createIntegerLiteral(value, CoreDatatype.XSD.LONG); } /** @@ -172,7 +172,7 @@ protected Literal createIntegerLiteral(Number value, IRI datatype) { return createNumericLiteral(value, datatype); } - protected Literal createIntegerLiteral(Number value, XSD.Datatype datatype) { + protected Literal createIntegerLiteral(Number value, CoreDatatype.XSD datatype) { return createNumericLiteral(value, datatype); } @@ -181,7 +181,7 @@ protected Literal createIntegerLiteral(Number value, XSD.Datatype datatype) { */ @Override public Literal createLiteral(float value) { - return createFPLiteral(value, org.eclipse.rdf4j.model.vocabulary.XSD.Datatype.FLOAT); + return createFPLiteral(value, CoreDatatype.XSD.FLOAT); } /** @@ -189,17 +189,17 @@ public Literal createLiteral(float value) { */ @Override public Literal createLiteral(double value) { - return createFPLiteral(value, org.eclipse.rdf4j.model.vocabulary.XSD.Datatype.DOUBLE); + return createFPLiteral(value, CoreDatatype.XSD.DOUBLE); } @Override public Literal createLiteral(BigInteger bigInteger) { - return createIntegerLiteral(bigInteger, org.eclipse.rdf4j.model.vocabulary.XSD.INTEGER); + return createIntegerLiteral(bigInteger, CoreDatatype.XSD.INTEGER); } @Override public Literal createLiteral(BigDecimal bigDecimal) { - return createNumericLiteral(bigDecimal, org.eclipse.rdf4j.model.vocabulary.XSD.DECIMAL); + return createNumericLiteral(bigDecimal, CoreDatatype.XSD.DECIMAL); } /** @@ -209,7 +209,7 @@ protected Literal createFPLiteral(Number value, IRI datatype) { return createNumericLiteral(value, datatype); } - protected Literal createFPLiteral(Number value, XSD.Datatype datatype) { + protected Literal createFPLiteral(Number value, CoreDatatype.XSD datatype) { return createNumericLiteral(value, datatype); } @@ -226,17 +226,6 @@ protected Literal createNumericLiteral(Number number, IRI datatype) { return new NumericLiteral(number, datatype); } - @Deprecated(since = "4.0.0", forRemoval = true) - protected Literal createNumericLiteral(Number number, XSD.Datatype datatype) { - if (number instanceof BigDecimal) { - return new DecimalLiteral((BigDecimal) number, datatype); - } - if (number instanceof BigInteger) { - return new IntegerLiteral((BigInteger) number, datatype); - } - return new NumericLiteral(number, datatype); - } - protected Literal createNumericLiteral(Number number, CoreDatatype datatype) { if (number instanceof BigDecimal) { return new DecimalLiteral((BigDecimal) number, datatype); diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/TreeModel.java b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/TreeModel.java index 81aafc95507..56bab88f335 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/impl/TreeModel.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/impl/TreeModel.java @@ -540,7 +540,7 @@ private void removeFrom(StatementTree subjects) { } } - static class TreeStatement extends ContextStatement { + static class TreeStatement extends GenericStatement { private static final long serialVersionUID = -7720419322256724495L; diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/util/Configurations.java b/core/model/src/main/java/org/eclipse/rdf4j/model/util/Configurations.java index 4c520a5f824..41c46493e1f 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/util/Configurations.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/util/Configurations.java @@ -33,11 +33,35 @@ @InternalUseOnly public class Configurations { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private static final Logger logger = LoggerFactory.getLogger(Configurations.class); + /** + * Verifies if use of legacy configuration vocabulary is preferred. Defaults to false. Can be set by + * having a system property org.eclipse.rdf4j.model.vocabulary.useLegacyConfig set to + * true. + * + * @return true if org.eclipse.rdf4j.model.vocabulary.useLegacyConfig system property is + * set to true, false otherwise. + * + * @since 5.0.0 + */ + public static boolean useLegacyConfig() { + return "true".equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig")); + } + + /** + * Verifies if the supplied configuration model uses any legacy vocabulary by checking the IRIs of its properties + * + * @param configModel a configuration model + * @return true if any property IRIs start with http://www.openrdf.org/config, + * false otherwise. + */ + public static boolean hasLegacyConfiguration(Model configModel) { + return configModel.predicates() + .stream() + .anyMatch(p -> p.stringValue().startsWith("http://www.openrdf.org/config")); + } + /** * Retrieve a property value for the supplied subject as a {@link Resource} if present, falling back to a supplied * legacy property . @@ -52,13 +76,18 @@ public class Configurations { */ @InternalUseOnly public static Optional getResourceValue(Model model, Resource subject, IRI property, IRI legacyProperty) { - if (!USE_CONFIG) { - var result = Models.objectResource(model.getStatements(subject, legacyProperty, null)); - if (result.isPresent()) { - return result; - } + var preferredProperty = useLegacyConfig() ? legacyProperty : property; + var fallbackProperty = useLegacyConfig() ? property : legacyProperty; + + var preferredResult = Models.objectResource(model.getStatements(subject, preferredProperty, null)); + var fallbackResult = Models.objectResource(model.getStatements(subject, fallbackProperty, null)); + + logDiscrepancyWarning(preferredResult, fallbackResult); + + if (preferredResult.isPresent()) { + return preferredResult; } - return Models.objectResource(model.getStatements(subject, property, null)); + return fallbackResult; } /** @@ -75,13 +104,17 @@ public static Optional getResourceValue(Model model, Resource subject, */ @InternalUseOnly public static Optional getLiteralValue(Model model, Resource subject, IRI property, IRI legacyProperty) { - if (!USE_CONFIG) { - var result = Models.objectLiteral(model.getStatements(subject, legacyProperty, null)); - if (result.isPresent()) { - return result; - } + var preferredProperty = useLegacyConfig() ? legacyProperty : property; + var fallbackProperty = useLegacyConfig() ? property : legacyProperty; + + var preferredResult = Models.objectLiteral(model.getStatements(subject, preferredProperty, null)); + var fallbackResult = Models.objectLiteral(model.getStatements(subject, fallbackProperty, null)); + + logDiscrepancyWarning(preferredResult, fallbackResult); + if (preferredResult.isPresent()) { + return preferredResult; } - return Models.objectLiteral(model.getStatements(subject, property, null)); + return fallbackResult; } /** @@ -98,31 +131,27 @@ public static Optional getLiteralValue(Model model, Resource subject, I */ @InternalUseOnly public static Set getPropertyValues(Model model, Resource subject, IRI property, IRI legacyProperty) { + var preferredProperty = useLegacyConfig() ? legacyProperty : property; + var fallbackProperty = useLegacyConfig() ? property : legacyProperty; - Set objects = model.filter(subject, property, null).objects(); - Set legacyObjects = model.filter(subject, legacyProperty, null).objects(); - if (USE_CONFIG) { - legacyObjects = objects; - } else { - if (objects.isEmpty()) { - return legacyObjects; - } - } + var preferredObjects = model.filter(subject, preferredProperty, null).objects(); + var fallbackObjects = model.filter(subject, fallbackProperty, null).objects(); - if (!objects.equals(legacyObjects)) { + if (!fallbackObjects.isEmpty() && !preferredObjects.equals(fallbackObjects)) { logger.warn("Discrepancy between use of the old and new config vocabulary."); - if (objects.containsAll(legacyObjects)) { - return objects; - } else if (legacyObjects.containsAll(objects)) { - return legacyObjects; + + if (preferredObjects.containsAll(fallbackObjects)) { + return preferredObjects; + } else if (fallbackObjects.containsAll(preferredObjects)) { + return fallbackObjects; } - Set results = new HashSet<>(objects); - results.addAll(legacyObjects); + Set results = new HashSet<>(preferredObjects); + results.addAll(fallbackObjects); return results; } - return legacyObjects; + return preferredObjects; } /** @@ -139,12 +168,23 @@ public static Set getPropertyValues(Model model, Resource subject, IRI pr */ @InternalUseOnly public static Optional getIRIValue(Model model, Resource subject, IRI property, IRI legacyProperty) { - if (!USE_CONFIG) { - var result = Models.objectIRI(model.getStatements(subject, legacyProperty, null)); - if (result.isPresent()) { - return result; - } + var preferredProperty = useLegacyConfig() ? legacyProperty : property; + var fallbackProperty = useLegacyConfig() ? property : legacyProperty; + + var preferredResult = Models.objectIRI(model.getStatements(subject, preferredProperty, null)); + var fallbackResult = Models.objectIRI(model.getStatements(subject, fallbackProperty, null)); + + logDiscrepancyWarning(preferredResult, fallbackResult); + if (preferredResult.isPresent()) { + return preferredResult; + } + return fallbackResult; + } + + private static void logDiscrepancyWarning(Optional preferred, + Optional fallback) { + if (!fallback.isEmpty() && !preferred.equals(fallback)) { + logger.warn("Discrepancy between use of the old and new config vocabulary."); } - return Models.objectIRI(model.getStatements(subject, property, null)); } } diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/util/LexicalValueComparator.java b/core/model/src/main/java/org/eclipse/rdf4j/model/util/LexicalValueComparator.java index 4fc8f46c447..bbb0354a3c1 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/util/LexicalValueComparator.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/util/LexicalValueComparator.java @@ -19,6 +19,7 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Triple; import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.vocabulary.XSD; @@ -112,11 +113,12 @@ private int compareLiterals(Literal leftLit, Literal rightLit) { if (leftDatatype != null) { if (rightDatatype != null) { // Both literals have datatypes - Optional leftXmlDatatype = Literals.getXsdDatatype(leftLit); - Optional rightXmlDatatype = Literals.getXsdDatatype(rightLit); + CoreDatatype leftXmlDatatype = leftLit.getCoreDatatype(); + CoreDatatype rightXmlDatatype = rightLit.getCoreDatatype(); - if (leftXmlDatatype.isPresent() && rightXmlDatatype.isPresent()) { - result = compareDatatypes(leftXmlDatatype.get(), rightXmlDatatype.get()); + if (leftXmlDatatype.isXSDDatatype() && rightXmlDatatype.isXSDDatatype()) { + result = compareDatatypes(((CoreDatatype.XSD) leftXmlDatatype), + ((CoreDatatype.XSD) rightXmlDatatype)); } else { result = compareDatatypes(leftDatatype, rightDatatype); } @@ -184,7 +186,7 @@ private int compareDatatypes(IRI leftDatatype, IRI rightDatatype) { } } - private int compareDatatypes(XSD.Datatype leftDatatype, XSD.Datatype rightDatatype) { + private int compareDatatypes(CoreDatatype.XSD leftDatatype, CoreDatatype.XSD rightDatatype) { if (leftDatatype.isNumericDatatype()) { if (rightDatatype.isNumericDatatype()) { // both are numeric datatypes diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/util/Literals.java b/core/model/src/main/java/org/eclipse/rdf4j/model/util/Literals.java index da6dd997668..5d540d79390 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/util/Literals.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/util/Literals.java @@ -57,29 +57,11 @@ public static String getLabel(Value v, String fallback) { return v instanceof Literal ? getLabel((Literal) v, fallback) : fallback; } + @Deprecated(since = "5.0.0", forRemoval = true) public static String getLabel(Optional v, String fallback) { return v != null ? getLabel(v.orElseGet(null), fallback) : fallback; } - /** - * Retrieves the {@link org.eclipse.rdf4j.model.vocabulary.XSD.Datatype} value for the supplied Literal, if it has - * one. - * - * @param l a Literal - * @return an Optional {@link org.eclipse.rdf4j.model.vocabulary.XSD.Datatype} enum, if one is available. Note that - * the absence of this enum does not indicate that the literal has no datatype, merely that it has no - * cached enum representation of that datatype. - * @since 3.5.0 - * @deprecated Use {@link Literal#getCoreDatatype()} instead. - */ - @Deprecated(since = "4.0.0", forRemoval = true) - public static Optional getXsdDatatype(Literal l) { - if (l instanceof SimpleLiteral) { - return ((SimpleLiteral) l).getXsdDatatype(); - } - return Optional.empty(); - } - /** * Gets the byte value of the supplied literal. The fallback value is returned in case {@link Literal#byteValue()} * throws a {@link NumberFormatException}. diff --git a/core/model/src/main/java/org/eclipse/rdf4j/model/util/URIUtil.java b/core/model/src/main/java/org/eclipse/rdf4j/model/util/URIUtil.java index 381f2d9a0da..48f0b912ab6 100644 --- a/core/model/src/main/java/org/eclipse/rdf4j/model/util/URIUtil.java +++ b/core/model/src/main/java/org/eclipse/rdf4j/model/util/URIUtil.java @@ -13,7 +13,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; -import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; @@ -31,15 +30,13 @@ public class URIUtil { * URI component would conflict with the reserved purpose, then the conflicting data must be escaped before forming * the URI. http://www.isi.edu/in-notes/rfc2396.txt section 2.2. */ - private static final Set reserved = new HashSet<>( - Arrays.asList(new Character[] { ';', '/', '?', ':', '@', '&', '=', '+', '$', ',' })); + private static final Set reserved = Set.of(';', '/', '?', ':', '@', '&', '=', '+', '$', ','); /** * Punctuation mark characters, which are part of the set of unreserved chars and therefore allowed to occur in * unescaped form. See http://www.isi.edu/in-notes/rfc2396.txt */ - private static final Set mark = new HashSet<>( - Arrays.asList(new Character[] { '-', '_', '.', '!', '~', '*', '\'', '(', ')' })); + private static final Set mark = Set.of('-', '_', '.', '!', '~', '*', '\'', '(', ')'); /** * Regular expression pattern for matching unicode control characters. diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/benchmark/InstanceofBenchmark.java b/core/model/src/test/java/org/eclipse/rdf4j/model/benchmark/InstanceofBenchmark.java index 890c86b9e48..7ba9ec361b7 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/benchmark/InstanceofBenchmark.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/benchmark/InstanceofBenchmark.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.model.benchmark; -import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -57,7 +56,7 @@ public class InstanceofBenchmark { List subjects; @Setup(Level.Iteration) - public void setUp() throws InterruptedException, IOException { + public void setUp() { subjects = new ArrayList<>(); Random random = new Random(89439204); diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/impl/ContextStatementTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/impl/ContextStatementTest.java index d674859ec47..6e9dc237081 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/impl/ContextStatementTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/impl/ContextStatementTest.java @@ -40,11 +40,11 @@ public class ContextStatementTest { private static final IRI g2 = vf.createIRI("urn:g2"); @BeforeEach - public void setUp() throws Exception { + public void setUp() { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/impl/SimpleStatementTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/impl/GenericStatementTest.java similarity index 84% rename from core/model/src/test/java/org/eclipse/rdf4j/model/impl/SimpleStatementTest.java rename to core/model/src/test/java/org/eclipse/rdf4j/model/impl/GenericStatementTest.java index 90261bba048..a07b83e723b 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/impl/SimpleStatementTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/impl/GenericStatementTest.java @@ -17,13 +17,13 @@ import org.eclipse.rdf4j.model.Value; /** - * Unit tests for {@link SimpleTriple}. + * Unit tests for {@link GenericStatement}. */ -public class SimpleStatementTest extends StatementTest { +public class GenericStatementTest extends StatementTest { @Override protected Statement statement(Resource subject, IRI predicate, Value object, Resource context) { - return new ContextStatement(subject, predicate, object, context); + return new GenericStatement<>(subject, predicate, object, context); } @Override diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/impl/SimpleValueFactoryTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/impl/SimpleValueFactoryTest.java index 7f2d244c97c..b641230b6ad 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/impl/SimpleValueFactoryTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/impl/SimpleValueFactoryTest.java @@ -27,10 +27,9 @@ protected ValueFactory factory() { } /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { f = SimpleValueFactory.getInstance(); } diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/ConfigurationsTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/ConfigurationsTest.java new file mode 100644 index 00000000000..7a57ccb53e3 --- /dev/null +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/ConfigurationsTest.java @@ -0,0 +1,283 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.model.util; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.eclipse.rdf4j.model.util.Values.bnode; +import static org.eclipse.rdf4j.model.util.Values.iri; +import static org.eclipse.rdf4j.model.util.Values.literal; + +import org.assertj.core.groups.Tuple; +import org.eclipse.rdf4j.model.vocabulary.CONFIG; +import org.eclipse.rdf4j.model.vocabulary.RDFS; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + +public class ConfigurationsTest { + + private static final Logger logger = (Logger) LoggerFactory.getLogger(Configurations.class); + private static ListAppender listAppender; + + @BeforeEach + public void configureLogAppender() { + listAppender = new ListAppender<>(); + listAppender.start(); + logger.addAppender(listAppender); + } + + @Test + public void testHasLegacyConfiguration() { + { + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(iri("http://www.openrdf.org/config/testConfigProperty"), "label") + .add(CONFIG.delegate, "comment") + .build(); + + assertThat(Configurations.hasLegacyConfiguration(m)).isTrue(); + } + + { + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(CONFIG.delegate, "comment") + .add(RDFS.LABEL, "label") + .build(); + + assertThat(Configurations.hasLegacyConfiguration(m)).isFalse(); + } + } + + @Test + public void testGetLiteralValue_discrepancy() { + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label") + .add(RDFS.COMMENT, "comment") + .build(); + + var result = Configurations.getLiteralValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).contains(literal("label")); + assertLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetLiteralValue_useLegacy_discrepancy() { + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label") + .add(RDFS.COMMENT, "comment") + .build(); + + var result = Configurations.getLiteralValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + assertThat(result).contains(literal("comment")); + assertLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetLiteralValue_no_discrepancy() { + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label") + .build(); + + var result = Configurations.getLiteralValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).contains(literal("label")); + assertNotLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetLiteralValue_useLegacy_onlyNew() { + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label") + .build(); + + var result = Configurations.getLiteralValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + + assertThat(result).contains(literal("label")); + assertLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetResourceValue_discrepancy() { + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, iri("urn:label")) + .add(RDFS.COMMENT, iri("urn:comment")) + .build(); + + var result = Configurations.getResourceValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).contains(iri("urn:label")); + assertLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetResourceValue_useLegacy_discrepancy() { + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, iri("urn:label")) + .add(RDFS.COMMENT, iri("urn:comment")) + .build(); + + var result = Configurations.getResourceValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + + assertThat(result).contains(iri("urn:comment")); + assertLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetResourceValue_no_discrepancy() { + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, iri("urn:label")) + .build(); + + var result = Configurations.getResourceValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).contains(iri("urn:label")); + assertNotLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetIRIValue_discrepancy() { + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, iri("urn:label")) + .add(RDFS.COMMENT, iri("urn:comment")) + .build(); + + var result = Configurations.getIRIValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).contains(iri("urn:label")); + assertLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetIRIValue_no_discrepancy() { + var subject = bnode(); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, iri("urn:label")) + .build(); + + var result = Configurations.getIRIValue(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).contains(iri("urn:label")); + assertNotLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetPropertyValues_no_legacy() { + var subject = bnode(); + + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label 1") + .add(RDFS.LABEL, "label 2") + .build(); + + var result = Configurations.getPropertyValues(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).hasSize(2); + assertNotLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetPropertyValues_no_discrepancy() { + var subject = bnode(); + + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label 1") + .add(RDFS.LABEL, "label 2") + .add(RDFS.COMMENT, "label 1") + .add(RDFS.COMMENT, "label 2") + .build(); + + var result = Configurations.getPropertyValues(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).hasSize(2); + assertNotLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetPropertyValues_useLegacy_no_discrepancy() { + var subject = bnode(); + + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label 1") + .add(RDFS.LABEL, "label 2") + .add(RDFS.COMMENT, "label 1") + .add(RDFS.COMMENT, "label 2") + .build(); + + var result = Configurations.getPropertyValues(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).hasSize(2); + assertNotLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetPropertyValues_discrepancy() { + var subject = bnode(); + + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label 1") + .add(RDFS.LABEL, "label 2") + .add(RDFS.COMMENT, "comment 1") + .add(RDFS.COMMENT, "label 2") + .build(); + + var result = Configurations.getPropertyValues(m, subject, RDFS.LABEL, RDFS.COMMENT); + assertThat(result).hasSize(3); + assertLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + @Test + public void testGetPropertyValues_useLegacy_discrepancy() { + var subject = bnode(); + + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + var m = new ModelBuilder().subject(subject) + .add(RDFS.LABEL, "label 1") + .add(RDFS.LABEL, "label 2") + .add(RDFS.COMMENT, "comment 1") + .add(RDFS.COMMENT, "comment 2") + .build(); + + var result = Configurations.getPropertyValues(m, subject, RDFS.LABEL, RDFS.COMMENT); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + assertThat(result).hasSize(4); + + assertLogged("Discrepancy between use of the old and new config vocabulary.", Level.WARN); + } + + /* private methods */ + + private static void assertLogged(String message, Level level) { + assertThat(listAppender.list) + .extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getLevel) + .containsExactly(Tuple.tuple(message, level)); + } + + private static void assertNotLogged(String message, Level level) { + assertThat(listAppender.list) + .extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getLevel) + .doesNotContain(Tuple.tuple(message, level)); + } + +} diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/LiteralsTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/LiteralsTest.java index 2ea7f0e1595..13af1ffa324 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/LiteralsTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/LiteralsTest.java @@ -98,7 +98,7 @@ public class LiteralsTest { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#normalizeLanguageTag(String)} . */ @Test - public void testNormaliseBCP47Tag() throws Exception { + public void testNormaliseBCP47Tag() { for (String[] expectedNormalization : expectedTagNormalizations) { assertThat(Literals.normalizeLanguageTag(expectedNormalization[0])).isEqualTo(expectedNormalization[1]); @@ -115,7 +115,7 @@ public void testNormaliseBCP47Tag() throws Exception { */ @Disabled @Test - public final void testGetLabelLiteralString() throws Exception { + public final void testGetLabelLiteralString() { fail("Not yet implemented"); // TODO } @@ -125,7 +125,7 @@ public final void testGetLabelLiteralString() throws Exception { */ @Disabled @Test - public final void testGetLabelValueString() throws Exception { + public final void testGetLabelValueString() { fail("Not yet implemented"); // TODO } @@ -135,7 +135,7 @@ public final void testGetLabelValueString() throws Exception { */ @Disabled @Test - public final void testGetByteValueLiteralByte() throws Exception { + public final void testGetByteValueLiteralByte() { fail("Not yet implemented"); // TODO } @@ -144,7 +144,7 @@ public final void testGetByteValueLiteralByte() throws Exception { */ @Disabled @Test - public final void testGetByteValueValueByte() throws Exception { + public final void testGetByteValueValueByte() { fail("Not yet implemented"); // TODO } @@ -154,7 +154,7 @@ public final void testGetByteValueValueByte() throws Exception { */ @Disabled @Test - public final void testGetShortValueLiteralShort() throws Exception { + public final void testGetShortValueLiteralShort() { fail("Not yet implemented"); // TODO } @@ -164,7 +164,7 @@ public final void testGetShortValueLiteralShort() throws Exception { */ @Disabled @Test - public final void testGetShortValueValueShort() throws Exception { + public final void testGetShortValueValueShort() { fail("Not yet implemented"); // TODO } @@ -173,7 +173,7 @@ public final void testGetShortValueValueShort() throws Exception { */ @Disabled @Test - public final void testGetIntValueLiteralInt() throws Exception { + public final void testGetIntValueLiteralInt() { fail("Not yet implemented"); // TODO } @@ -182,7 +182,7 @@ public final void testGetIntValueLiteralInt() throws Exception { */ @Disabled @Test - public final void testGetIntValueValueInt() throws Exception { + public final void testGetIntValueValueInt() { fail("Not yet implemented"); // TODO } @@ -192,7 +192,7 @@ public final void testGetIntValueValueInt() throws Exception { */ @Disabled @Test - public final void testGetLongValueLiteralLong() throws Exception { + public final void testGetLongValueLiteralLong() { fail("Not yet implemented"); // TODO } @@ -201,7 +201,7 @@ public final void testGetLongValueLiteralLong() throws Exception { */ @Disabled @Test - public final void testGetLongValueValueLong() throws Exception { + public final void testGetLongValueValueLong() { fail("Not yet implemented"); // TODO } @@ -212,7 +212,7 @@ public final void testGetLongValueValueLong() throws Exception { */ @Disabled @Test - public final void testGetIntegerValueLiteralBigInteger() throws Exception { + public final void testGetIntegerValueLiteralBigInteger() { fail("Not yet implemented"); // TODO } @@ -223,7 +223,7 @@ public final void testGetIntegerValueLiteralBigInteger() throws Exception { */ @Disabled @Test - public final void testGetIntegerValueValueBigInteger() throws Exception { + public final void testGetIntegerValueValueBigInteger() { fail("Not yet implemented"); // TODO } @@ -234,7 +234,7 @@ public final void testGetIntegerValueValueBigInteger() throws Exception { */ @Disabled @Test - public final void testGetDecimalValueLiteralBigDecimal() throws Exception { + public final void testGetDecimalValueLiteralBigDecimal() { fail("Not yet implemented"); // TODO } @@ -245,7 +245,7 @@ public final void testGetDecimalValueLiteralBigDecimal() throws Exception { */ @Disabled @Test - public final void testGetDecimalValueValueBigDecimal() throws Exception { + public final void testGetDecimalValueValueBigDecimal() { fail("Not yet implemented"); // TODO } @@ -255,7 +255,7 @@ public final void testGetDecimalValueValueBigDecimal() throws Exception { */ @Disabled @Test - public final void testGetFloatValueLiteralFloat() throws Exception { + public final void testGetFloatValueLiteralFloat() { fail("Not yet implemented"); // TODO } @@ -265,7 +265,7 @@ public final void testGetFloatValueLiteralFloat() throws Exception { */ @Disabled @Test - public final void testGetFloatValueValueFloat() throws Exception { + public final void testGetFloatValueValueFloat() { fail("Not yet implemented"); // TODO } @@ -275,7 +275,7 @@ public final void testGetFloatValueValueFloat() throws Exception { */ @Disabled @Test - public final void testGetDoubleValueLiteralDouble() throws Exception { + public final void testGetDoubleValueLiteralDouble() { fail("Not yet implemented"); // TODO } @@ -285,7 +285,7 @@ public final void testGetDoubleValueLiteralDouble() throws Exception { */ @Disabled @Test - public final void testGetDoubleValueValueDouble() throws Exception { + public final void testGetDoubleValueValueDouble() { fail("Not yet implemented"); // TODO } @@ -295,7 +295,7 @@ public final void testGetDoubleValueValueDouble() throws Exception { */ @Disabled @Test - public final void testGetBooleanValueLiteralBoolean() throws Exception { + public final void testGetBooleanValueLiteralBoolean() { fail("Not yet implemented"); // TODO } @@ -305,7 +305,7 @@ public final void testGetBooleanValueLiteralBoolean() throws Exception { */ @Disabled @Test - public final void testGetBooleanValueValueBoolean() throws Exception { + public final void testGetBooleanValueValueBoolean() { fail("Not yet implemented"); // TODO } @@ -316,7 +316,7 @@ public final void testGetBooleanValueValueBoolean() throws Exception { */ @Disabled @Test - public final void testGetCalendarValueLiteralXMLGregorianCalendar() throws Exception { + public final void testGetCalendarValueLiteralXMLGregorianCalendar() { fail("Not yet implemented"); // TODO } @@ -327,7 +327,7 @@ public final void testGetCalendarValueLiteralXMLGregorianCalendar() throws Excep */ @Disabled @Test - public final void testGetCalendarValueValueXMLGregorianCalendar() throws Exception { + public final void testGetCalendarValueValueXMLGregorianCalendar() { fail("Not yet implemented"); // TODO } @@ -350,7 +350,7 @@ public final void testGetDurationValueLiteralDuration() throws Exception { * . */ @Test - public void testCreateLiteralObjectNull() throws Exception { + public void testCreateLiteralObjectNull() { Object obj = null; try { @@ -367,7 +367,7 @@ public void testCreateLiteralObjectNull() throws Exception { * . */ @Test - public void testCreateLiteralObjectBoolean() throws Exception { + public void testCreateLiteralObjectBoolean() { Object obj = Boolean.TRUE; Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -383,7 +383,7 @@ public void testCreateLiteralObjectBoolean() throws Exception { * . */ @Test - public void testCreateLiteralObjectByte() throws Exception { + public void testCreateLiteralObjectByte() { Object obj = new Integer(42).byteValue(); Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -399,7 +399,7 @@ public void testCreateLiteralObjectByte() throws Exception { * . */ @Test - public void testCreateLiteralObjectDouble() throws Exception { + public void testCreateLiteralObjectDouble() { Object obj = new Double(42); Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -415,7 +415,7 @@ public void testCreateLiteralObjectDouble() throws Exception { * . */ @Test - public void testCreateLiteralObjectFloat() throws Exception { + public void testCreateLiteralObjectFloat() { Object obj = new Float(42); Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -431,7 +431,7 @@ public void testCreateLiteralObjectFloat() throws Exception { * . */ @Test - public void testCreateLiteralObjectInteger() throws Exception { + public void testCreateLiteralObjectInteger() { Object obj = new Integer(4); Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -447,7 +447,7 @@ public void testCreateLiteralObjectInteger() throws Exception { * . */ @Test - public void testCreateLiteralObjectLong() throws Exception { + public void testCreateLiteralObjectLong() { Object obj = new Long(42); Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -463,7 +463,7 @@ public void testCreateLiteralObjectLong() throws Exception { * . */ @Test - public void testCreateLiteralObjectShort() throws Exception { + public void testCreateLiteralObjectShort() { Object obj = Short.parseShort("42"); Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -479,7 +479,7 @@ public void testCreateLiteralObjectShort() throws Exception { * . */ @Test - public void testCreateLiteralObjectXMLGregorianCalendar() throws Exception { + public void testCreateLiteralObjectXMLGregorianCalendar() { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date()); @@ -502,7 +502,7 @@ public void testCreateLiteralObjectXMLGregorianCalendar() throws Exception { * . */ @Test - public void testCreateLiteralObjectDate() throws Exception { + public void testCreateLiteralObjectDate() { Object obj = new Date(); Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -517,7 +517,7 @@ public void testCreateLiteralObjectDate() throws Exception { * . */ @Test - public void testCreateLiteralObjectString() throws Exception { + public void testCreateLiteralObjectString() { Object obj = "random unique string"; Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -533,7 +533,7 @@ public void testCreateLiteralObjectString() throws Exception { * . */ @Test - public void testCreateLiteralObjectObject() throws Exception { + public void testCreateLiteralObjectObject() { Object obj = new Object(); Literal l = Literals.createLiteral(SimpleValueFactory.getInstance(), obj); @@ -548,7 +548,7 @@ public void testCreateLiteralObjectObject() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectNull() throws Exception { + public void testCreateLiteralOrFailObjectNull() { Object obj = null; try { @@ -565,7 +565,7 @@ public void testCreateLiteralOrFailObjectNull() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectBoolean() throws Exception { + public void testCreateLiteralOrFailObjectBoolean() { Object obj = Boolean.TRUE; Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -581,7 +581,7 @@ public void testCreateLiteralOrFailObjectBoolean() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectByte() throws Exception { + public void testCreateLiteralOrFailObjectByte() { Object obj = new Integer(42).byteValue(); Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -597,7 +597,7 @@ public void testCreateLiteralOrFailObjectByte() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectDouble() throws Exception { + public void testCreateLiteralOrFailObjectDouble() { Object obj = new Double(42); Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -613,7 +613,7 @@ public void testCreateLiteralOrFailObjectDouble() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectFloat() throws Exception { + public void testCreateLiteralOrFailObjectFloat() { Object obj = new Float(42); Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -629,7 +629,7 @@ public void testCreateLiteralOrFailObjectFloat() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectInteger() throws Exception { + public void testCreateLiteralOrFailObjectInteger() { Object obj = new Integer(4); Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -645,7 +645,7 @@ public void testCreateLiteralOrFailObjectInteger() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectLong() throws Exception { + public void testCreateLiteralOrFailObjectLong() { Object obj = new Long(42); Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -661,7 +661,7 @@ public void testCreateLiteralOrFailObjectLong() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectShort() throws Exception { + public void testCreateLiteralOrFailObjectShort() { Object obj = Short.parseShort("42"); Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -677,7 +677,7 @@ public void testCreateLiteralOrFailObjectShort() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectXMLGregorianCalendar() throws Exception { + public void testCreateLiteralOrFailObjectXMLGregorianCalendar() { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date()); @@ -700,7 +700,7 @@ public void testCreateLiteralOrFailObjectXMLGregorianCalendar() throws Exception * . */ @Test - public void testCreateLiteralOrFailObjectDate() throws Exception { + public void testCreateLiteralOrFailObjectDate() { Object obj = new Date(); Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -715,7 +715,7 @@ public void testCreateLiteralOrFailObjectDate() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectString() throws Exception { + public void testCreateLiteralOrFailObjectString() { Object obj = "random unique string"; Literal l = Literals.createLiteralOrFail(SimpleValueFactory.getInstance(), obj); @@ -731,7 +731,7 @@ public void testCreateLiteralOrFailObjectString() throws Exception { * . */ @Test - public void testCreateLiteralOrFailObjectObject() throws Exception { + public void testCreateLiteralOrFailObjectObject() { Object obj = new Object(); try { @@ -748,7 +748,7 @@ public void testCreateLiteralOrFailObjectObject() throws Exception { * . */ @Test - public void testCanCreateLiteralObjectNull() throws Exception { + public void testCanCreateLiteralObjectNull() { Object obj = null; assertFalse(Literals.canCreateLiteral(obj)); @@ -758,7 +758,7 @@ public void testCanCreateLiteralObjectNull() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectBoolean() throws Exception { + public void testCanCreateLiteralObjectBoolean() { Object obj = Boolean.TRUE; assertTrue(Literals.canCreateLiteral(obj)); @@ -769,7 +769,7 @@ public void testCanCreateLiteralObjectBoolean() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectByte() throws Exception { + public void testCanCreateLiteralObjectByte() { Object obj = new Integer(42).byteValue(); assertTrue(Literals.canCreateLiteral(obj)); @@ -780,7 +780,7 @@ public void testCanCreateLiteralObjectByte() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectDouble() throws Exception { + public void testCanCreateLiteralObjectDouble() { Object obj = new Double(42); assertTrue(Literals.canCreateLiteral(obj)); @@ -791,7 +791,7 @@ public void testCanCreateLiteralObjectDouble() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectFloat() throws Exception { + public void testCanCreateLiteralObjectFloat() { Object obj = new Float(42); assertTrue(Literals.canCreateLiteral(obj)); @@ -802,7 +802,7 @@ public void testCanCreateLiteralObjectFloat() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectInteger() throws Exception { + public void testCanCreateLiteralObjectInteger() { Object obj = new Integer(4); assertTrue(Literals.canCreateLiteral(obj)); @@ -813,7 +813,7 @@ public void testCanCreateLiteralObjectInteger() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectLong() throws Exception { + public void testCanCreateLiteralObjectLong() { Object obj = new Long(42); assertTrue(Literals.canCreateLiteral(obj)); @@ -824,7 +824,7 @@ public void testCanCreateLiteralObjectLong() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectShort() throws Exception { + public void testCanCreateLiteralObjectShort() { Object obj = Short.parseShort("42"); assertTrue(Literals.canCreateLiteral(obj)); @@ -848,7 +848,7 @@ public void testCanCreateLiteralObjectXMLGregorianCalendar() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectDate() throws Exception { + public void testCanCreateLiteralObjectDate() { Object obj = new Date(); assertTrue(Literals.canCreateLiteral(obj)); @@ -859,7 +859,7 @@ public void testCanCreateLiteralObjectDate() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectString() throws Exception { + public void testCanCreateLiteralObjectString() { Object obj = "random unique string"; assertTrue(Literals.canCreateLiteral(obj)); @@ -870,7 +870,7 @@ public void testCanCreateLiteralObjectString() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#canCreateLiteral(Object)} . */ @Test - public void testCanCreateLiteralObjectObject() throws Exception { + public void testCanCreateLiteralObjectObject() { Object obj = new Object(); assertFalse(Literals.canCreateLiteral(obj)); @@ -881,7 +881,7 @@ public void testCanCreateLiteralObjectObject() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#getLabel(Optional, String)}} . */ @Test - public void testGetLabelForOptional() throws Exception { + public void testGetLabelForOptional() { Literal lit = vf.createLiteral(1.0); model.add(foo, bar, lit); @@ -896,7 +896,7 @@ public void testGetLabelForOptional() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Literals#getLabel(Optional, String)}} . */ @Test - public void testGetLabelForOptionalInFallback() throws Exception { + public void testGetLabelForOptionalInFallback() { Literal lit = vf.createLiteral(1.0); model.add(foo, bar, lit); diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/ModelBuilderTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/ModelBuilderTest.java index f5eee9f2f95..fd78c50fd4b 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/ModelBuilderTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/ModelBuilderTest.java @@ -31,7 +31,7 @@ public class ModelBuilderTest { private Model model; @BeforeEach - public void setUp() throws Exception { + public void setUp() { model = new LinkedHashModel(); testBuilder = new ModelBuilder(model); } diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/ModelCollectorTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/ModelCollectorTest.java index dab6b7a2fbb..d9a8086733b 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/ModelCollectorTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/ModelCollectorTest.java @@ -32,7 +32,7 @@ public class ModelCollectorTest { private final ValueFactory F = SimpleValueFactory.getInstance(); @BeforeEach - public void setUp() throws Exception { + public void setUp() { for (int i = 0; i < nrStmts; i++) { stmts.add(F.createStatement(F.createIRI("http://www.example.com/" + i), RDFS.LABEL, F.createLiteral(i))); } diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/NamespacesTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/NamespacesTest.java index 5dc2fcb40cc..5c6ce7ba3e7 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/NamespacesTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/NamespacesTest.java @@ -49,7 +49,7 @@ public class NamespacesTest { private String testName2; @BeforeEach - public void setUp() throws Exception { + public void setUp() { testPrefix1 = "ns1"; testPrefix2 = "ns2"; testName1 = "http://example.org/ns1#"; @@ -116,7 +116,7 @@ public final void testAsMapMultiple() { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapClear() throws Exception { + public final void testWrapClear() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); // Check no exceptions when calling clear on empty backing set @@ -137,7 +137,7 @@ public final void testWrapClear() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapContainsKey() throws Exception { + public final void testWrapContainsKey() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); // Check no exceptions when calling containsKey on empty backing set @@ -156,7 +156,7 @@ public final void testWrapContainsKey() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapContainsValue() throws Exception { + public final void testWrapContainsValue() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); // Check no exceptions when calling containsKey on empty backing set @@ -175,7 +175,7 @@ public final void testWrapContainsValue() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapEntrySet() throws Exception { + public final void testWrapEntrySet() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); @@ -204,7 +204,7 @@ public final void testWrapEntrySet() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapGet() throws Exception { + public final void testWrapGet() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); assertNull(testMap.get(testPrefix1)); @@ -220,7 +220,7 @@ public final void testWrapGet() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapIsEmpty() throws Exception { + public final void testWrapIsEmpty() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); assertTrue(testMap.isEmpty()); @@ -236,7 +236,7 @@ public final void testWrapIsEmpty() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapKeySet() throws Exception { + public final void testWrapKeySet() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); @@ -264,7 +264,7 @@ public final void testWrapKeySet() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapPut() throws Exception { + public final void testWrapPut() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); @@ -304,7 +304,7 @@ public final void testWrapPut() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapPutAll() throws Exception { + public final void testWrapPutAll() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); @@ -360,7 +360,7 @@ public final void testWrapPutAll() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapRemove() throws Exception { + public final void testWrapRemove() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); @@ -416,7 +416,7 @@ public final void testWrapRemove() throws Exception { * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}. */ @Test - public final void testWrapValues() throws Exception { + public final void testWrapValues() { Set testSet = new LinkedHashSet<>(); Map testMap = Namespaces.wrap(testSet); diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/RDFCollectionsTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/RDFCollectionsTest.java index 8dc4bd940f0..c1bbea6d5f0 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/RDFCollectionsTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/RDFCollectionsTest.java @@ -48,7 +48,7 @@ public class RDFCollectionsTest { private Literal c; @BeforeEach - public void setUp() throws Exception { + public void setUp() { a = Literals.createLiteral(vf, "A"); b = Literals.createLiteral(vf, "B"); c = Literals.createLiteral(vf, "C"); diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/RDFContainersTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/RDFContainersTest.java index b3db876c6b0..4be6702a119 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/RDFContainersTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/RDFContainersTest.java @@ -54,7 +54,7 @@ public class RDFContainersTest { private IRI RDF_3; @BeforeEach - public void setUp() throws Exception { + public void setUp() { a = Literals.createLiteral(vf, "A"); b = Literals.createLiteral(vf, "B"); c = Literals.createLiteral(vf, "C"); diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/URIUtilTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/URIUtilTest.java index f4c0c25507c..767ef29ae09 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/URIUtilTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/URIUtilTest.java @@ -21,7 +21,7 @@ public class URIUtilTest { @Test - public void testIsCorrectURISplit() throws Exception { + public void testIsCorrectURISplit() { assertTrue(URIUtil.isCorrectURISplit("http://www.example.org/page#", "")); assertTrue(URIUtil.isCorrectURISplit("http://www.example.org/page#", "1")); assertTrue(URIUtil.isCorrectURISplit("http://www.example.org/page#", "1/2")); @@ -46,7 +46,7 @@ public void testIsCorrectURISplit() throws Exception { } @Test - public void testIsValidURIReference() throws Exception { + public void testIsValidURIReference() { assertTrue(URIUtil.isValidURIReference("http://example.org/foo/bar/")); assertTrue("whitespace should be allowed", URIUtil.isValidURIReference("http://example.org/foo/bar with a lot of space/")); diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/ValuesTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/ValuesTest.java index 0914743a420..9e73b373b7c 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/ValuesTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/ValuesTest.java @@ -570,14 +570,14 @@ public void testGetValueFactory() { } @Test() - public void testLiteralObjectNull() throws Exception { + public void testLiteralObjectNull() { Object obj = null; assertThatThrownBy(() -> literal(obj)).isInstanceOf(NullPointerException.class) .hasMessageContaining("object may not be null"); } @Test - public void testLiteralObjectBoolean() throws Exception { + public void testLiteralObjectBoolean() { Object obj = Boolean.TRUE; Literal l = literal(obj); assertThat(l).isNotNull(); @@ -586,7 +586,7 @@ public void testLiteralObjectBoolean() throws Exception { } @Test - public void testLiteralObjectByte() throws Exception { + public void testLiteralObjectByte() { Object obj = Integer.valueOf(42).byteValue(); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -595,7 +595,7 @@ public void testLiteralObjectByte() throws Exception { } @Test - public void testLiteralObjectDouble() throws Exception { + public void testLiteralObjectDouble() { Object obj = Double.valueOf(42.0); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -604,7 +604,7 @@ public void testLiteralObjectDouble() throws Exception { } @Test - public void testLiteralObjectFloat() throws Exception { + public void testLiteralObjectFloat() { Object obj = Float.valueOf(42); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -613,7 +613,7 @@ public void testLiteralObjectFloat() throws Exception { } @Test - public void testLiteralObjectBigDecimal() throws Exception { + public void testLiteralObjectBigDecimal() { Object obj = BigDecimal.valueOf(42.1); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -622,7 +622,7 @@ public void testLiteralObjectBigDecimal() throws Exception { } @Test - public void testLiteralObjectInteger() throws Exception { + public void testLiteralObjectInteger() { Object obj = Integer.valueOf(42); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -631,7 +631,7 @@ public void testLiteralObjectInteger() throws Exception { } @Test - public void testLiteralObjectBigInteger() throws Exception { + public void testLiteralObjectBigInteger() { Object obj = BigInteger.valueOf(42l); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -640,7 +640,7 @@ public void testLiteralObjectBigInteger() throws Exception { } @Test - public void testLiteralObjectShort() throws Exception { + public void testLiteralObjectShort() { Object obj = Short.parseShort("42"); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -649,7 +649,7 @@ public void testLiteralObjectShort() throws Exception { } @Test - public void testLiteralObjectXMLGregorianCalendar() throws Exception { + public void testLiteralObjectXMLGregorianCalendar() { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date()); try { @@ -663,7 +663,7 @@ public void testLiteralObjectXMLGregorianCalendar() throws Exception { } @Test - public void testLiteralObjectDate() throws Exception { + public void testLiteralObjectDate() { Object obj = new Date(); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -671,7 +671,7 @@ public void testLiteralObjectDate() throws Exception { } @Test - public void testLiteralTemporalPeriod() throws Exception { + public void testLiteralTemporalPeriod() { Object obj = Period.ofWeeks(42); Literal l = literal(obj); assertThat(l).isNotNull(); @@ -680,7 +680,7 @@ public void testLiteralTemporalPeriod() throws Exception { } @Test - public void testLiteralObjectString() throws Exception { + public void testLiteralObjectString() { Object obj = "random unique string"; Literal l = literal(obj); assertThat(l).isNotNull(); @@ -689,7 +689,7 @@ public void testLiteralObjectString() throws Exception { } @Test - public void testLiteralObjectObject() throws Exception { + public void testLiteralObjectObject() { Object obj = new Object(); Literal l = literal(obj); assertThat(l).isNotNull(); diff --git a/core/model/src/test/java/org/eclipse/rdf4j/model/util/VocabulariesTest.java b/core/model/src/test/java/org/eclipse/rdf4j/model/util/VocabulariesTest.java index 42bd44cadee..070573e6f40 100644 --- a/core/model/src/test/java/org/eclipse/rdf4j/model/util/VocabulariesTest.java +++ b/core/model/src/test/java/org/eclipse/rdf4j/model/util/VocabulariesTest.java @@ -28,7 +28,7 @@ public class VocabulariesTest { @Test - public void testVocabAllIRI() throws Exception { + public void testVocabAllIRI() { Set dcIRIs = new HashSet<>(Arrays.asList(DC.CONTRIBUTOR, DC.COVERAGE, DC.CREATOR, DC.DATE, DC.DESCRIPTION, DC.FORMAT, DC.IDENTIFIER, DC.LANGUAGE, DC.PUBLISHER, DC.RELATION, DC.RIGHTS, DC.SOURCE, DC.SUBJECT, DC.TITLE, DC.TYPE)); @@ -39,7 +39,7 @@ public void testVocabAllIRI() throws Exception { } @Test - public void testVocabAllIRIHYDRA() throws Exception { + public void testVocabAllIRIHYDRA() { Set hydraIRIs = new HashSet<>(Arrays.asList(HYDRA.API_DOCUMENTATION, HYDRA.CLASS, HYDRA.COLLECTION, HYDRA.ERROR, HYDRA.IRI_TEMPLATE, HYDRA.IRI_TEMPLATE_MAPPING, HYDRA.LINK, HYDRA.OPERATION, diff --git a/core/query/pom.xml b/core/query/pom.xml index 8d3b8cf9ebb..8b1f374544e 100644 --- a/core/query/pom.xml +++ b/core/query/pom.xml @@ -42,12 +42,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/QueryResult.java b/core/query/src/main/java/org/eclipse/rdf4j/query/QueryResult.java index 05c7946ebd7..946de7a177e 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/QueryResult.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/QueryResult.java @@ -24,7 +24,7 @@ * @author Arjohn Kampman */ public interface QueryResult - extends AutoCloseable, CloseableIteration, Iterable { + extends CloseableIteration, Iterable { @Override default Iterator iterator() { diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/QueryResults.java b/core/query/src/main/java/org/eclipse/rdf4j/query/QueryResults.java index ab081daca74..90448a63c1f 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/QueryResults.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/QueryResults.java @@ -27,7 +27,6 @@ import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.common.exception.RDF4JException; import org.eclipse.rdf4j.common.iteration.AbstractCloseableIteration; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.DistinctIteration; @@ -73,7 +72,7 @@ public class QueryResults extends Iterations { * @param iteration the source iteration to get the statements from. * @return a {@link Model} containing all statements obtained from the specified source iteration. */ - public static Model asModel(CloseableIteration iteration) + public static Model asModel(CloseableIteration iteration) throws QueryEvaluationException { return asModel(iteration, new DynamicModelFactory()); } @@ -85,7 +84,7 @@ public static Model asModel(CloseableIteration iteration, + public static Model asModel(CloseableIteration iteration, ModelFactory modelFactory) throws QueryEvaluationException { Model model = modelFactory.createEmptyModel(); @@ -193,7 +192,7 @@ public static TupleQueryResult distinctResults(TupleQueryResult queryResult) { * neither {@code limit} nor {@code offset} are applied, this returns the original {@code queryResult}. */ public static TupleQueryResult limitResults(TupleQueryResult queryResult, long limit, long offset) { - CloseableIteration iter = queryResult; + CloseableIteration iter = queryResult; if (offset > 0) { iter = new OffsetIteration<>(iter, offset); } @@ -219,7 +218,7 @@ public static TupleQueryResult limitResults(TupleQueryResult queryResult, long l * neither {@code limit} nor {@code offset} are applied, this returns the original {@code queryResult}. */ public static GraphQueryResult limitResults(GraphQueryResult queryResult, long limit, long offset) { - CloseableIteration iter = queryResult; + CloseableIteration iter = queryResult; if (offset > 0) { iter = new OffsetIteration<>(iter, offset); } @@ -565,10 +564,10 @@ public static boolean bindingSetsCompatible(BindingSet bs1, BindingSet bs2) { return true; } - private static class GraphQueryResultFilter extends AbstractCloseableIteration + private static class GraphQueryResultFilter extends AbstractCloseableIteration implements GraphQueryResult { - private final DistinctIteration filter; + private final DistinctIteration filter; private final GraphQueryResult unfiltered; @@ -633,10 +632,10 @@ public Map getNamespaces() throws QueryEvaluationException { } } - private static class TupleQueryResultFilter extends AbstractCloseableIteration + private static class TupleQueryResultFilter extends AbstractCloseableIteration implements TupleQueryResult { - private final DistinctIteration filter; + private final DistinctIteration filter; private final TupleQueryResult unfiltered; diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/BackgroundGraphResult.java b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/BackgroundGraphResult.java index 34a0598f746..9ad807c32f6 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/BackgroundGraphResult.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/BackgroundGraphResult.java @@ -12,7 +12,6 @@ import java.io.InputStream; import java.io.InputStreamReader; -import java.lang.ref.WeakReference; import java.nio.charset.Charset; import java.util.Collections; import java.util.Map; @@ -33,7 +32,7 @@ * @author James Leigh */ @Deprecated(since = "4.1.0") -public class BackgroundGraphResult extends IterationWrapper +public class BackgroundGraphResult extends IterationWrapper implements GraphQueryResult, Runnable, RDFHandler { private final RDFParser parser; @@ -52,9 +51,8 @@ public class BackgroundGraphResult extends IterationWrapper queue; - public BackgroundGraphResult(RDFParser parser, InputStream in, Charset charset, String baseURI, - WeakReference callerRef) { - this(new QueueCursor<>(10, callerRef), parser, in, charset, baseURI); + public BackgroundGraphResult(RDFParser parser, InputStream in, Charset charset, String baseURI) { + this(new QueueCursor<>(10), parser, in, charset, baseURI); } public BackgroundGraphResult(QueueCursor queue, RDFParser parser, InputStream in, Charset charset, diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/GraphQueryResultImpl.java b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/GraphQueryResultImpl.java index 23f30a49a69..da47c3418cb 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/GraphQueryResultImpl.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/GraphQueryResultImpl.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * @author Jeen Broekstra @@ -24,7 +23,7 @@ public class GraphQueryResultImpl extends IteratingGraphQueryResult { public GraphQueryResultImpl(Map namespaces, - CloseableIteration statementIter) { + CloseableIteration statementIter) { super(namespaces, statementIter); } diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/IteratingGraphQueryResult.java b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/IteratingGraphQueryResult.java index 2fcbf543da9..f1348f5271c 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/IteratingGraphQueryResult.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/IteratingGraphQueryResult.java @@ -19,7 +19,6 @@ import org.eclipse.rdf4j.common.iteration.IterationWrapper; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.query.GraphQueryResult; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * An iterating implementation of the {@link GraphQueryResult} interface. @@ -28,7 +27,7 @@ * @author Jeen Broekstra */ @Deprecated(since = "4.1.0") -public class IteratingGraphQueryResult extends IterationWrapper +public class IteratingGraphQueryResult extends IterationWrapper implements GraphQueryResult { /*-----------* @@ -46,11 +45,11 @@ public IteratingGraphQueryResult(Map namespaces, Iterable namespaces, Iterator statementIter) { - this(namespaces, new CloseableIteratorIteration(statementIter)); + this(namespaces, new CloseableIteratorIteration(statementIter)); } public IteratingGraphQueryResult(Map namespaces, - CloseableIteration statementIter) { + CloseableIteration statementIter) { super(statementIter); this.namespaces = Collections.unmodifiableMap(namespaces); } diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/IteratingTupleQueryResult.java b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/IteratingTupleQueryResult.java index 3e2c6978170..4b59aafe843 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/IteratingTupleQueryResult.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/IteratingTupleQueryResult.java @@ -25,7 +25,7 @@ * An iterating implementation of the {@link TupleQueryResult} interface. */ @Deprecated(since = "4.1.0") -public class IteratingTupleQueryResult extends IterationWrapper +public class IteratingTupleQueryResult extends IterationWrapper implements TupleQueryResult { /*-----------* @@ -50,7 +50,7 @@ public IteratingTupleQueryResult(List bindingNames, Iterable bindingNames, Iterator bindingSetIter) { - this(bindingNames, new CloseableIteratorIteration(bindingSetIter)); + this(bindingNames, new CloseableIteratorIteration(bindingSetIter)); } /** @@ -61,7 +61,7 @@ public IteratingTupleQueryResult(List bindingNames, Iterator bindingNames, - CloseableIteration bindingSetIter) { + CloseableIteration bindingSetIter) { super(bindingSetIter); // Don't allow modifications to the binding names when it is accessed // through getBindingNames: diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/MutableTupleQueryResult.java b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/MutableTupleQueryResult.java index 59244828588..ef888b59ef8 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/MutableTupleQueryResult.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/MutableTupleQueryResult.java @@ -19,7 +19,6 @@ import java.util.Set; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryEvaluationException; @@ -73,15 +72,8 @@ public MutableTupleQueryResult(Collection bindingNames, Collection MutableTupleQueryResult(Collection bindingNames, - Iteration bindingSetIter) throws E { - this.bindingNames.addAll(bindingNames); - Iterations.addAll(bindingSetIter, this.bindingSets); - } - - public MutableTupleQueryResult(Collection bindingNames, - CloseableIteration bindingSetIter) throws E { + CloseableIteration bindingSetIter) throws E { this.bindingNames.addAll(bindingNames); Iterations.addAll(bindingSetIter, this.bindingSets); } diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/QueueCursor.java b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/QueueCursor.java index 43b8e265e62..7711d645ea1 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/QueueCursor.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/QueueCursor.java @@ -34,56 +34,6 @@ public QueueCursor(int capacity) { super(capacity, false); } - /** - * Creates an QueueCursor with the given (fixed) capacity and default access policy. - * - * @param capacity the capacity of this queue - * @param callerReference the thing that needs this cursor. Used to detect unexpected code failures and clean up in - * those case - * @deprecated WeakReference is no longer supported as a way to automatically close this iteration. The recommended - * approach to automatically closing an iteration on garbage collection is to use a - * {@link java.lang.ref.Cleaner}. - */ - @Deprecated(since = "4.1.2", forRemoval = true) - public QueueCursor(int capacity, WeakReference callerReference) { - this(capacity, false, callerReference); - } - - /** - * Creates an QueueCursor with the given (fixed) capacity and the specified access policy. - * - * @param capacity the capacity of this queue - * @param fair if true then queue accesses for threads blocked on insertion or removal, are - * processed in FIFO order; if false the access order is unspecified. - * @param callerReference the thing that needs this cursor. Used to detect unexpected code failures and clean up in - * those case - * @deprecated WeakReference is no longer supported as a way to automatically close this iteration. The recommended - * approach to automatically closing an iteration on garbage collection is to use a - * {@link java.lang.ref.Cleaner}. - */ - @Deprecated(since = "4.1.2", forRemoval = true) - public QueueCursor(int capacity, boolean fair, WeakReference callerReference) { - super(capacity, fair, callerReference); - } - - /** - * Creates an QueueCursor with the given {@link BlockingQueue} as its backing queue.
- * It may not be threadsafe to modify or access the given {@link BlockingQueue} from other locations. This method - * only enables the default {@link ArrayBlockingQueue} to be overridden. - * - * @param queue A BlockingQueue that is not used in other locations, but will be used as the backing Queue - * implementation for this cursor. - * @param callerReference the thing that needs this cursor. Used to detect unexpected code failures and clean up in - * those case - * @deprecated WeakReference is no longer supported as a way to automatically close this iteration. The recommended - * approach to automatically closing an iteration on garbage collection is to use a - * {@link java.lang.ref.Cleaner}. - */ - @Deprecated(since = "4.1.2", forRemoval = true) - public QueueCursor(BlockingQueue queue, WeakReference callerReference) { - super(queue, callerReference); - } - /** * Creates an QueueCursor with the given {@link BlockingQueue} as its backing queue.
* It may not be threadsafe to modify or access the given {@link BlockingQueue} from other locations. This method diff --git a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/TupleQueryResultImpl.java b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/TupleQueryResultImpl.java index 08c0f7f576b..b800e419f65 100644 --- a/core/query/src/main/java/org/eclipse/rdf4j/query/impl/TupleQueryResultImpl.java +++ b/core/query/src/main/java/org/eclipse/rdf4j/query/impl/TupleQueryResultImpl.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * @author Jeen Broekstra @@ -24,7 +23,7 @@ public class TupleQueryResultImpl extends IteratingTupleQueryResult { public TupleQueryResultImpl(List bindingNames, - CloseableIteration bindingSetIter) { + CloseableIteration bindingSetIter) { super(bindingNames, bindingSetIter); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/CloseableIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/CloseableIterationTest.java index 8de0645b08e..c75b07b2f4c 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/CloseableIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/CloseableIterationTest.java @@ -23,12 +23,12 @@ public abstract class CloseableIterationTest extends IterationTest { @Override - protected abstract CloseableIteration createTestIteration() throws Exception; + protected abstract CloseableIteration createTestIteration(); @Test public void testClosedIteration() throws Exception { for (int n = 0; n < getTestIterationSize(); n++) { - CloseableIteration iter = createTestIteration(); + CloseableIteration iter = createTestIteration(); // Close after n iterations for (int i = 0; i < n; i++) { diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/CloseableIteratorIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/CloseableIteratorIterationTest.java index 51e9842433f..1d089d85f24 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/CloseableIteratorIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/CloseableIteratorIterationTest.java @@ -13,7 +13,7 @@ public class CloseableIteratorIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new CloseableIteratorIteration<>(stringList1.iterator()); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/ConvertingIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/ConvertingIterationTest.java index bbd8ad31e9e..830cbc37e74 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/ConvertingIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/ConvertingIterationTest.java @@ -17,9 +17,9 @@ public class ConvertingIterationTest extends CloseableIterationTest { private static final List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - protected static CloseableIteration createConvertingIteration() { - Iteration intIteration = new CloseableIteratorIteration<>(intList.iterator()); - return new ConvertingIteration(intIteration) { + protected static CloseableIteration createConvertingIteration() { + CloseableIteration intIteration = new CloseableIteratorIteration<>(intList.iterator()); + return new ConvertingIteration(intIteration) { @Override protected String convert(Integer integer) { @@ -29,7 +29,7 @@ protected String convert(Integer integer) { } @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return createConvertingIteration(); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DelayedIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DelayedIterationTest.java index 5faf19f7df3..4acf7e7675d 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DelayedIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DelayedIterationTest.java @@ -13,11 +13,11 @@ public class DelayedIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { - return new DelayedIteration() { + protected CloseableIteration createTestIteration() { + return new DelayedIteration() { @Override - protected Iteration createIteration() { + protected CloseableIteration createIteration() { return createStringList1Iteration(); } }; diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctIntersectionIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctIntersectionIterationTest.java index 6df78a5b672..f9f2b6d3bd3 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctIntersectionIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctIntersectionIterationTest.java @@ -16,7 +16,7 @@ public class DistinctIntersectionIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new IntersectIteration<>(createStringList1Iteration(), createStringList2Iteration(), true); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctIterationTest.java index 0250e52db2d..bc2fbffce93 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctIterationTest.java @@ -15,7 +15,7 @@ public class DistinctIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new DistinctIteration<>(createStringList1Iteration()); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctMinusIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctMinusIterationTest.java index f106aaf862f..ed119a3b8ea 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctMinusIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/DistinctMinusIterationTest.java @@ -16,7 +16,7 @@ public class DistinctMinusIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new MinusIteration<>(createStringList1Iteration(), createStringList2Iteration(), true); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/EmptyIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/EmptyIterationTest.java index c5d9e55a0cc..bcda5c3ca47 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/EmptyIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/EmptyIterationTest.java @@ -12,12 +12,12 @@ public class EmptyIterationTest extends CloseableIterationTest { - protected static EmptyIteration createEmptyIteration() { + protected static EmptyIteration createEmptyIteration() { return new EmptyIteration<>(); } @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return createEmptyIteration(); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/ExceptionConvertingIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/ExceptionConvertingIterationTest.java index 36e3857dee7..eea61b77165 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/ExceptionConvertingIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/ExceptionConvertingIterationTest.java @@ -13,11 +13,11 @@ public class ExceptionConvertingIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { - return new ExceptionConvertingIteration(createStringList1Iteration()) { + protected CloseableIteration createTestIteration() { + return new ExceptionConvertingIteration<>(createStringList1Iteration()) { @Override - protected Exception convert(Exception e) { + protected RuntimeException convert(RuntimeException e) { return e; } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/FilterIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/FilterIterationTest.java index b00123f5970..a8f8615c5b2 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/FilterIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/FilterIterationTest.java @@ -15,11 +15,11 @@ public class FilterIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { - return new FilterIteration(createStringList1Iteration()) { + protected CloseableIteration createTestIteration() { + return new FilterIteration(createStringList1Iteration()) { @Override - protected boolean accept(String object) throws Exception { + protected boolean accept(String object) { return "3".equals(object); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IntersectionIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IntersectionIterationTest.java index 380d6318bc4..9bb997cf05b 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IntersectionIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IntersectionIterationTest.java @@ -16,7 +16,7 @@ public class IntersectionIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new IntersectIteration<>(createStringList1Iteration(), createStringList2Iteration()); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IterationTest.java index 903efb5eea0..c4ed5fef542 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IterationTest.java @@ -23,21 +23,21 @@ public abstract class IterationTest { protected static final List stringList2 = Arrays.asList("4", "5", "6", "7", "8"); - protected static CloseableIteration createStringList1Iteration() { + protected static CloseableIteration createStringList1Iteration() { return new CloseableIteratorIteration<>(stringList1.iterator()); } - protected static CloseableIteration createStringList2Iteration() { + protected static CloseableIteration createStringList2Iteration() { return new CloseableIteratorIteration<>(stringList2.iterator()); } - protected abstract Iteration createTestIteration() throws Exception; + protected abstract CloseableIteration createTestIteration(); protected abstract int getTestIterationSize(); @Test public void testFullIteration() throws Exception { - Iteration iter = createTestIteration(); + CloseableIteration iter = createTestIteration(); int count = 0; while (iter.hasNext()) { diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IteratorIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IteratorIterationTest.java index 2fd95878013..ffecef51861 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IteratorIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/IteratorIterationTest.java @@ -13,7 +13,7 @@ public class IteratorIterationTest extends IterationTest { @Override - protected Iteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new IteratorIteration<>(stringList1.iterator()); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/LimitIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/LimitIterationTest.java index ae21e208911..142c40dd5a6 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/LimitIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/LimitIterationTest.java @@ -18,12 +18,12 @@ public class LimitIterationTest extends CloseableIterationTest { - protected static LimitIteration createLimitIteration(int limit) { + protected static LimitIteration createLimitIteration(int limit) { return new LimitIteration<>(createStringList1Iteration(), limit); } @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return createLimitIteration(5); } @@ -35,7 +35,7 @@ protected int getTestIterationSize() { @Test public void testInRangeOffset() throws Exception { for (int limit = 0; limit < stringList1.size(); limit++) { - Iteration iter = createLimitIteration(limit); + CloseableIteration iter = createLimitIteration(limit); List resultList = Iterations.asList(iter); List expectedList = stringList1.subList(0, limit); assertEquals(expectedList, resultList, "testInRangeOffset failed for limit: " + limit); @@ -44,7 +44,7 @@ public void testInRangeOffset() throws Exception { @Test public void testOutOfRangeOffset() throws Exception { - Iteration iter = createLimitIteration(2 * stringList1.size()); + CloseableIteration iter = createLimitIteration(2 * stringList1.size()); List resultList = Iterations.asList(iter); assertEquals(stringList1, resultList); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/LookAheadIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/LookAheadIterationTest.java index 8acf0132798..2afb16e3640 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/LookAheadIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/LookAheadIterationTest.java @@ -15,13 +15,13 @@ public class LookAheadIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { final Iterator iter = stringList1.iterator(); - return new LookAheadIteration() { + return new LookAheadIteration() { @Override - protected String getNextElement() throws Exception { + protected String getNextElement() { if (iter.hasNext()) { return iter.next(); } else { diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/MinusIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/MinusIterationTest.java index 3178b4a9543..7694a183341 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/MinusIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/MinusIterationTest.java @@ -16,7 +16,7 @@ public class MinusIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new MinusIteration<>(createStringList1Iteration(), createStringList2Iteration()); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/OffsetIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/OffsetIterationTest.java index 440523d1627..03988f26763 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/OffsetIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/OffsetIterationTest.java @@ -19,12 +19,12 @@ public class OffsetIterationTest extends CloseableIterationTest { - protected static OffsetIteration createOffsetIteration(int offset) { + protected static OffsetIteration createOffsetIteration(int offset) { return new OffsetIteration<>(createStringList1Iteration(), offset); } @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return createOffsetIteration(5); } @@ -36,7 +36,7 @@ protected int getTestIterationSize() { @Test public void testInRangeOffset() throws Exception { for (int offset = 0; offset < stringList1.size(); offset++) { - Iteration iter = createOffsetIteration(offset); + CloseableIteration iter = createOffsetIteration(offset); List resultList = Iterations.asList(iter); List expectedList = stringList1.subList(offset, stringList1.size()); assertEquals(expectedList, resultList, "test failed for offset: " + offset); @@ -45,7 +45,7 @@ public void testInRangeOffset() throws Exception { @Test public void testOutOfRangeOffset() throws Exception { - Iteration iter = createOffsetIteration(2 * stringList1.size()); + CloseableIteration iter = createOffsetIteration(2 * stringList1.size()); List resultList = Iterations.asList(iter); assertEquals(Collections.emptyList(), resultList); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/SingletonIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/SingletonIterationTest.java index e453c705c5c..02fc28669cd 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/SingletonIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/SingletonIterationTest.java @@ -13,7 +13,7 @@ public class SingletonIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new SingletonIteration<>("3"); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/UnionIterationTest.java b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/UnionIterationTest.java index e44b225fb0a..2f4f76c5ce2 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/UnionIterationTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/common/iteration/UnionIterationTest.java @@ -17,7 +17,7 @@ public class UnionIterationTest extends CloseableIterationTest { @Override - protected CloseableIteration createTestIteration() { + protected CloseableIteration createTestIteration() { return new UnionIteration<>(createStringList1Iteration(), createStringList2Iteration()); } @@ -28,10 +28,10 @@ protected int getTestIterationSize() { @Test public void testArgumentsClosed() throws Exception { - SingletonIteration iter1 = new SingletonIteration<>("1"); - SingletonIteration iter2 = new SingletonIteration<>("2"); - SingletonIteration iter3 = new SingletonIteration<>("3"); - try (UnionIteration unionIter = new UnionIteration<>(iter1, iter2, iter3)) { + SingletonIteration iter1 = new SingletonIteration<>("1"); + SingletonIteration iter2 = new SingletonIteration<>("2"); + SingletonIteration iter3 = new SingletonIteration<>("3"); + try (UnionIteration unionIter = new UnionIteration<>(iter1, iter2, iter3)) { unionIter.next(); } diff --git a/core/query/src/test/java/org/eclipse/rdf4j/query/QueryResultsTest.java b/core/query/src/test/java/org/eclipse/rdf4j/query/QueryResultsTest.java index 6fd45e8d40d..23035e7128f 100644 --- a/core/query/src/test/java/org/eclipse/rdf4j/query/QueryResultsTest.java +++ b/core/query/src/test/java/org/eclipse/rdf4j/query/QueryResultsTest.java @@ -224,7 +224,7 @@ public void testBindingSetsCompatible() { } } - private class StubGraphQueryResult extends AbstractCloseableIteration + private class StubGraphQueryResult extends AbstractCloseableIteration implements GraphQueryResult { private final List statements = new ArrayList<>(); diff --git a/core/queryalgebra/evaluation/pom.xml b/core/queryalgebra/evaluation/pom.xml index 8fdff2a4cdc..558421515d8 100644 --- a/core/queryalgebra/evaluation/pom.xml +++ b/core/queryalgebra/evaluation/pom.xml @@ -83,10 +83,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/AbstractQueryPreparer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/AbstractQueryPreparer.java deleted file mode 100644 index b38aad74f14..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/AbstractQueryPreparer.java +++ /dev/null @@ -1,333 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.ConvertingIteration; -import org.eclipse.rdf4j.common.iteration.FilterIteration; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.BooleanQuery; -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.GraphQuery; -import org.eclipse.rdf4j.query.GraphQueryResult; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.QueryResults; -import org.eclipse.rdf4j.query.TupleQuery; -import org.eclipse.rdf4j.query.TupleQueryResult; -import org.eclipse.rdf4j.query.TupleQueryResultHandler; -import org.eclipse.rdf4j.query.TupleQueryResultHandlerException; -import org.eclipse.rdf4j.query.Update; -import org.eclipse.rdf4j.query.UpdateExecutionException; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.UpdateExpr; -import org.eclipse.rdf4j.query.explanation.Explanation; -import org.eclipse.rdf4j.query.impl.IteratingGraphQueryResult; -import org.eclipse.rdf4j.query.impl.IteratingTupleQueryResult; -import org.eclipse.rdf4j.query.parser.ParsedBooleanQuery; -import org.eclipse.rdf4j.query.parser.ParsedGraphQuery; -import org.eclipse.rdf4j.query.parser.ParsedTupleQuery; -import org.eclipse.rdf4j.query.parser.ParsedUpdate; -import org.eclipse.rdf4j.query.parser.impl.AbstractParserQuery; -import org.eclipse.rdf4j.query.parser.impl.AbstractParserUpdate; -import org.eclipse.rdf4j.rio.RDFHandler; -import org.eclipse.rdf4j.rio.RDFHandlerException; - -public abstract class AbstractQueryPreparer implements QueryPreparer { - - private final TripleSource tripleSource; - - public AbstractQueryPreparer(TripleSource tripleSource) { - this.tripleSource = tripleSource; - } - - @Override - public BooleanQuery prepare(ParsedBooleanQuery q) { - return new BooleanQueryImpl(q); - } - - @Override - public TupleQuery prepare(ParsedTupleQuery q) { - return new TupleQueryImpl(q); - } - - @Override - public GraphQuery prepare(ParsedGraphQuery q) { - return new GraphQueryImpl(q); - } - - @Override - public Update prepare(ParsedUpdate u) { - return new UpdateImpl(u); - } - - @Override - public TripleSource getTripleSource() { - return tripleSource; - } - - protected abstract CloseableIteration evaluate(TupleExpr tupleExpr, - Dataset dataset, BindingSet bindings, boolean includeInferred, int maxExecutionTime) - throws QueryEvaluationException; - - protected abstract void execute(UpdateExpr updateExpr, Dataset dataset, BindingSet bindings, - boolean includeInferred, int maxExecutionTime) throws UpdateExecutionException; - - class BooleanQueryImpl extends AbstractParserQuery implements BooleanQuery { - - BooleanQueryImpl(ParsedBooleanQuery query) { - super(query); - } - - @Override - public ParsedBooleanQuery getParsedQuery() { - return (ParsedBooleanQuery) super.getParsedQuery(); - } - - @Override - public boolean evaluate() throws QueryEvaluationException { - CloseableIteration bindingsIter1 = null; - CloseableIteration bindingsIter2 = null; - try { - ParsedBooleanQuery parsedBooleanQuery = getParsedQuery(); - TupleExpr tupleExpr = parsedBooleanQuery.getTupleExpr(); - Dataset dataset = getDataset(); - if (dataset == null) { - // No external dataset specified, use query's own dataset (if any) - dataset = parsedBooleanQuery.getDataset(); - } - - bindingsIter1 = AbstractQueryPreparer.this.evaluate(tupleExpr, dataset, getBindings(), - getIncludeInferred(), getMaxExecutionTime()); - bindingsIter2 = enforceMaxQueryTime(bindingsIter1); - - return bindingsIter2.hasNext(); - } finally { - try { - if (bindingsIter2 != null) { - bindingsIter2.close(); - } - } finally { - if (bindingsIter1 != null) { - bindingsIter1.close(); - } - } - } - } - - @Override - public Explanation explain(Explanation.Level level) { - throw new UnsupportedOperationException(); - } - } - - class TupleQueryImpl extends AbstractParserQuery implements TupleQuery { - - TupleQueryImpl(ParsedTupleQuery query) { - super(query); - } - - @Override - public ParsedTupleQuery getParsedQuery() { - return (ParsedTupleQuery) super.getParsedQuery(); - } - - @Override - public TupleQueryResult evaluate() throws QueryEvaluationException { - CloseableIteration bindingsIter1 = null; - CloseableIteration bindingsIter2 = null; - IteratingTupleQueryResult result = null; - boolean allGood = false; - try { - TupleExpr tupleExpr = getParsedQuery().getTupleExpr(); - bindingsIter1 = AbstractQueryPreparer.this.evaluate(tupleExpr, getActiveDataset(), getBindings(), - getIncludeInferred(), getMaxExecutionTime()); - bindingsIter2 = enforceMaxQueryTime(bindingsIter1); - result = new IteratingTupleQueryResult(new ArrayList<>(tupleExpr.getBindingNames()), bindingsIter2); - allGood = true; - return result; - } finally { - if (!allGood) { - try { - if (result != null) { - result.close(); - } - } finally { - try { - if (bindingsIter2 != null) { - bindingsIter2.close(); - } - } finally { - if (bindingsIter1 != null) { - bindingsIter1.close(); - } - } - } - } - } - } - - @Override - public void evaluate(TupleQueryResultHandler handler) - throws QueryEvaluationException, TupleQueryResultHandlerException { - TupleQueryResult queryResult = evaluate(); - QueryResults.report(queryResult, handler); - } - - @Override - public Explanation explain(Explanation.Level level) { - throw new UnsupportedOperationException(); - } - } - - class GraphQueryImpl extends AbstractParserQuery implements GraphQuery { - - GraphQueryImpl(ParsedGraphQuery query) { - super(query); - } - - @Override - public ParsedGraphQuery getParsedQuery() { - return (ParsedGraphQuery) super.getParsedQuery(); - } - - @Override - public GraphQueryResult evaluate() throws QueryEvaluationException { - CloseableIteration bindingsIter1 = null; - CloseableIteration bindingsIter2 = null; - CloseableIteration bindingsIter3 = null; - CloseableIteration stIter = null; - IteratingGraphQueryResult result = null; - - boolean allGood = false; - try { - TupleExpr tupleExpr = getParsedQuery().getTupleExpr(); - bindingsIter1 = AbstractQueryPreparer.this.evaluate(tupleExpr, getActiveDataset(), getBindings(), - getIncludeInferred(), getMaxExecutionTime()); - - // Filters out all partial and invalid matches - bindingsIter2 = new FilterIteration(bindingsIter1) { - - @Override - protected boolean accept(BindingSet bindingSet) { - Value context = bindingSet.getValue("context"); - - return bindingSet.getValue("subject") instanceof Resource - && bindingSet.getValue("predicate") instanceof IRI - && bindingSet.getValue("object") instanceof Value - && (context == null || context instanceof Resource); - } - }; - - bindingsIter3 = enforceMaxQueryTime(bindingsIter2); - - // Convert the BindingSet objects to actual RDF statements - stIter = new ConvertingIteration(bindingsIter3) { - - private final ValueFactory vf = tripleSource.getValueFactory(); - - @Override - protected Statement convert(BindingSet bindingSet) { - Resource subject = (Resource) bindingSet.getValue("subject"); - IRI predicate = (IRI) bindingSet.getValue("predicate"); - Value object = bindingSet.getValue("object"); - Resource context = (Resource) bindingSet.getValue("context"); - - if (context == null) { - return vf.createStatement(subject, predicate, object); - } else { - return vf.createStatement(subject, predicate, object, context); - } - } - }; - - result = new IteratingGraphQueryResult(getParsedQuery().getQueryNamespaces(), stIter); - allGood = true; - return result; - } finally { - if (!allGood) { - try { - if (result != null) { - result.close(); - } - } finally { - try { - if (stIter != null) { - stIter.close(); - } - } finally { - try { - if (bindingsIter3 != null) { - bindingsIter3.close(); - } - } finally { - try { - if (bindingsIter2 != null) { - bindingsIter2.close(); - } - } finally { - if (bindingsIter1 != null) { - bindingsIter1.close(); - } - } - } - } - } - } - } - } - - @Override - public void evaluate(RDFHandler handler) throws QueryEvaluationException, RDFHandlerException { - GraphQueryResult queryResult = evaluate(); - QueryResults.report(queryResult, handler); - } - - @Override - public Explanation explain(Explanation.Level level) { - throw new UnsupportedOperationException(); - } - } - - class UpdateImpl extends AbstractParserUpdate { - - UpdateImpl(ParsedUpdate update) { - super(update); - } - - @Override - public void execute() throws UpdateExecutionException { - ParsedUpdate parsedUpdate = getParsedUpdate(); - List updateExprs = parsedUpdate.getUpdateExprs(); - Map datasetMapping = parsedUpdate.getDatasetMapping(); - for (UpdateExpr updateExpr : updateExprs) { - Dataset activeDataset = getMergedDataset(datasetMapping.get(updateExpr)); - - try { - AbstractQueryPreparer.this.execute(updateExpr, activeDataset, getBindings(), getIncludeInferred(), - getMaxExecutionTime()); - } catch (UpdateExecutionException e) { - if (!updateExpr.isSilent()) { - throw e; - } - } - } - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/ArrayBindingSet.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/ArrayBindingSet.java index e1b42a46866..242cb73a71b 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/ArrayBindingSet.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/ArrayBindingSet.java @@ -131,7 +131,7 @@ public Function getDirectGetBinding(String bindingName if (index == -1) { return null; } - return (a) -> { + return a -> { Value value = a.values[index]; if (value != null) { return new SimpleBinding(bindingName, value); @@ -147,7 +147,7 @@ public Function getDirectGetValue(String bindingName) { if (index == -1) { return null; } - return (a) -> a.values[index]; + return a -> a.values[index]; } @@ -156,7 +156,7 @@ public Function getDirectHasBinding(String bindingName if (index == -1) { return null; } - return (a) -> a.whichBindingsHaveBeenSet[index]; + return a -> a.whichBindingsHaveBeenSet[index]; } private int getIndex(String bindingName) { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/EvaluationStrategy.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/EvaluationStrategy.java index 224388e86d5..c3e6c67f982 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/EvaluationStrategy.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/EvaluationStrategy.java @@ -73,18 +73,6 @@ public interface EvaluationStrategy extends FederatedServiceResolver { TupleExpr optimize(TupleExpr expr, EvaluationStatistics evaluationStatistics, BindingSet bindings); - /** - * Evaluates the tuple expression against the supplied triple source with the specified set of variable bindings as - * input. - * - * @param expr The Service Expression to evaluate - * @param serviceUri TODO - * @param bindings The variables bindings iterator to use for evaluating the expression, if applicable. - * @return A closeable iterator over all of variable binding sets that match the tuple expression. - */ - CloseableIteration evaluate(Service expr, String serviceUri, - CloseableIteration bindings) throws QueryEvaluationException; - /** * Evaluates the tuple expression against the supplied triple source with the specified set of variable bindings as * input. @@ -93,7 +81,7 @@ CloseableIteration evaluate(Service expr, * @param bindings The variables bindings to use for evaluating the expression, if applicable. * @return A closeable iterator over the variable binding sets that match the tuple expression. */ - CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) + CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) throws QueryEvaluationException; /** @@ -103,13 +91,9 @@ CloseableIteration evaluate(TupleExpr expr * @param expr that is to be evaluated later * @return a QueryEvaluationStep that may avoid doing repeating the same work over and over. */ - default QueryEvaluationStep precompile(TupleExpr expr) { - return QueryEvaluationStep.minimal(this, expr); - } + QueryEvaluationStep precompile(TupleExpr expr); - default QueryEvaluationStep precompile(TupleExpr expr, QueryEvaluationContext context) { - return QueryEvaluationStep.minimal(this, expr); - } + QueryEvaluationStep precompile(TupleExpr expr, QueryEvaluationContext context); /** * Gets the value of this expression. @@ -186,15 +170,15 @@ default Queue makeQueue() { /** * Set the collection factory that will create the collections to use during query evaluaton. * - * @param a CollectionFactory that should be used during future query evaluations + * @param collectionFactory CollectionFactory that should be used during future query evaluations **/ @Experimental - public default void setCollectionFactory(Supplier collectionFactory) { + default void setCollectionFactory(Supplier collectionFactory) { // Do nothing per default. Implementations should take this value and use it } @Experimental - public default Supplier getCollectionFactory() { + default Supplier getCollectionFactory() { return DefaultCollectionFactory::new; } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/QueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/QueryEvaluationStep.java index 3c4091bf4b1..59c3662b90f 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/QueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/QueryEvaluationStep.java @@ -31,7 +31,7 @@ public interface QueryEvaluationStep { */ @Deprecated(since = "4.1.0", forRemoval = true) class DelayedEvaluationIteration - extends DelayedIteration { + extends DelayedIteration { private final QueryEvaluationStep arg; private final BindingSet bs; @@ -41,16 +41,16 @@ public DelayedEvaluationIteration(QueryEvaluationStep arg, BindingSet bs) { } @Override - protected CloseableIteration createIteration() + protected CloseableIteration createIteration() throws QueryEvaluationException { return arg.evaluate(bs); } } - EmptyIteration EMPTY_ITERATION = new EmptyIteration<>(); + EmptyIteration EMPTY_ITERATION = new EmptyIteration<>(); QueryEvaluationStep EMPTY = bindings -> EMPTY_ITERATION; - CloseableIteration evaluate(BindingSet bindings); + CloseableIteration evaluate(BindingSet bindings); /** * A fall back implementation that wraps a pre-existing evaluate method on a strategy @@ -76,7 +76,7 @@ static QueryEvaluationStep empty() { * @return a new evaluation step that executes wrap on the inner qes. */ static QueryEvaluationStep wrap(QueryEvaluationStep qes, - Function, CloseableIteration> wrap) { + Function, CloseableIteration> wrap) { return bs -> wrap.apply(qes.evaluate(bs)); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/RDFStarTripleSource.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/RDFStarTripleSource.java index a9af0e889a4..eb52e4ed199 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/RDFStarTripleSource.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/RDFStarTripleSource.java @@ -28,7 +28,7 @@ public interface RDFStarTripleSource extends TripleSource { * @return An iterator over the relevant triples. * @throws QueryEvaluationException If the rdf star triple source failed to get the statements. */ - CloseableIteration getRdfStarTriples(Resource subj, IRI pred, + CloseableIteration getRdfStarTriples(Resource subj, IRI pred, Value obj) throws QueryEvaluationException; } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/TripleSource.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/TripleSource.java index d0cf10996d7..584c0dd23ae 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/TripleSource.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/TripleSource.java @@ -26,8 +26,8 @@ */ public interface TripleSource { - EmptyIteration EMPTY_ITERATION = new EmptyIteration<>(); - EmptyIteration EMPTY_TRIPLE_ITERATION = new EmptyIteration<>(); + EmptyIteration EMPTY_ITERATION = new EmptyIteration<>(); + EmptyIteration EMPTY_TRIPLE_ITERATION = new EmptyIteration<>(); /** * Gets all statements that have a specific subject, predicate and/or object. All three parameters may be null to @@ -42,7 +42,7 @@ public interface TripleSource { * @return An iterator over the relevant statements. * @throws QueryEvaluationException If the triple source failed to get the statements. */ - CloseableIteration getStatements(Resource subj, IRI pred, + CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException; /** diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/FederatedServiceResolverBase.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/FederatedServiceResolverBase.java deleted file mode 100644 index 2866d51bf81..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/FederatedServiceResolverBase.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.federation; - -/** - * @author Jeen Broekstra - * @deprecated Use {@link AbstractFederatedServiceResolver} instead. - */ -@Deprecated(since = "4.0") -public abstract class FederatedServiceResolverBase extends AbstractFederatedServiceResolver { - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/JoinExecutorBase.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/JoinExecutorBase.java deleted file mode 100644 index d310d8ab8f1..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/JoinExecutorBase.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.federation; - -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.LookAheadIteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.algebra.TupleExpr; - -/** - * Base class for any join parallel join executor. Note that this class extends {@link LookAheadIteration} and thus any - * implementation of this class is applicable for pipelining when used in a different thread (access to shared variables - * is synchronized). - * - * @author Andreas Schwarte - * @deprecated Use {@link org.eclipse.rdf4j.repository.sparql.federation.JoinExecutorBase} - */ -@Deprecated(since = "2.3") -public abstract class JoinExecutorBase extends org.eclipse.rdf4j.repository.sparql.federation.JoinExecutorBase { - - public JoinExecutorBase(CloseableIteration leftIter, TupleExpr rightArg, - BindingSet bindings) throws QueryEvaluationException { - super(leftIter, rightArg, bindings); - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/RepositoryFederatedService.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/RepositoryFederatedService.java deleted file mode 100644 index 96f429e928e..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/RepositoryFederatedService.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.federation; - -import org.eclipse.rdf4j.repository.Repository; - -/** - * Federated Service wrapping the {@link Repository} to communicate with a SPARQL endpoint. - * - * @author Andreas Schwarte - * @deprecated Use {@link org.eclipse.rdf4j.repository.sparql.federation.RepositoryFederatedService} - */ -@Deprecated(since = "2.3") -public class RepositoryFederatedService - extends org.eclipse.rdf4j.repository.sparql.federation.RepositoryFederatedService { - - public RepositoryFederatedService(Repository repo, boolean shutDown) { - super(repo, shutDown); - } - - public RepositoryFederatedService(Repository repo) { - super(repo); - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/SPARQLFederatedService.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/SPARQLFederatedService.java deleted file mode 100644 index 43edbeaa594..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/SPARQLFederatedService.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.federation; - -import org.eclipse.rdf4j.http.client.HttpClientSessionManager; -import org.eclipse.rdf4j.repository.sparql.SPARQLRepository; - -/** - * Federated Service wrapping the {@link SPARQLRepository} to communicate with a SPARQL endpoint. - * - * @author Andreas Schwarte - * @deprecated Use {@link org.eclipse.rdf4j.repository.sparql.federation.SPARQLFederatedService} - */ -@Deprecated(since = "2.3") -public class SPARQLFederatedService extends org.eclipse.rdf4j.repository.sparql.federation.SPARQLFederatedService { - - public SPARQLFederatedService(String serviceUrl, HttpClientSessionManager client) { - super(serviceUrl, client); - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceCrossProductIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceCrossProductIteration.java deleted file mode 100644 index 11b00a5e899..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceCrossProductIteration.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.federation; - -import java.util.List; - -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.algebra.evaluation.iterator.CrossProductIteration; - -/** - * Iteration which forms the cross product of a list of materialized input bindings with each result obtained from the - * inner iteration. See {@link SPARQLFederatedService}. Example: inputBindings := {b1, b2, ...} resultIteration - * := {r1, r2, ...} getNextElement() returns (r1,b1), (r1, b2), ..., (r2, b1), (r2, b2), ... i.e. compute the cross - * product per result binding - * - * @author Andreas Schwarte - */ -@Deprecated -public class ServiceCrossProductIteration extends CrossProductIteration { - - public ServiceCrossProductIteration(CloseableIteration resultIteration, - List inputBindings) { - super(resultIteration, inputBindings); - } - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceJoinConversionIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceJoinConversionIteration.java deleted file mode 100644 index eb44632f449..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceJoinConversionIteration.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.federation; - -import java.util.List; - -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; - -/** - * Inserts original bindings into the result, uses ?__rowIdx to resolve original bindings. See - * {@link ServiceJoinIterator} and {@link SPARQLFederatedService}. - * - * @author Andreas Schwarte - * @deprecated since 2.3 use {@link org.eclipse.rdf4j.repository.sparql.federation.ServiceJoinConversionIteration} - */ -@Deprecated(since = "2.3", forRemoval = true) -public class ServiceJoinConversionIteration - extends org.eclipse.rdf4j.repository.sparql.federation.ServiceJoinConversionIteration { - - public ServiceJoinConversionIteration(CloseableIteration iter, - List bindings) { - super(iter, bindings); - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceJoinIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceJoinIterator.java index 5a9986835d9..80320e021d9 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceJoinIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/ServiceJoinIterator.java @@ -16,6 +16,7 @@ import org.eclipse.rdf4j.query.algebra.Service; import org.eclipse.rdf4j.query.algebra.Var; import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; +import org.eclipse.rdf4j.repository.sparql.federation.JoinExecutorBase; /** * Iterator for efficient SERVICE evaluation (vectored). SERVICE is the right handside argument of this join. @@ -37,7 +38,7 @@ public class ServiceJoinIterator extends JoinExecutorBase { * @param strategy * @throws QueryEvaluationException */ - public ServiceJoinIterator(CloseableIteration leftIter, Service service, + public ServiceJoinIterator(CloseableIteration leftIter, Service service, BindingSet bindings, EvaluationStrategy strategy) throws QueryEvaluationException { super(leftIter, service, bindings); this.service = service; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/TupleFunctionFederatedService.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/TupleFunctionFederatedService.java deleted file mode 100644 index bed23440262..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/TupleFunctionFederatedService.java +++ /dev/null @@ -1,202 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.federation; - -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Set; - -import org.eclipse.rdf4j.common.iteration.AbstractCloseableIteration; -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.DistinctIteration; -import org.eclipse.rdf4j.common.iteration.SilentIteration; -import org.eclipse.rdf4j.common.iteration.SingletonIteration; -import org.eclipse.rdf4j.common.iteration.UnionIteration; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.algebra.Service; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.TupleFunctionCall; -import org.eclipse.rdf4j.query.algebra.ValueConstant; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.Var; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; -import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; -import org.eclipse.rdf4j.query.algebra.evaluation.function.TupleFunction; -import org.eclipse.rdf4j.query.algebra.evaluation.function.TupleFunctionRegistry; -import org.eclipse.rdf4j.query.algebra.evaluation.impl.TupleFunctionEvaluationStrategy; -import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtil; - -/** - * A federated service that can evaluate {@link TupleFunction}s. - */ -public class TupleFunctionFederatedService implements FederatedService { - - private final TupleFunctionRegistry tupleFunctionRegistry; - - private final ValueFactory vf; - - private boolean isInitialized; - - public TupleFunctionFederatedService(TupleFunctionRegistry tupleFunctionRegistry, ValueFactory vf) { - this.tupleFunctionRegistry = tupleFunctionRegistry; - this.vf = vf; - } - - @Override - public boolean isInitialized() { - return isInitialized; - } - - @Override - public void initialize() { - isInitialized = true; - } - - @Override - public void shutdown() { - isInitialized = false; - } - - @Override - public boolean ask(Service service, BindingSet bindings, String baseUri) throws QueryEvaluationException { - try (final CloseableIteration iter = evaluate(service, - new SingletonIteration<>(bindings), baseUri)) { - if (iter.hasNext()) { - BindingSet bs = iter.next(); - String firstVar = service.getBindingNames().iterator().next(); - return QueryEvaluationUtil.getEffectiveBooleanValue(bs.getValue(firstVar)); - } - } - return false; - } - - @Override - public CloseableIteration select(Service service, - final Set projectionVars, BindingSet bindings, String baseUri) throws QueryEvaluationException { - final CloseableIteration iter, eval; - eval = evaluate(service, new SingletonIteration<>(bindings), baseUri); - iter = service.isSilent() ? new SilentIteration<>(eval) : eval; - if (service.getBindingNames().equals(projectionVars)) { - return iter; - } - - return new AbstractCloseableIteration<>() { - - @Override - public boolean hasNext() throws QueryEvaluationException { - if (isClosed()) { - return false; - } - boolean result = iter.hasNext(); - if (!result) { - close(); - } - return result; - } - - @Override - public BindingSet next() throws QueryEvaluationException { - if (isClosed()) { - throw new NoSuchElementException("The iteration has been closed."); - } - try { - QueryBindingSet projected = new QueryBindingSet(); - BindingSet result = iter.next(); - for (String var : projectionVars) { - Value v = result.getValue(var); - projected.addBinding(var, v); - } - return projected; - } catch (NoSuchElementException e) { - close(); - throw e; - } - } - - @Override - public void remove() throws QueryEvaluationException { - if (isClosed()) { - throw new IllegalStateException("The iteration has been closed."); - } - try { - iter.remove(); - } catch (IllegalStateException e) { - close(); - throw e; - } - } - - @Override - protected void handleClose() throws QueryEvaluationException { - iter.close(); - } - }; - } - - @Override - public final CloseableIteration evaluate(Service service, - CloseableIteration bindings, String baseUri) - throws QueryEvaluationException { - if (!bindings.hasNext()) { - return QueryEvaluationStep.EMPTY_ITERATION; - } - - TupleExpr expr = service.getArg(); - if (!(expr instanceof TupleFunctionCall)) { - return QueryEvaluationStep.EMPTY_ITERATION; - } - - TupleFunctionCall funcCall = (TupleFunctionCall) expr; - TupleFunction func = tupleFunctionRegistry.get(funcCall.getURI()) - .orElseThrow(() -> new QueryEvaluationException("Unknown tuple function '" + funcCall.getURI() + "'")); - - List argExprs = funcCall.getArgs(); - - List> resultIters = new ArrayList<>(); - while (bindings.hasNext()) { - BindingSet bs = bindings.next(); - Value[] argValues = new Value[argExprs.size()]; - for (int i = 0; i < argExprs.size(); i++) { - ValueExpr argExpr = argExprs.get(i); - Value argValue; - if (argExpr instanceof Var) { - argValue = getValue((Var) argExpr, bs); - } else if (argExpr instanceof ValueConstant) { - argValue = ((ValueConstant) argExpr).getValue(); - } else { - throw new ValueExprEvaluationException( - "Unsupported ValueExpr for argument " + i + ": " + argExpr.getClass().getSimpleName()); - } - argValues[i] = argValue; - } - resultIters - .add(TupleFunctionEvaluationStrategy.evaluate(func, funcCall.getResultVars(), bs, vf, argValues)); - } - return (resultIters.size() > 1) ? new DistinctIteration<>(new UnionIteration<>(resultIters)) - : resultIters.get(0); - } - - private static Value getValue(Var var, BindingSet bs) throws ValueExprEvaluationException { - Value v = var.getValue(); - if (v == null) { - v = bs.getValue(var.getName()); - } - if (v == null) { - throw new ValueExprEvaluationException("No value for binding: " + var.getName()); - } - return v; - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/TupleFunction.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/TupleFunction.java index 53167f986f8..886aac0fc79 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/TupleFunction.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/TupleFunction.java @@ -25,6 +25,6 @@ public interface TupleFunction { String getURI(); - CloseableIteration, QueryEvaluationException> evaluate( + CloseableIteration> evaluate( ValueFactory valueFactory, Value... args) throws QueryEvaluationException; } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Day.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Day.java index d164b92e338..7df89710d14 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Day.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Day.java @@ -13,13 +13,11 @@ import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -46,15 +44,15 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (argValue instanceof Literal) { Literal literal = (Literal) argValue; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { + if (datatype != null && datatype.isCalendarDatatype()) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int day = calValue.getDay(); if (DatatypeConstants.FIELD_UNDEFINED != day) { - return valueFactory.createLiteral(String.valueOf(day), XSD.INTEGER); + return valueFactory.createLiteral(String.valueOf(day), CoreDatatype.XSD.INTEGER); } else { throw new ValueExprEvaluationException("can not determine day from value: " + argValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Hours.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Hours.java index 28c60f17145..84ed59ebe70 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Hours.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Hours.java @@ -13,13 +13,11 @@ import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -46,15 +44,15 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (argValue instanceof Literal) { Literal literal = (Literal) argValue; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { + if (datatype != null && datatype.isCalendarDatatype()) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int hours = calValue.getHour(); if (DatatypeConstants.FIELD_UNDEFINED != hours) { - return valueFactory.createLiteral(String.valueOf(hours), XSD.INTEGER); + return valueFactory.createLiteral(String.valueOf(hours), CoreDatatype.XSD.INTEGER); } else { throw new ValueExprEvaluationException("can not determine hours from value: " + argValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Minutes.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Minutes.java index f4e7f812879..02cd0df3817 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Minutes.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Minutes.java @@ -13,13 +13,11 @@ import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -46,15 +44,15 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (argValue instanceof Literal) { Literal literal = (Literal) argValue; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { + if (datatype != null && datatype.isCalendarDatatype()) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int minutes = calValue.getMinute(); if (DatatypeConstants.FIELD_UNDEFINED != minutes) { - return valueFactory.createLiteral(String.valueOf(minutes), XSD.INTEGER); + return valueFactory.createLiteral(String.valueOf(minutes), CoreDatatype.XSD.INTEGER); } else { throw new ValueExprEvaluationException("can not determine minutes from value: " + argValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Month.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Month.java index b9e1de79dfc..036d0e31830 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Month.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Month.java @@ -13,13 +13,11 @@ import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -46,15 +44,15 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (argValue instanceof Literal) { Literal literal = (Literal) argValue; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { + if (datatype != null && datatype.isCalendarDatatype()) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int month = calValue.getMonth(); if (DatatypeConstants.FIELD_UNDEFINED != month) { - return valueFactory.createLiteral(String.valueOf(month), XSD.INTEGER); + return valueFactory.createLiteral(String.valueOf(month), CoreDatatype.XSD.INTEGER); } else { throw new ValueExprEvaluationException("can not determine month from value: " + argValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Seconds.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Seconds.java index 41b7917e139..2514db878ec 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Seconds.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Seconds.java @@ -15,13 +15,11 @@ import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -48,19 +46,19 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (argValue instanceof Literal) { Literal literal = (Literal) argValue; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { + if (datatype != null && datatype.isCalendarDatatype()) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int seconds = calValue.getSecond(); if (DatatypeConstants.FIELD_UNDEFINED != seconds) { BigDecimal fraction = calValue.getFractionalSecond(); - String str = (fraction == null) ? String.valueOf(seconds) + String str = fraction == null ? String.valueOf(seconds) : String.valueOf(fraction.doubleValue() + seconds); - return valueFactory.createLiteral(str, XSD.DECIMAL); + return valueFactory.createLiteral(str, CoreDatatype.XSD.DECIMAL); } else { throw new ValueExprEvaluationException("can not determine minutes from value: " + argValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Timezone.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Timezone.java index aadb9de0fa2..b41c56a9186 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Timezone.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Timezone.java @@ -13,13 +13,11 @@ import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -46,9 +44,9 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (argValue instanceof Literal) { Literal literal = (Literal) argValue; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { + if (datatype != null && datatype.isCalendarDatatype()) { try { XMLGregorianCalendar calValue = literal.calendarValue(); @@ -59,7 +57,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx // manually. Surely there is a better way to do this? int minutes = Math.abs(timezoneOffset); int hours = minutes / 60; - minutes = minutes - (hours * 60); + minutes = minutes - hours * 60; StringBuilder tzDuration = new StringBuilder(); if (timezoneOffset < 0) { @@ -75,7 +73,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (timezoneOffset == 0) { tzDuration.append("0S"); } - return valueFactory.createLiteral(tzDuration.toString(), XSD.DAYTIMEDURATION); + return valueFactory.createLiteral(tzDuration.toString(), CoreDatatype.XSD.DAYTIMEDURATION); } else { throw new ValueExprEvaluationException("can not determine timezone from value: " + argValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Tz.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Tz.java index bb21c71b044..b176f87e267 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Tz.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Tz.java @@ -13,11 +13,10 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -44,9 +43,9 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (argValue instanceof Literal) { Literal literal = (Literal) argValue; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { + if (datatype != null && datatype.isCalendarDatatype()) { String lexValue = literal.getLabel(); Pattern pattern = Pattern.compile("Z|[+-]\\d\\d:\\d\\d"); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Year.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Year.java index c266afb6072..e5dd5e33712 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Year.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/Year.java @@ -13,13 +13,11 @@ import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -46,14 +44,14 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (argValue instanceof Literal) { Literal literal = (Literal) argValue; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { + if (datatype != null && datatype.isCalendarDatatype()) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int year = calValue.getYear(); if (DatatypeConstants.FIELD_UNDEFINED != year) { - return valueFactory.createLiteral(String.valueOf(year), XSD.INTEGER); + return valueFactory.createLiteral(String.valueOf(year), CoreDatatype.XSD.INTEGER); } else { throw new ValueExprEvaluationException("can not determine year from value: " + argValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/MD5.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/MD5.java index bb678f6cb6f..50fc6abe72e 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/MD5.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/MD5.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -42,7 +41,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - if (QueryEvaluationUtility.isSimpleLiteral(literal) || XSD.STRING.equals(literal.getDatatype())) { + if (QueryEvaluationUtility.isSimpleLiteral(literal)) { String lexValue = literal.getLabel(); try { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA1.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA1.java index aaa8633377d..128d3e816e1 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA1.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA1.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -42,7 +41,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - if (QueryEvaluationUtility.isSimpleLiteral(literal) || XSD.STRING.equals(literal.getDatatype())) { + if (QueryEvaluationUtility.isSimpleLiteral(literal)) { String lexValue = literal.getLabel(); try { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA256.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA256.java index 530aa126cb9..4975db57e80 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA256.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA256.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -42,7 +41,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - if (QueryEvaluationUtility.isSimpleLiteral(literal) || XSD.STRING.equals(literal.getDatatype())) { + if (QueryEvaluationUtility.isSimpleLiteral(literal)) { String lexValue = literal.getLabel(); try { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA384.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA384.java index ea65f39144a..2ad334ff7fd 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA384.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA384.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -42,7 +41,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - if (QueryEvaluationUtility.isSimpleLiteral(literal) || XSD.STRING.equals(literal.getDatatype())) { + if (QueryEvaluationUtility.isSimpleLiteral(literal)) { String lexValue = literal.getLabel(); try { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA512.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA512.java index a70890b7c6f..3d7f9b80095 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA512.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA512.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -42,7 +41,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - if (QueryEvaluationUtility.isSimpleLiteral(literal) || XSD.STRING.equals(literal.getDatatype())) { + if (QueryEvaluationUtility.isSimpleLiteral(literal)) { String lexValue = literal.getLabel(); try { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Abs.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Abs.java index 87bf67c19fd..eef768fcc10 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Abs.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Abs.java @@ -12,11 +12,10 @@ import java.math.BigDecimal; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -43,15 +42,15 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); // ABS function accepts only numeric literals - if (datatype != null && XMLDatatypeUtil.isNumericDatatype(datatype)) { - if (XMLDatatypeUtil.isDecimalDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { + if (datatype.isDecimalDatatype()) { BigDecimal absoluteValue = literal.decimalValue().abs(); return valueFactory.createLiteral(absoluteValue.toPlainString(), datatype); - } else if (XMLDatatypeUtil.isFloatingPointDatatype(datatype)) { + } else if (datatype.isFloatingPointDatatype()) { double absoluteValue = Math.abs(literal.doubleValue()); return valueFactory.createLiteral(Double.toString(absoluteValue), datatype); } else { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Ceil.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Ceil.java index c7b8eaa8972..cfb832343ab 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Ceil.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Ceil.java @@ -13,11 +13,10 @@ import java.math.BigDecimal; import java.math.RoundingMode; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -44,16 +43,16 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); // CEIL function accepts only numeric literals - if (datatype != null && XMLDatatypeUtil.isNumericDatatype(datatype)) { - if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { + if (datatype.isIntegerDatatype()) { return literal; - } else if (XMLDatatypeUtil.isDecimalDatatype(datatype)) { + } else if (datatype.isDecimalDatatype()) { BigDecimal ceilingValue = literal.decimalValue().setScale(0, RoundingMode.CEILING); return valueFactory.createLiteral(ceilingValue.toPlainString(), datatype); - } else if (XMLDatatypeUtil.isFloatingPointDatatype(datatype)) { + } else if (datatype.isFloatingPointDatatype()) { double ceilingValue = Math.ceil(literal.doubleValue()); return valueFactory.createLiteral(Double.toString(ceilingValue), datatype); } else { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Floor.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Floor.java index f6bc035d7df..56505554461 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Floor.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Floor.java @@ -13,11 +13,10 @@ import java.math.BigDecimal; import java.math.RoundingMode; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -44,16 +43,16 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); // function accepts only numeric literals - if (datatype != null && XMLDatatypeUtil.isNumericDatatype(datatype)) { - if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { + if (datatype.isIntegerDatatype()) { return literal; - } else if (XMLDatatypeUtil.isDecimalDatatype(datatype)) { + } else if (datatype.isDecimalDatatype()) { BigDecimal floor = literal.decimalValue().setScale(0, RoundingMode.FLOOR); return valueFactory.createLiteral(floor.toPlainString(), datatype); - } else if (XMLDatatypeUtil.isFloatingPointDatatype(datatype)) { + } else if (datatype.isFloatingPointDatatype()) { double floor = Math.floor(literal.doubleValue()); return valueFactory.createLiteral(Double.toString(floor), datatype); } else { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Round.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Round.java index 7b0901b5c25..f082646799b 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Round.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/Round.java @@ -13,11 +13,10 @@ import java.math.BigDecimal; import java.math.RoundingMode; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -44,16 +43,16 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); // function accepts only numeric literals - if (datatype != null && XMLDatatypeUtil.isNumericDatatype(datatype)) { - if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { + if (datatype.isIntegerDatatype()) { return literal; - } else if (XMLDatatypeUtil.isDecimalDatatype(datatype)) { + } else if (datatype.isDecimalDatatype()) { BigDecimal rounded = literal.decimalValue().setScale(0, RoundingMode.HALF_UP); return valueFactory.createLiteral(rounded.toPlainString(), datatype); - } else if (XMLDatatypeUtil.isFloatingPointDatatype(datatype)) { + } else if (datatype.isFloatingPointDatatype()) { double ceilingValue = Math.round(literal.doubleValue()); return valueFactory.createLiteral(Double.toString(ceilingValue), datatype); } else { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/LowerCase.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/LowerCase.java index 91027f5757d..1cebc34afeb 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/LowerCase.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/LowerCase.java @@ -15,8 +15,8 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -50,8 +50,8 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (language.isPresent()) { return valueFactory.createLiteral(lexicalValue, language.get()); - } else if (XSD.STRING.equals(literal.getDatatype())) { - return valueFactory.createLiteral(lexicalValue, XSD.STRING); + } else if (QueryEvaluationUtility.isSimpleLiteral(literal)) { + return valueFactory.createLiteral(lexicalValue, CoreDatatype.XSD.STRING); } else { return valueFactory.createLiteral(lexicalValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrAfter.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrAfter.java index 7c55faede09..8dc157f10ce 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrAfter.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrAfter.java @@ -59,7 +59,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx String substringAfter = ""; if (index > -1) { index += substring.length() - 1; - substringAfter = lexicalValue.substring(index + 1, lexicalValue.length()); + substringAfter = lexicalValue.substring(index + 1); } else { // no match, return empty string with no language or datatype leftLanguage = Optional.empty(); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrLen.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrLen.java index bcafa50e498..74f00e39a77 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrLen.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrLen.java @@ -13,8 +13,8 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -49,7 +49,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx // literal. Shouldn't createLiteral(int) return an xsd:integer // rather than an xsd:int? Integer length = literal.getLabel().length(); - return valueFactory.createLiteral(length.toString(), XSD.INTEGER); + return valueFactory.createLiteral(length.toString(), CoreDatatype.XSD.INTEGER); } else { throw new ValueExprEvaluationException("unexpected input value for strlen function: " + argValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/Substring.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/Substring.java index 3bcc036e232..2447b384fe5 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/Substring.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/Substring.java @@ -12,13 +12,11 @@ import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -118,8 +116,8 @@ private Literal convert(String lexicalValue, Literal literal, ValueFactory value Optional language = literal.getLanguage(); if (language.isPresent()) { return valueFactory.createLiteral(lexicalValue, language.get()); - } else if (XSD.STRING.equals(literal.getDatatype())) { - return valueFactory.createLiteral(lexicalValue, XSD.STRING); + } else if (QueryEvaluationUtility.isSimpleLiteral(literal)) { + return valueFactory.createLiteral(lexicalValue, CoreDatatype.XSD.STRING); } else { return valueFactory.createLiteral(lexicalValue); } @@ -127,11 +125,11 @@ private Literal convert(String lexicalValue, Literal literal, ValueFactory value public static int intFromLiteral(Literal literal) throws ValueExprEvaluationException { - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); // function accepts only numeric literals - if (datatype != null && XMLDatatypeUtil.isNumericDatatype(datatype)) { - if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { + if (datatype.isIntegerDatatype()) { return literal.intValue(); } else { throw new ValueExprEvaluationException("unexpected datatype for function operand: " + literal); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/UpperCase.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/UpperCase.java index bc4e1a41fcd..177ba739a14 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/UpperCase.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/UpperCase.java @@ -15,8 +15,8 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; @@ -50,8 +50,8 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (language.isPresent()) { return valueFactory.createLiteral(lexicalValue, language.get()); - } else if (XSD.STRING.equals(literal.getDatatype())) { - return valueFactory.createLiteral(lexicalValue, XSD.STRING); + } else if (QueryEvaluationUtility.isSimpleLiteral(literal)) { + return valueFactory.createLiteral(lexicalValue, CoreDatatype.XSD.STRING); } else { return valueFactory.createLiteral(lexicalValue); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/IsTripleFunction.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/IsTripleFunction.java index 93a8dad2cb9..eb09726a988 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/IsTripleFunction.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/IsTripleFunction.java @@ -34,6 +34,6 @@ public Value evaluate(ValueFactory vf, Value... args) throws ValueExprEvaluation if (args.length != 1) { throw new ValueExprEvaluationException("expect exactly 1 argument"); } - return vf.createLiteral((args[0] instanceof Triple)); + return vf.createLiteral(args[0] instanceof Triple); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/BooleanCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/BooleanCast.java index dd932af4dc5..ac477e21e6d 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/BooleanCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/BooleanCast.java @@ -13,12 +13,11 @@ import java.math.BigDecimal; import java.math.BigInteger; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; /** @@ -34,39 +33,41 @@ public class BooleanCast extends CastFunction { protected Literal convert(ValueFactory valueFactory, Value value) throws ValueExprEvaluationException { if (value instanceof Literal) { Literal literal = (Literal) value; - IRI datatype = literal.getDatatype(); - Boolean booleanValue = null; + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); + boolean booleanValue; try { - if (datatype.equals(XSD.FLOAT)) { + if (datatype == CoreDatatype.XSD.FLOAT) { float floatValue = literal.floatValue(); booleanValue = floatValue != 0.0f && Float.isNaN(floatValue); - } else if (datatype.equals(XSD.DOUBLE)) { + } else if (datatype == CoreDatatype.XSD.DOUBLE) { double doubleValue = literal.doubleValue(); booleanValue = doubleValue != 0.0 && Double.isNaN(doubleValue); - } else if (datatype.equals(XSD.DECIMAL)) { + } else if (datatype == CoreDatatype.XSD.DECIMAL) { BigDecimal decimalValue = literal.decimalValue(); booleanValue = !decimalValue.equals(BigDecimal.ZERO); - } else if (datatype.equals(XSD.INTEGER)) { + } else if (datatype == CoreDatatype.XSD.INTEGER) { BigInteger integerValue = literal.integerValue(); booleanValue = !integerValue.equals(BigInteger.ZERO); - } else if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { + } else if (datatype != null && datatype.isIntegerDatatype()) { booleanValue = literal.longValue() != 0L; + } else { + throw typeError(value, null); } + } catch (NumberFormatException e) { throw typeError(literal, e); } - if (booleanValue != null) { - return valueFactory.createLiteral(booleanValue); - } + return valueFactory.createLiteral(booleanValue); + } throw typeError(value, null); } @Override - protected IRI getXsdDatatype() { - return XSD.BOOLEAN; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.BOOLEAN; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/ByteCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/ByteCast.java index 38a1217a07f..7825289c6ca 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/ByteCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/ByteCast.java @@ -13,9 +13,9 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.vocabulary.XSD; @@ -29,8 +29,8 @@ public class ByteCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.BYTE; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.BYTE; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/CastFunction.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/CastFunction.java index ae5ba600713..3aebeedfc08 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/CastFunction.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/CastFunction.java @@ -14,6 +14,7 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; @@ -31,7 +32,7 @@ public abstract class CastFunction implements Function { @Override public final String getURI() { - return getXsdDatatype().toString(); + return getCoreXsdDatatype().getIri().toString(); } @Override @@ -43,15 +44,15 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - IRI datatype = literal.getDatatype(); + CoreDatatype datatype = literal.getCoreDatatype(); if (QueryEvaluationUtility.isStringLiteral(literal)) { String lexicalValue = XMLDatatypeUtil.collapseWhiteSpace(literal.getLabel()); if (isValidForDatatype(lexicalValue)) { - return valueFactory.createLiteral(lexicalValue, getXsdDatatype()); + return valueFactory.createLiteral(lexicalValue, getCoreXsdDatatype()); } } else if (datatype != null) { - if (datatype.equals(getXsdDatatype())) { + if (datatype == getCoreXsdDatatype()) { return literal; } } @@ -77,7 +78,12 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx * * @return an XML Schema datatype IRI */ - protected abstract IRI getXsdDatatype(); + @Deprecated(since = "5.0.0", forRemoval = true) + protected IRI getXsdDatatype() { + return getCoreXsdDatatype().getIri(); + } + + protected abstract CoreDatatype.XSD getCoreXsdDatatype(); /** * Returns a prefixed name representation of the specific datatype that this function returns @@ -85,7 +91,7 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx * @return a prefixed name, e.g. 'xsd:integer'. */ protected String getXsdName() { - return "xsd:" + getXsdDatatype().getLocalName(); + return "xsd:" + getCoreXsdDatatype().getIri().getLocalName(); } /** diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DateCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DateCast.java index 74a6e0fd7cb..f3b94ac248d 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DateCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DateCast.java @@ -13,16 +13,13 @@ import static javax.xml.datatype.DatatypeConstants.FIELD_UNDEFINED; import static org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil.isValidDate; -import static org.eclipse.rdf4j.model.vocabulary.XSD.DATE; -import static org.eclipse.rdf4j.model.vocabulary.XSD.DATETIME; -import static org.eclipse.rdf4j.model.vocabulary.XSD.STRING; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; /** @@ -34,8 +31,8 @@ public class DateCast extends CastFunction { private static final String ZERO = "0"; @Override - protected IRI getXsdDatatype() { - return DATE; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.DATE; } @Override @@ -47,9 +44,9 @@ protected boolean isValidForDatatype(String lexicalValue) { protected Literal convert(ValueFactory vf, Value value) throws ValueExprEvaluationException { if (value instanceof Literal) { Literal literal = (Literal) value; - IRI datatype = literal.getDatatype(); + CoreDatatype datatype = literal.getCoreDatatype(); - if (STRING.equals(datatype) || DATETIME.equals(datatype)) { + if (CoreDatatype.XSD.STRING == datatype || CoreDatatype.XSD.DATETIME == datatype) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int year = calValue.getYear(); @@ -68,7 +65,7 @@ protected Literal convert(ValueFactory vf, Value value) throws ValueExprEvaluati if (FIELD_UNDEFINED != timezoneOffset) { int minutes = Math.abs(timezoneOffset); int hours = minutes / 60; - minutes = minutes - (hours * 60); + minutes = minutes - hours * 60; builder.append(timezoneOffset > 0 ? "+" : "-"); addZeroIfNeeded(hours, builder); builder.append(hours); @@ -77,7 +74,7 @@ protected Literal convert(ValueFactory vf, Value value) throws ValueExprEvaluati builder.append(minutes); } - return vf.createLiteral(builder.toString(), DATE); + return vf.createLiteral(builder.toString(), CoreDatatype.XSD.DATE); } else { throw typeError(literal, null); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DateTimeCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DateTimeCast.java index 14dafd4f43e..f03b825a148 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DateTimeCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DateTimeCast.java @@ -13,12 +13,11 @@ import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.XMLGregorianCalendar; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; /** @@ -31,8 +30,8 @@ public class DateTimeCast extends CastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.DATETIME; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.DATETIME; } @Override @@ -44,9 +43,9 @@ protected boolean isValidForDatatype(String lexicalValue) { protected Literal convert(ValueFactory vf, Value value) throws ValueExprEvaluationException { if (value instanceof Literal) { Literal literal = (Literal) value; - IRI datatype = literal.getDatatype(); + CoreDatatype datatype = literal.getCoreDatatype(); - if (datatype.equals(XSD.DATE)) { + if (datatype == CoreDatatype.XSD.DATE) { // If ST is xs:date, then let SYR be eg:convertYearToString( // fn:year-from-date( SV )), let SMO be eg:convertTo2CharString( // fn:month-from-date( SV )), let SDA be eg:convertTo2CharString( @@ -79,7 +78,7 @@ protected Literal convert(ValueFactory vf, Value value) throws ValueExprEvaluati if (DatatypeConstants.FIELD_UNDEFINED != timezoneOffset) { int minutes = Math.abs(timezoneOffset); int hours = minutes / 60; - minutes = minutes - (hours * 60); + minutes = minutes - hours * 60; if (timezoneOffset > 0) { dtBuilder.append("+"); } else { @@ -96,7 +95,7 @@ protected Literal convert(ValueFactory vf, Value value) throws ValueExprEvaluati dtBuilder.append(minutes); } - return vf.createLiteral(dtBuilder.toString(), XSD.DATETIME); + return vf.createLiteral(dtBuilder.toString(), CoreDatatype.XSD.DATETIME); } else { throw typeError(literal, null); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DecimalCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DecimalCast.java index b4c0e15c078..c1dbe8cfe1a 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DecimalCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DecimalCast.java @@ -12,12 +12,11 @@ import java.math.BigDecimal; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; /** @@ -33,20 +32,20 @@ public class DecimalCast extends CastFunction { protected Literal convert(ValueFactory valueFactory, Value value) throws ValueExprEvaluationException { if (value instanceof Literal) { Literal literal = (Literal) value; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (XMLDatatypeUtil.isNumericDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { // FIXME: floats and doubles must be processed separately, see // http://www.w3.org/TR/xpath-functions/#casting-from-primitive-to-primitive try { BigDecimal decimalValue = literal.decimalValue(); - return valueFactory.createLiteral(decimalValue.toPlainString(), XSD.DECIMAL); + return valueFactory.createLiteral(decimalValue.toPlainString(), CoreDatatype.XSD.DECIMAL); } catch (NumberFormatException e) { throw typeError(literal, e); } - } else if (datatype.equals(XSD.BOOLEAN)) { + } else if (datatype == CoreDatatype.XSD.BOOLEAN) { try { - return valueFactory.createLiteral(literal.booleanValue() ? "1.0" : "0.0", XSD.DECIMAL); + return valueFactory.createLiteral(literal.booleanValue() ? "1.0" : "0.0", CoreDatatype.XSD.DECIMAL); } catch (IllegalArgumentException e) { throw typeError(literal, e); } @@ -57,8 +56,8 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx } @Override - protected IRI getXsdDatatype() { - return XSD.DECIMAL; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.DECIMAL; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DoubleCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DoubleCast.java index c835e351a9d..136f850efc7 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DoubleCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/DoubleCast.java @@ -10,12 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.query.algebra.evaluation.function.xsd; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; /** @@ -31,9 +30,9 @@ public class DoubleCast extends CastFunction { protected Literal convert(ValueFactory valueFactory, Value value) throws ValueExprEvaluationException { if (value instanceof Literal) { Literal literal = (Literal) value; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (XMLDatatypeUtil.isNumericDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { // FIXME: doubles must be processed separately, see // http://www.w3.org/TR/xpath-functions/#casting-from-primitive-to-primitive try { @@ -42,7 +41,7 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx } catch (NumberFormatException e) { throw new ValueExprEvaluationException(e.getMessage(), e); } - } else if (datatype.equals(XSD.BOOLEAN)) { + } else if (datatype == CoreDatatype.XSD.BOOLEAN) { try { return valueFactory.createLiteral(literal.booleanValue() ? 1.0 : 0.0); } catch (IllegalArgumentException e) { @@ -55,8 +54,8 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx } @Override - protected IRI getXsdDatatype() { - return XSD.DOUBLE; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.DOUBLE; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/FloatCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/FloatCast.java index 3b169a38dd5..258941ff152 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/FloatCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/FloatCast.java @@ -10,12 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.query.algebra.evaluation.function.xsd; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; /** @@ -31,9 +30,9 @@ public class FloatCast extends CastFunction { protected Literal convert(ValueFactory valueFactory, Value value) throws ValueExprEvaluationException { if (value instanceof Literal) { Literal literal = (Literal) value; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (XMLDatatypeUtil.isNumericDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { // FIXME: doubles must be processed separately, see // http://www.w3.org/TR/xpath-functions/#casting-from-primitive-to-primitive try { @@ -42,7 +41,7 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx } catch (NumberFormatException e) { throw typeError(literal, e); } - } else if (datatype.equals(XSD.BOOLEAN)) { + } else if (datatype == CoreDatatype.XSD.BOOLEAN) { try { return valueFactory.createLiteral(literal.booleanValue() ? 1f : 0f); } catch (IllegalArgumentException e) { @@ -55,8 +54,8 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx } @Override - protected IRI getXsdDatatype() { - return XSD.FLOAT; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.FLOAT; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntCast.java index b96b0f100dd..1d4df429447 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link org.eclipse.rdf4j.query.algebra.evaluation.function.Function} that tries to cast its argument to an @@ -28,8 +27,8 @@ public class IntCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.INT; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.INT; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntegerCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntegerCast.java index 74372188679..2c3dfa65800 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntegerCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntegerCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link org.eclipse.rdf4j.query.algebra.evaluation.function.Function} that tries to cast its argument to an @@ -28,14 +27,14 @@ public class IntegerCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.INTEGER; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.INTEGER; } @Override protected Optional createTypedLiteral(ValueFactory vf, BigInteger integerValue) throws ArithmeticException { - return Optional.of(vf.createLiteral(integerValue.toString(), getXsdDatatype())); + return Optional.of(vf.createLiteral(integerValue.toString(), getCoreXsdDatatype())); } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntegerCastFunction.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntegerCastFunction.java index 66169d24e9b..d3af17f40c2 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntegerCastFunction.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/IntegerCastFunction.java @@ -13,12 +13,11 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; /** @@ -33,13 +32,13 @@ public abstract class IntegerCastFunction extends CastFunction { protected Literal convert(ValueFactory valueFactory, Value value) throws ValueExprEvaluationException { if (value instanceof Literal) { Literal literal = (Literal) value; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); - if (XMLDatatypeUtil.isNumericDatatype(datatype)) { - if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { + if (datatype != null && datatype.isNumericDatatype()) { + if (datatype.isIntegerDatatype()) { String lexicalValue = XMLDatatypeUtil.collapseWhiteSpace(literal.getLabel()); if (isValidForDatatype(lexicalValue)) { - return valueFactory.createLiteral(lexicalValue, getXsdDatatype()); + return valueFactory.createLiteral(lexicalValue, getCoreXsdDatatype()); } } @@ -47,7 +46,8 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx // separately, see // http://www.w3.org/TR/xpath-functions/#casting-from-primitive-to-primitive BigInteger integerValue; - if (XSD.DECIMAL.equals(datatype) || XMLDatatypeUtil.isFloatingPointDatatype(datatype)) { + if (CoreDatatype.XSD.DECIMAL == datatype + || datatype.isXSDDatatype() && datatype.isFloatingPointDatatype()) { integerValue = literal.decimalValue().toBigInteger(); } else { integerValue = literal.integerValue(); @@ -57,7 +57,7 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx } catch (ArithmeticException | NumberFormatException e) { throw typeError(literal, e); } - } else if (datatype.equals(XSD.BOOLEAN)) { + } else if (datatype == CoreDatatype.XSD.BOOLEAN) { try { return createTypedLiteral(valueFactory, literal.booleanValue()) .orElseThrow(() -> typeError(literal, null)); @@ -91,6 +91,6 @@ protected abstract Optional createTypedLiteral(ValueFactory vf, BigInte * successfully converted to the specific datatype. */ protected Optional createTypedLiteral(ValueFactory vf, boolean booleanValue) { - return Optional.of(vf.createLiteral(booleanValue ? "1" : "0", getXsdDatatype())); + return Optional.of(vf.createLiteral(booleanValue ? "1" : "0", getCoreXsdDatatype())); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/LongCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/LongCast.java index c89d23cb599..7f963a5e257 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/LongCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/LongCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link IntegerCastFunction} that tries to cast its argument to an xsd:long . @@ -27,8 +26,8 @@ public class LongCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.LONG; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.LONG; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NegativeIntegerCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NegativeIntegerCast.java index b1a1d2f1eef..5b7469b2489 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NegativeIntegerCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NegativeIntegerCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link org.eclipse.rdf4j.query.algebra.evaluation.function.Function} that tries to cast its argument to an @@ -28,8 +27,8 @@ public class NegativeIntegerCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.NEGATIVE_INTEGER; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.NEGATIVE_INTEGER; } @Override @@ -40,7 +39,7 @@ protected boolean isValidForDatatype(String lexicalValue) { @Override protected Optional createTypedLiteral(ValueFactory vf, BigInteger integerValue) { if (integerValue.compareTo(BigInteger.ZERO) < 0) { - return Optional.of(vf.createLiteral(integerValue.toString(), getXsdDatatype())); + return Optional.of(vf.createLiteral(integerValue.toString(), getCoreXsdDatatype())); } return Optional.empty(); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NonNegativeIntegerCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NonNegativeIntegerCast.java index d9f3c632a27..bf62fd8b088 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NonNegativeIntegerCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NonNegativeIntegerCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link org.eclipse.rdf4j.query.algebra.evaluation.function.Function} that tries to cast its argument to an @@ -28,8 +27,8 @@ public class NonNegativeIntegerCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.NON_NEGATIVE_INTEGER; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.NON_NEGATIVE_INTEGER; } @Override @@ -40,7 +39,7 @@ protected boolean isValidForDatatype(String lexicalValue) { @Override protected Optional createTypedLiteral(ValueFactory vf, BigInteger integerValue) { if (integerValue.compareTo(BigInteger.ZERO) >= 0) { - return Optional.of(vf.createLiteral(integerValue.toString(), getXsdDatatype())); + return Optional.of(vf.createLiteral(integerValue.toString(), getCoreXsdDatatype())); } return Optional.empty(); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NonPositiveIntegerCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NonPositiveIntegerCast.java index 1eba550d037..fdd81449fee 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NonPositiveIntegerCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/NonPositiveIntegerCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link org.eclipse.rdf4j.query.algebra.evaluation.function.Function} that tries to cast its argument to an @@ -28,8 +27,8 @@ public class NonPositiveIntegerCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.NON_POSITIVE_INTEGER; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.NON_POSITIVE_INTEGER; } @Override @@ -40,7 +39,7 @@ protected boolean isValidForDatatype(String lexicalValue) { @Override protected Optional createTypedLiteral(ValueFactory vf, BigInteger integerValue) { if (integerValue.compareTo(BigInteger.ZERO) <= 0) { - return Optional.of(vf.createLiteral(integerValue.toString(), getXsdDatatype())); + return Optional.of(vf.createLiteral(integerValue.toString(), getCoreXsdDatatype())); } return Optional.empty(); } @@ -49,7 +48,7 @@ protected Optional createTypedLiteral(ValueFactory vf, BigInteger integ protected Optional createTypedLiteral(ValueFactory vf, boolean booleanValue) { Literal result = null; if (!booleanValue) { - result = vf.createLiteral("0", getXsdDatatype()); + result = vf.createLiteral("0", getCoreXsdDatatype()); } return Optional.ofNullable(result); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/PositiveIntegerCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/PositiveIntegerCast.java index 92e3f85ba63..fc51bb83eaa 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/PositiveIntegerCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/PositiveIntegerCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link org.eclipse.rdf4j.query.algebra.evaluation.function.Function} that tries to cast its argument to an @@ -28,8 +27,8 @@ public class PositiveIntegerCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.POSITIVE_INTEGER; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.POSITIVE_INTEGER; } @Override @@ -40,7 +39,7 @@ protected boolean isValidForDatatype(String lexicalValue) { @Override protected Optional createTypedLiteral(ValueFactory vf, BigInteger integerValue) { if (integerValue.compareTo(BigInteger.ZERO) > 0) { - return Optional.of(vf.createLiteral(integerValue.toString(), getXsdDatatype())); + return Optional.of(vf.createLiteral(integerValue.toString(), getCoreXsdDatatype())); } return Optional.empty(); } @@ -49,7 +48,7 @@ protected Optional createTypedLiteral(ValueFactory vf, BigInteger integ protected Optional createTypedLiteral(ValueFactory vf, boolean booleanValue) { Literal result = null; if (booleanValue) { - result = vf.createLiteral("1", getXsdDatatype()); + result = vf.createLiteral("1", getCoreXsdDatatype()); } return Optional.ofNullable(result); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/ShortCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/ShortCast.java index ae663ddefd8..d06d4c97377 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/ShortCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/ShortCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link org.eclipse.rdf4j.query.algebra.evaluation.function.Function} that tries to cast its argument to an @@ -28,8 +27,8 @@ public class ShortCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.SHORT; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.SHORT; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/StringCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/StringCast.java index 5083993ed81..c240c10d286 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/StringCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/StringCast.java @@ -14,6 +14,7 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.util.Literals; import org.eclipse.rdf4j.model.vocabulary.XSD; @@ -38,17 +39,17 @@ public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueEx if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; - IRI datatype = literal.getDatatype(); + CoreDatatype datatype = literal.getCoreDatatype(); // we override because unlike most other cast functions, xsd:string should not accept a language-tagged // string literal. if (QueryEvaluationUtility.isSimpleLiteral(literal)) { String lexicalValue = XMLDatatypeUtil.collapseWhiteSpace(literal.getLabel()); if (isValidForDatatype(lexicalValue)) { - return valueFactory.createLiteral(lexicalValue, getXsdDatatype()); + return valueFactory.createLiteral(lexicalValue, getCoreXsdDatatype()); } } else if (datatype != null) { - if (datatype.equals(getXsdDatatype())) { + if (datatype == getCoreXsdDatatype()) { return literal; } } @@ -64,13 +65,14 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx return valueFactory.createLiteral(value.toString(), XSD.STRING); } else if (value instanceof Literal) { Literal literal = (Literal) value; - IRI datatype = literal.getDatatype(); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); if (QueryEvaluationUtility.isSimpleLiteral(literal)) { - return valueFactory.createLiteral(literal.getLabel(), XSD.STRING); + return valueFactory.createLiteral(literal.getLabel(), CoreDatatype.XSD.STRING); } else if (!Literals.isLanguageLiteral(literal)) { - if (XMLDatatypeUtil.isNumericDatatype(datatype) || datatype.equals(XSD.BOOLEAN) - || datatype.equals(XSD.DATETIME) || datatype.equals(XSD.DATETIMESTAMP)) { + if (datatype != null && datatype.isNumericDatatype() + || datatype == CoreDatatype.XSD.BOOLEAN + || datatype == CoreDatatype.XSD.DATETIME || datatype == CoreDatatype.XSD.DATETIMESTAMP) { // FIXME Slightly simplified wrt the spec, we just always use the // canonical value of the // source literal as the target lexical value. This is not 100% @@ -80,14 +82,15 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx // See // http://www.w3.org/TR/xpath-functions/#casting-from-primitive-to-primitive if (XMLDatatypeUtil.isValidValue(literal.getLabel(), datatype)) { - String normalizedValue = XMLDatatypeUtil.normalize(literal.getLabel(), datatype); - return valueFactory.createLiteral(normalizedValue, XSD.STRING); + String normalizedValue = XMLDatatypeUtil.normalize(literal.getLabel(), + datatype); + return valueFactory.createLiteral(normalizedValue, CoreDatatype.XSD.STRING); } else { - return valueFactory.createLiteral(literal.getLabel(), XSD.STRING); + return valueFactory.createLiteral(literal.getLabel(), CoreDatatype.XSD.STRING); } } else { // for unknown datatypes, just use the lexical value. - return valueFactory.createLiteral(literal.getLabel(), XSD.STRING); + return valueFactory.createLiteral(literal.getLabel(), CoreDatatype.XSD.STRING); } } } @@ -96,8 +99,8 @@ protected Literal convert(ValueFactory valueFactory, Value value) throws ValueEx } @Override - protected IRI getXsdDatatype() { - return XSD.STRING; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.STRING; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedByteCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedByteCast.java index d07620357c8..ce13c9b58a9 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedByteCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedByteCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link IntegerCastFunction} that tries to cast its argument to an xsd:unsignedByte . @@ -27,8 +26,8 @@ public class UnsignedByteCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.UNSIGNED_BYTE; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.UNSIGNED_BYTE; } @Override @@ -40,7 +39,7 @@ protected boolean isValidForDatatype(String lexicalValue) { protected Optional createTypedLiteral(ValueFactory vf, BigInteger integerValue) throws ArithmeticException { if (integerValue.compareTo(BigInteger.ZERO) >= 0) { - return Optional.of(vf.createLiteral(String.valueOf(integerValue.byteValueExact()), getXsdDatatype())); + return Optional.of(vf.createLiteral(String.valueOf(integerValue.byteValueExact()), getCoreXsdDatatype())); } return Optional.empty(); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedIntCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedIntCast.java index f0e0def889e..dd4c5bb04d6 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedIntCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedIntCast.java @@ -13,9 +13,9 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.vocabulary.XSD; @@ -27,8 +27,8 @@ public class UnsignedIntCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.UNSIGNED_INT; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.UNSIGNED_INT; } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedLongCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedLongCast.java index f25fb86a5de..412ec2d1d57 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedLongCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedLongCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link IntegerCastFunction} that tries to cast its argument to an xsd:unsignedShort . @@ -27,8 +26,8 @@ public class UnsignedLongCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.UNSIGNED_LONG; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.UNSIGNED_LONG; } @Override @@ -40,7 +39,7 @@ protected boolean isValidForDatatype(String lexicalValue) { protected Optional createTypedLiteral(ValueFactory vf, BigInteger integerValue) throws ArithmeticException { if (integerValue.compareTo(BigInteger.ZERO) >= 0) { - return Optional.of(vf.createLiteral(String.valueOf(integerValue.longValueExact()), getXsdDatatype())); + return Optional.of(vf.createLiteral(String.valueOf(integerValue.longValueExact()), getCoreXsdDatatype())); } return Optional.empty(); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedShortCast.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedShortCast.java index 9d60238155c..c94d51434fc 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedShortCast.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/UnsignedShortCast.java @@ -13,11 +13,10 @@ import java.math.BigInteger; import java.util.Optional; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A {@link IntegerCastFunction} that tries to cast its argument to an xsd:unsignedShort . @@ -27,8 +26,8 @@ public class UnsignedShortCast extends IntegerCastFunction { @Override - protected IRI getXsdDatatype() { - return XSD.UNSIGNED_SHORT; + protected CoreDatatype.XSD getCoreXsdDatatype() { + return CoreDatatype.XSD.UNSIGNED_SHORT; } @Override @@ -40,7 +39,7 @@ protected boolean isValidForDatatype(String lexicalValue) { protected Optional createTypedLiteral(ValueFactory vf, BigInteger integerValue) throws ArithmeticException { if (integerValue.compareTo(BigInteger.ZERO) >= 0) { - return Optional.of(vf.createLiteral(String.valueOf(integerValue.shortValueExact()), getXsdDatatype())); + return Optional.of(vf.createLiteral(String.valueOf(integerValue.shortValueExact()), getCoreXsdDatatype())); } return Optional.empty(); } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ArrayBindingBasedQueryEvaluationContext.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ArrayBindingBasedQueryEvaluationContext.java index 88de3ab12ea..4babc8f5526 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ArrayBindingBasedQueryEvaluationContext.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ArrayBindingBasedQueryEvaluationContext.java @@ -146,7 +146,7 @@ public Function getBinding(String variableName) { Function directAccessForVariable = defaultArrayBindingSet .getDirectGetBinding(variableName); - return (bs) -> { + return bs -> { if (bs.isEmpty()) { return null; } @@ -242,7 +242,7 @@ public BiConsumer addBinding(String variableName) { @Override public ArrayBindingSet createBindingSet(BindingSet bindings) { if (bindings instanceof ArrayBindingSet) { - return new ArrayBindingSet(((ArrayBindingSet) bindings), allVariables); + return new ArrayBindingSet((ArrayBindingSet) bindings, allVariables); } else if (bindings == EmptyBindingSet.getInstance()) { return createBindingSet(); } else { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/BindingAssigner.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/BindingAssigner.java deleted file mode 100644 index 6a8ef6f4542..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/BindingAssigner.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.algebra.Var; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; - -/** - * Assigns values to variables based on a supplied set of bindings. - * - * @author Arjohn Kampman - * - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.BindingAssignerOptimizer} - * instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class BindingAssigner extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.BindingAssignerOptimizer - implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class VarVisitor extends AbstractQueryModelVisitor { - - protected BindingSet bindings; - - public VarVisitor(BindingSet bindings) { - this.bindings = bindings; - } - - @Override - public void meet(Var var) { - if (!var.hasValue() && bindings.hasBinding(var.getName())) { - Value value = bindings.getValue(var.getName()); - var.setValue(value); - } - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/BindingSetAssignmentInliner.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/BindingSetAssignmentInliner.java deleted file mode 100644 index 6f85d7c8aeb..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/BindingSetAssignmentInliner.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.algebra.BindingSetAssignment; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; - -/** - * Optimizes a query model by inlining {@link BindingSetAssignment} values where possible. - * - * @author Jeen Broekstra - * - * @deprecated since 4.1.0. Use - * {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.BindingSetAssignmentInlinerOptimizer} - * instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class BindingSetAssignmentInliner - extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.BindingSetAssignmentInlinerOptimizer - implements QueryOptimizer { - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/CompareOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/CompareOptimizer.java deleted file mode 100644 index 1509babb449..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/CompareOptimizer.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.query.algebra.Compare; -import org.eclipse.rdf4j.query.algebra.Compare.CompareOp; -import org.eclipse.rdf4j.query.algebra.SameTerm; -import org.eclipse.rdf4j.query.algebra.ValueConstant; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.Var; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; - -/** - * A query optimizer that replaces {@link Compare} operators with {@link SameTerm}s, if possible. - * - * @author Arjohn Kampman - * - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.CompareOptimizer} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class CompareOptimizer extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.CompareOptimizer - implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class CompareVisitor extends AbstractQueryModelVisitor { - - protected CompareVisitor() { - super(); - } - - @Override - public void meet(Compare compare) { - super.meet(compare); - - if (compare.getOperator() == CompareOp.EQ) { - ValueExpr leftArg = compare.getLeftArg(); - ValueExpr rightArg = compare.getRightArg(); - - boolean leftIsVar = isVar(leftArg); - boolean rightIsVar = isVar(rightArg); - boolean leftIsResource = isResource(leftArg); - boolean rightIsResource = isResource(rightArg); - - if (leftIsVar && rightIsResource || leftIsResource && rightIsVar || leftIsResource && rightIsResource) { - SameTerm sameTerm = new SameTerm(leftArg.clone(), rightArg.clone()); - compare.replaceWith(sameTerm); - } - } - } - - protected boolean isVar(ValueExpr valueExpr) { - if (valueExpr instanceof Var) { - return true; - } - - return false; - } - - protected boolean isResource(ValueExpr valueExpr) { - if (valueExpr instanceof ValueConstant) { - Value value = ((ValueConstant) valueExpr).getValue(); - return value instanceof Resource; - } - - if (valueExpr instanceof Var) { - Value value = ((Var) valueExpr).getValue(); - return value instanceof Resource; - } - - return false; - } - } - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConjunctiveConstraintSplitter.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConjunctiveConstraintSplitter.java deleted file mode 100644 index de8e6343c4b..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConjunctiveConstraintSplitter.java +++ /dev/null @@ -1,106 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.rdf4j.query.algebra.And; -import org.eclipse.rdf4j.query.algebra.Filter; -import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; -import org.eclipse.rdf4j.query.algebra.helpers.collectors.VarNameCollector; - -/** - * Splits conjunctive constraints into seperate constraints. - * - * @author Arjohn Kampman - * - * @deprecated since 4.1.0. Use - * {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ConjunctiveConstraintSplitterOptimizer} - * instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class ConjunctiveConstraintSplitter - extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ConjunctiveConstraintSplitterOptimizer - implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class ConstraintVisitor extends AbstractQueryModelVisitor { - - protected final TupleExpr tupleExpr; - - public ConstraintVisitor(TupleExpr tupleExpr) { - this.tupleExpr = tupleExpr; - } - - @Override - public void meet(Filter filter) { - super.meet(filter); - - List conjunctiveConstraints = new ArrayList<>(16); - getConjunctiveConstraints(filter.getCondition(), conjunctiveConstraints); - - TupleExpr filterArg = filter.getArg(); - - for (int i = conjunctiveConstraints.size() - 1; i >= 1; i--) { - Filter newFilter = new Filter(filterArg, conjunctiveConstraints.get(i)); - filterArg = newFilter; - } - - filter.setCondition(conjunctiveConstraints.get(0)); - filter.setArg(filterArg); - } - - @Override - public void meet(LeftJoin node) { - super.meet(node); - - if (node.getCondition() != null) { - List conjunctiveConstraints = new ArrayList<>(16); - getConjunctiveConstraints(node.getCondition(), conjunctiveConstraints); - - TupleExpr arg = node.getRightArg(); - ValueExpr condition = null; - - for (ValueExpr constraint : conjunctiveConstraints) { - if (isWithinBindingScope(constraint, arg)) { - arg = new Filter(arg, constraint); - } else if (condition == null) { - condition = constraint; - } else { - condition = new And(condition, constraint); - } - } - - node.setCondition(condition); - node.setRightArg(arg); - } - } - - protected void getConjunctiveConstraints(ValueExpr valueExpr, List conjunctiveConstraints) { - if (valueExpr instanceof And) { - And and = (And) valueExpr; - getConjunctiveConstraints(and.getLeftArg(), conjunctiveConstraints); - getConjunctiveConstraints(and.getRightArg(), conjunctiveConstraints); - } else { - conjunctiveConstraints.add(valueExpr); - } - } - - private boolean isWithinBindingScope(ValueExpr condition, TupleExpr node) { - return node.getBindingNames().containsAll(VarNameCollector.process(condition)); - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConstantOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConstantOptimizer.java deleted file mode 100644 index ca96a986c2d..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConstantOptimizer.java +++ /dev/null @@ -1,307 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.impl.BooleanLiteral; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.algebra.And; -import org.eclipse.rdf4j.query.algebra.BinaryValueOperator; -import org.eclipse.rdf4j.query.algebra.Bound; -import org.eclipse.rdf4j.query.algebra.FunctionCall; -import org.eclipse.rdf4j.query.algebra.If; -import org.eclipse.rdf4j.query.algebra.Or; -import org.eclipse.rdf4j.query.algebra.ProjectionElemList; -import org.eclipse.rdf4j.query.algebra.Regex; -import org.eclipse.rdf4j.query.algebra.UnaryValueOperator; -import org.eclipse.rdf4j.query.algebra.ValueConstant; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.Var; -import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; -import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; -import org.eclipse.rdf4j.query.algebra.evaluation.function.FunctionRegistry; -import org.eclipse.rdf4j.query.algebra.evaluation.function.numeric.Rand; -import org.eclipse.rdf4j.query.algebra.evaluation.function.rdfterm.STRUUID; -import org.eclipse.rdf4j.query.algebra.evaluation.function.rdfterm.UUID; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; -import org.eclipse.rdf4j.query.impl.EmptyBindingSet; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A query optimizer that optimizes constant value expressions. - * - * @author James Leigh - * @author Arjohn Kampman - * - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ConstantOptimizer} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class ConstantOptimizer extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ConstantOptimizer - implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static final Logger logger = LoggerFactory.getLogger(ConstantOptimizer.class); - - @Deprecated(forRemoval = true, since = "4.1.0") - protected final EvaluationStrategy strategy; - - public ConstantOptimizer(EvaluationStrategy strategy) { - super(strategy); - this.strategy = null; - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected class ConstantVisitor extends VarNameCollector { - - final List projElemLists = new ArrayList<>(); - - @Override - public void meet(ProjectionElemList projElems) { - super.meet(projElems); - projElemLists.add(projElems); - } - - @Override - public void meet(Or or) { - or.visitChildren(this); - - try { - if (isConstant(or.getLeftArg()) && isConstant(or.getRightArg())) { - boolean value = strategy.isTrue(or, EmptyBindingSet.getInstance()); - or.replaceWith(new ValueConstant(BooleanLiteral.valueOf(value))); - } else if (isConstant(or.getLeftArg())) { - boolean leftIsTrue = strategy.isTrue(or.getLeftArg(), EmptyBindingSet.getInstance()); - if (leftIsTrue) { - or.replaceWith(new ValueConstant(BooleanLiteral.TRUE)); - } else { - or.replaceWith(or.getRightArg()); - } - } else if (isConstant(or.getRightArg())) { - boolean rightIsTrue = strategy.isTrue(or.getRightArg(), EmptyBindingSet.getInstance()); - if (rightIsTrue) { - or.replaceWith(new ValueConstant(BooleanLiteral.TRUE)); - } else { - or.replaceWith(or.getLeftArg()); - } - } - } catch (ValueExprEvaluationException e) { - // TODO: incompatible values types(?), remove the affected part of - // the query tree - logger.debug("Failed to evaluate BinaryValueOperator with two constant arguments", e); - } catch (QueryEvaluationException e) { - logger.error("Query evaluation exception caught", e); - } - } - - @Override - public void meet(And and) { - and.visitChildren(this); - - try { - if (isConstant(and.getLeftArg()) && isConstant(and.getRightArg())) { - boolean value = strategy.isTrue(and, EmptyBindingSet.getInstance()); - and.replaceWith(new ValueConstant(BooleanLiteral.valueOf(value))); - } else if (isConstant(and.getLeftArg())) { - boolean leftIsTrue = strategy.isTrue(and.getLeftArg(), EmptyBindingSet.getInstance()); - if (leftIsTrue) { - and.replaceWith(and.getRightArg()); - } else { - and.replaceWith(new ValueConstant(BooleanLiteral.FALSE)); - } - } else if (isConstant(and.getRightArg())) { - boolean rightIsTrue = strategy.isTrue(and.getRightArg(), EmptyBindingSet.getInstance()); - if (rightIsTrue) { - and.replaceWith(and.getLeftArg()); - } else { - and.replaceWith(new ValueConstant(BooleanLiteral.FALSE)); - } - } - } catch (ValueExprEvaluationException e) { - // TODO: incompatible values types(?), remove the affected part of - // the query tree - logger.debug("Failed to evaluate BinaryValueOperator with two constant arguments", e); - } catch (QueryEvaluationException e) { - logger.error("Query evaluation exception caught", e); - } - } - - @Override - protected void meetBinaryValueOperator(BinaryValueOperator binaryValueOp) { - super.meetBinaryValueOperator(binaryValueOp); - - if (isConstant(binaryValueOp.getLeftArg()) && isConstant(binaryValueOp.getRightArg())) { - try { - Value value = strategy.evaluate(binaryValueOp, EmptyBindingSet.getInstance()); - binaryValueOp.replaceWith(new ValueConstant(value)); - } catch (ValueExprEvaluationException e) { - // TODO: incompatible values types(?), remove the affected part - // of the query tree - logger.debug("Failed to evaluate BinaryValueOperator with two constant arguments", e); - } catch (QueryEvaluationException e) { - logger.error("Query evaluation exception caught", e); - } - } - } - - @Override - protected void meetUnaryValueOperator(UnaryValueOperator unaryValueOp) { - super.meetUnaryValueOperator(unaryValueOp); - - if (isConstant(unaryValueOp.getArg())) { - try { - Value value = strategy.evaluate(unaryValueOp, EmptyBindingSet.getInstance()); - unaryValueOp.replaceWith(new ValueConstant(value)); - } catch (ValueExprEvaluationException e) { - // TODO: incompatible values types(?), remove the affected part - // of the query tree - logger.debug("Failed to evaluate UnaryValueOperator with a constant argument", e); - } catch (QueryEvaluationException e) { - logger.error("Query evaluation exception caught", e); - } - } - } - - @Override - public void meet(FunctionCall functionCall) { - super.meet(functionCall); - - List args = functionCall.getArgs(); - - if (args.isEmpty()) { - /* - * SPARQL has two types of zero-arg function. One are proper 'constant' functions like NOW() which - * generate a single value for the entire query and which can be safely optimized to a constant. Other - * functions, like RAND(), UUID() and STRUUID(), are a special case: they are expected to yield a new - * value on every call, and can therefore not be replaced by a constant. - */ - if (!isConstantZeroArgFunction(functionCall)) { - return; - } - } else { - for (ValueExpr arg : args) { - if (!isConstant(arg)) { - return; - } - } - } - - // All arguments are constant - - try { - Value value = strategy.evaluate(functionCall, EmptyBindingSet.getInstance()); - functionCall.replaceWith(new ValueConstant(value)); - } catch (ValueExprEvaluationException e) { - // TODO: incompatible values types(?), remove the affected part of - // the query tree - logger.debug("Failed to evaluate BinaryValueOperator with two constant arguments", e); - } catch (QueryEvaluationException e) { - logger.error("Query evaluation exception caught", e); - } - } - - /** - * Determines if the provided zero-arg function is a function that should return a constant value for the entire - * query execution (e.g NOW()), or if it should generate a new value for every call (e.g. RAND()). - * - * @param functionCall a zero-arg function call. - * @return true iff the provided function returns a constant value for the query execution, false - * otherwise. - */ - private boolean isConstantZeroArgFunction(FunctionCall functionCall) { - Function function = FunctionRegistry.getInstance() - .get(functionCall.getURI()) - .orElseThrow(() -> new QueryEvaluationException( - "Unable to find function with the URI: " + functionCall.getURI())); - - // we treat constant functions as the 'regular case' and make - // exceptions for specific SPARQL built-in functions that require - // different treatment. - if (function instanceof Rand || function instanceof UUID || function instanceof STRUUID) { - return false; - } - - return true; - } - - @Override - public void meet(Bound bound) { - super.meet(bound); - - if (bound.getArg().hasValue()) { - // variable is always bound - bound.replaceWith(new ValueConstant(BooleanLiteral.TRUE)); - } - } - - @Override - public void meet(If node) { - super.meet(node); - - if (isConstant(node.getCondition())) { - try { - if (strategy.isTrue(node.getCondition(), EmptyBindingSet.getInstance())) { - node.replaceWith(node.getResult()); - } else { - node.replaceWith(node.getAlternative()); - } - } catch (ValueExprEvaluationException e) { - logger.debug("Failed to evaluate UnaryValueOperator with a constant argument", e); - } catch (QueryEvaluationException e) { - logger.error("Query evaluation exception caught", e); - } - } - } - - /** - * Override meetBinaryValueOperator - */ - @Override - public void meet(Regex node) { - super.meetNode(node); - - if (isConstant(node.getArg()) && isConstant(node.getPatternArg()) && isConstant(node.getFlagsArg())) { - try { - Value value = strategy.evaluate(node, EmptyBindingSet.getInstance()); - node.replaceWith(new ValueConstant(value)); - } catch (ValueExprEvaluationException e) { - logger.debug("Failed to evaluate BinaryValueOperator with two constant arguments", e); - } catch (QueryEvaluationException e) { - logger.error("Query evaluation exception caught", e); - } - } - } - - private boolean isConstant(ValueExpr expr) { - return expr instanceof ValueConstant || expr instanceof Var && ((Var) expr).hasValue(); - } - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected class VarNameCollector extends AbstractQueryModelVisitor { - - final Set varNames = new HashSet<>(); - - @Override - public void meet(Var var) { - if (!var.isAnonymous()) { - varNames.add(var.getName()); - } - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/DefaultEvaluationStrategy.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/DefaultEvaluationStrategy.java index 50df541f05b..ee50f83d191 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/DefaultEvaluationStrategy.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/DefaultEvaluationStrategy.java @@ -35,7 +35,7 @@ import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.impl.BooleanLiteral; import org.eclipse.rdf4j.model.util.Literals; import org.eclipse.rdf4j.query.BindingSet; @@ -77,7 +77,6 @@ import org.eclipse.rdf4j.query.algebra.Lang; import org.eclipse.rdf4j.query.algebra.LangMatches; import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.Like; import org.eclipse.rdf4j.query.algebra.ListMemberOperator; import org.eclipse.rdf4j.query.algebra.LocalName; import org.eclipse.rdf4j.query.algebra.MathExpr; @@ -166,7 +165,6 @@ import org.eclipse.rdf4j.query.algebra.evaluation.util.ValueComparator; import org.eclipse.rdf4j.query.algebra.evaluation.util.XMLDatatypeMathUtil; import org.eclipse.rdf4j.query.impl.EmptyBindingSet; -import org.eclipse.rdf4j.util.UUIDable; import com.google.common.base.Stopwatch; @@ -183,7 +181,7 @@ * @author David Huynh * @author Andreas Schwarte */ -public class DefaultEvaluationStrategy implements EvaluationStrategy, FederatedServiceResolverClient, UUIDable { +public class DefaultEvaluationStrategy implements EvaluationStrategy, FederatedServiceResolverClient { protected final TripleSource tripleSource; @@ -214,12 +212,12 @@ public class DefaultEvaluationStrategy implements EvaluationStrategy, FederatedS private Supplier collectionFactory = DefaultCollectionFactory::new; - static CloseableIteration evaluate(TupleFunction func, + static CloseableIteration evaluate(TupleFunction func, final List resultVars, final BindingSet bindings, ValueFactory valueFactory, Value... argValues) throws QueryEvaluationException { - final CloseableIteration, QueryEvaluationException> iter = func + final CloseableIteration> iter = func .evaluate(valueFactory, argValues); - return new LookAheadIteration() { + return new LookAheadIteration() { @Override public BindingSet getNextElement() throws QueryEvaluationException { @@ -298,15 +296,6 @@ public DefaultEvaluationStrategy(TripleSource tripleSource, Dataset dataset, this.setQueryEvaluationMode(QueryEvaluationMode.STANDARD); } - @Deprecated(forRemoval = true, since = "4.0.0") - @Override - synchronized public UUID getUUID() { - if (uuid == null) { - uuid = UUID.randomUUID(); - } - return uuid; - } - @Override public void setFederatedServiceResolver(FederatedServiceResolver resolver) { serviceResolver = resolver; @@ -347,32 +336,75 @@ public TupleExpr optimize(TupleExpr expr, EvaluationStatistics evaluationStatist return expr; } - @Deprecated(forRemoval = true) + @Deprecated(forRemoval = true) // this method is still in use and I think that there is quite a lot of work left + // before it can be removed @Override - public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) + public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) throws QueryEvaluationException { - CloseableIteration ret = null; - + CloseableIteration result = null; try { if (expr instanceof StatementPattern) { - ret = evaluate((StatementPattern) expr, bindings); + result = precompile(expr).evaluate(bindings); } else if (expr instanceof UnaryTupleOperator) { - ret = evaluate((UnaryTupleOperator) expr, bindings); + if (expr instanceof Projection) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof MultiProjection) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Filter) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Service) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Slice) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Extension) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Distinct) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Reduced) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Group) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Order) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof QueryRoot) { + // new query, reset shared return value for successive calls of + // NOW() + this.sharedValueOfNow = null; + result = evaluate(((UnaryTupleOperator) expr).getArg(), bindings); + } else if (expr instanceof DescribeOperator) { + result = precompile(expr).evaluate(bindings); + } else { + throw new QueryEvaluationException( + "Unknown unary tuple operator type: " + ((UnaryTupleOperator) expr).getClass()); + } } else if (expr instanceof BinaryTupleOperator) { - ret = evaluate((BinaryTupleOperator) expr, bindings); + if (expr instanceof Join) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof LeftJoin) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Union) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Intersection) { + result = precompile(expr).evaluate(bindings); + } else if (expr instanceof Difference) { + result = precompile(expr).evaluate(bindings); + } else { + throw new QueryEvaluationException( + "Unsupported binary tuple operator type: " + ((BinaryTupleOperator) expr).getClass()); + } } else if (expr instanceof SingletonSet) { - ret = evaluate((SingletonSet) expr, bindings); + result = precompile(expr).evaluate(bindings); } else if (expr instanceof EmptySet) { - ret = evaluate((EmptySet) expr, bindings); + result = new EmptyIteration<>(); } else if (expr instanceof ZeroLengthPath) { - ret = evaluate((ZeroLengthPath) expr, bindings); + result = precompile(expr).evaluate(bindings); } else if (expr instanceof ArbitraryLengthPath) { - ret = evaluate((ArbitraryLengthPath) expr, bindings); + result = precompile(expr).evaluate(bindings); } else if (expr instanceof BindingSetAssignment) { - ret = evaluate((BindingSetAssignment) expr, bindings); + result = precompile(expr).evaluate(bindings); } else if (expr instanceof TripleRef) { - ret = evaluate((TripleRef) expr, bindings); + result = evaluate((TripleRef) expr, bindings); } else if (expr instanceof TupleFunctionCall) { if (getQueryEvaluationMode().compareTo(QueryEvaluationMode.STANDARD) < 0) { throw new QueryEvaluationException( @@ -388,19 +420,18 @@ public CloseableIteration evaluate(TupleEx if (trackTime) { // set resultsSizeActual to at least be 0 so we can track iterations that don't procude anything expr.setTotalTimeNanosActual(Math.max(0, expr.getTotalTimeNanosActual())); - ret = new TimedIterator(ret, expr); + result = new TimedIterator(result, expr); } if (trackResultSize) { // set resultsSizeActual to at least be 0 so we can track iterations that don't procude anything expr.setResultSizeActual(Math.max(0, expr.getResultSizeActual())); - ret = new ResultSizeCountingIterator(ret, expr); + result = new ResultSizeCountingIterator(result, expr); } - return ret; - + return result; } catch (Throwable t) { - if (ret != null) { - ret.close(); + if (result != null) { + result.close(); } throw t; } @@ -456,30 +487,24 @@ public QueryEvaluationStep precompile(TupleExpr expr, QueryEvaluationContext con } return ret; } else { - return EvaluationStrategy.super.precompile(expr); + return QueryEvaluationStep.minimal(this, expr); } } private QueryEvaluationStep trackResultSize(TupleExpr expr, QueryEvaluationStep qes) { - return QueryEvaluationStep.wrap(qes, (iter) -> { + return QueryEvaluationStep.wrap(qes, iter -> { expr.setResultSizeActual(Math.max(0, expr.getResultSizeActual())); return new ResultSizeCountingIterator(iter, expr); }); } private QueryEvaluationStep trackTime(TupleExpr expr, QueryEvaluationStep qes) { - return QueryEvaluationStep.wrap(qes, (iter) -> { + return QueryEvaluationStep.wrap(qes, iter -> { expr.setTotalTimeNanosActual(Math.max(0, expr.getTotalTimeNanosActual())); return new TimedIterator(iter, expr); }); } - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(ArbitraryLengthPath alp, - final BindingSet bindings) throws QueryEvaluationException { - return precompile(alp).evaluate(bindings); - } - protected QueryEvaluationStep prepare(ArbitraryLengthPath alp, QueryEvaluationContext context) throws QueryEvaluationException { final Scope scope = alp.getScope(); @@ -488,20 +513,8 @@ protected QueryEvaluationStep prepare(ArbitraryLengthPath alp, QueryEvaluationCo final Var objVar = alp.getObjectVar(); final Var contextVar = alp.getContextVar(); final long minLength = alp.getMinLength(); - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bindings) { - return new PathIteration(DefaultEvaluationStrategy.this, scope, subjectVar, pathExpression, objVar, - contextVar, minLength, bindings); - } - }; - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(ZeroLengthPath zlp, - final BindingSet bindings) throws QueryEvaluationException { - return precompile(zlp).evaluate(bindings); + return bindings -> new PathIteration(DefaultEvaluationStrategy.this, scope, subjectVar, pathExpression, objVar, + contextVar, minLength, bindings); } protected QueryEvaluationStep prepare(ZeroLengthPath zlp, QueryEvaluationContext context) @@ -516,29 +529,6 @@ protected QueryEvaluationStep prepare(ZeroLengthPath zlp, QueryEvaluationContext return new ZeroLengthPathEvaluationStep(subjectVar, objVar, contextVar, subPrep, objPrep, this, context); } - @Deprecated(forRemoval = true) - @Override - public CloseableIteration evaluate(Service service, String serviceUri, - CloseableIteration bindings) throws QueryEvaluationException { - try { - FederatedService fs = serviceResolver.getService(serviceUri); - return fs.evaluate(service, bindings, service.getBaseURI()); - } catch (QueryEvaluationException e) { - // suppress exceptions if silent - if (service.isSilent()) { - return bindings; - } else { - throw new QueryEvaluationException(e); - } - } - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Service service, BindingSet bindings) - throws QueryEvaluationException { - return precompile(service).evaluate(bindings); - } - protected QueryEvaluationStep prepare(Difference node, QueryEvaluationContext context) throws QueryEvaluationException { return new MinusQueryEvaluationStep(precompile(node.getLeftArg(), context), @@ -546,13 +536,9 @@ protected QueryEvaluationStep prepare(Difference node, QueryEvaluationContext co } protected QueryEvaluationStep prepare(Group node, QueryEvaluationContext context) throws QueryEvaluationException { - return new QueryEvaluationStep() { - @Override - public CloseableIteration evaluate(BindingSet bindings) { - return new GroupIterator(DefaultEvaluationStrategy.this, node, bindings, iterationCacheSyncThreshold, - context); - } - }; + return bindings -> new GroupIterator(DefaultEvaluationStrategy.this, node, bindings, + iterationCacheSyncThreshold, + context); } protected QueryEvaluationStep prepare(Intersection node, QueryEvaluationContext context) @@ -574,11 +560,16 @@ protected QueryEvaluationStep prepare(LeftJoin node, QueryEvaluationContext cont protected QueryEvaluationStep prepare(MultiProjection node, QueryEvaluationContext context) throws QueryEvaluationException { QueryEvaluationStep arg = precompile(node.getArg(), context); - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bindings) { - return new MultiProjectionIterator(node, arg.evaluate(bindings), bindings); + return bindings -> { + CloseableIteration evaluate = null; + try { + evaluate = arg.evaluate(bindings); + return new MultiProjectionIterator(node, evaluate, bindings); + } catch (Throwable t) { + if (evaluate != null) { + evaluate.close(); + } + throw t; } }; } @@ -637,19 +628,20 @@ protected QueryEvaluationStep prepare(Filter node, QueryEvaluationContext contex // If we have a failed compilation we always return false. // Which means empty. so let's short circuit that. // ves = new QueryValueEvaluationStep.ConstantQueryValueEvaluationStep(BooleanLiteral.FALSE); - return new QueryEvaluationStep() { - @Override - public CloseableIteration evaluate(BindingSet bs) { - return new EmptyIteration<>(); - } - }; + return bs -> new EmptyIteration<>(); } - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bs) { - return new FilterIterator(node, arg.evaluate(bs), ves, DefaultEvaluationStrategy.this); + return bs -> { + CloseableIteration evaluate = null; + try { + evaluate = arg.evaluate(bs); + return new FilterIterator(node, evaluate, ves, DefaultEvaluationStrategy.this); + } catch (Throwable t) { + if (evaluate != null) { + evaluate.close(); + } + throw t; } + }; } @@ -678,71 +670,74 @@ private QueryRootQueryEvaluationStep(QueryEvaluationStep arg, QueryEvaluationCon } @Override - public CloseableIteration evaluate(BindingSet bs) { + public CloseableIteration evaluate(BindingSet bs) { // TODO fix the sharing of the now element to be safe DefaultEvaluationStrategy.this.sharedValueOfNow = null; - CloseableIteration evaluate = arg.evaluate(bs); - CloseableIteration closeContext = new CloseableIteration() { + CloseableIteration evaluate = null; + try { + evaluate = arg.evaluate(bs); + var eval = evaluate; - @Override - public boolean hasNext() throws QueryEvaluationException { - return evaluate.hasNext(); - } + CloseableIteration closeContext = new CloseableIteration<>() { - @Override - public BindingSet next() throws QueryEvaluationException { - return evaluate.next(); - } + @Override + public boolean hasNext() throws QueryEvaluationException { + return eval.hasNext(); + } - @Override - public void remove() throws QueryEvaluationException { - evaluate.remove(); + @Override + public BindingSet next() throws QueryEvaluationException { + return eval.next(); + } - } + @Override + public void remove() throws QueryEvaluationException { + eval.remove(); + + } - @Override - public void close() throws QueryEvaluationException { + @Override + public void close() throws QueryEvaluationException { + eval.close(); + } + }; + return closeContext; + } catch (Throwable t) { + if (evaluate != null) { evaluate.close(); } - }; - return evaluate; + throw t; + } } + } protected QueryEvaluationStep prepare(DescribeOperator node, QueryEvaluationContext context) throws QueryEvaluationException { QueryEvaluationStep child = precompile(node.getArg(), context); - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bs) { - CloseableIteration evaluate = null; + return bs -> { + CloseableIteration evaluate = null; - try { - evaluate = child.evaluate(bs); - return new DescribeIteration(evaluate, DefaultEvaluationStrategy.this, node.getBindingNames(), bs); - } catch (Throwable t) { - if (evaluate != null) { - evaluate.close(); - } - throw t; + try { + evaluate = child.evaluate(bs); + return new DescribeIteration(evaluate, DefaultEvaluationStrategy.this, node.getBindingNames(), bs); + } catch (Throwable t) { + if (evaluate != null) { + evaluate.close(); } - + throw t; } + }; } protected QueryEvaluationStep prepare(Distinct node, QueryEvaluationContext context) throws QueryEvaluationException { final QueryEvaluationStep child = precompile(node.getArg(), context); - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bindings) { - final CloseableIteration evaluate = child.evaluate(bindings); - return new DistinctIteration(evaluate, - DefaultEvaluationStrategy.this::makeSet); - } + return bindings -> { + final CloseableIteration evaluate = child.evaluate(bindings); + return new DistinctIteration(evaluate, + DefaultEvaluationStrategy.this::makeSet); }; } @@ -750,13 +745,7 @@ public CloseableIteration evaluate(Binding protected QueryEvaluationStep prepare(Reduced node, QueryEvaluationContext context) throws QueryEvaluationException { QueryEvaluationStep arg = precompile(node.getArg(), context); - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bindings) { - return new ReducedIteration<>(arg.evaluate(bindings)); - } - }; + return bindings -> new ReducedIteration<>(arg.evaluate(bindings)); } protected QueryEvaluationStep prepare(TupleFunctionCall expr, QueryEvaluationContext context) @@ -770,31 +759,15 @@ protected QueryEvaluationStep prepare(TupleFunctionCall expr, QueryEvaluationCon argEpresions[i] = precompile(args.get(i), context); } - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bindings) { - Value[] argValues = new Value[args.size()]; - for (int i = 0; i < args.size(); i++) { - argValues[i] = argEpresions[i].evaluate(bindings); - } - - return DefaultEvaluationStrategy.evaluate(func, expr.getResultVars(), bindings, - tripleSource.getValueFactory(), argValues); + return bindings -> { + Value[] argValues = new Value[args.size()]; + for (int i = 0; i < args.size(); i++) { + argValues[i] = argEpresions[i].evaluate(bindings); } - }; - } - @Deprecated - public CloseableIteration evaluate(DescribeOperator operator, - final BindingSet bindings) throws QueryEvaluationException { - return precompile(operator).evaluate(bindings); - } - - @Deprecated - public CloseableIteration evaluate(StatementPattern statementPattern, - final BindingSet bindings) throws QueryEvaluationException { - return precompile(statementPattern).evaluate(bindings); + return evaluate(func, expr.getResultVars(), bindings, + tripleSource.getValueFactory(), argValues); + }; } public static Value getVarValue(Var var, BindingSet bindings) { @@ -807,43 +780,6 @@ public static Value getVarValue(Var var, BindingSet bindings) { } } - @Deprecated - public CloseableIteration evaluate(UnaryTupleOperator expr, - BindingSet bindings) throws QueryEvaluationException { - if (expr instanceof Projection) { - return evaluate((Projection) expr, bindings); - } else if (expr instanceof MultiProjection) { - return evaluate((MultiProjection) expr, bindings); - } else if (expr instanceof Filter) { - return evaluate((Filter) expr, bindings); - } else if (expr instanceof Service) { - return evaluate((Service) expr, bindings); - } else if (expr instanceof Slice) { - return evaluate((Slice) expr, bindings); - } else if (expr instanceof Extension) { - return evaluate((Extension) expr, bindings); - } else if (expr instanceof Distinct) { - return evaluate((Distinct) expr, bindings); - } else if (expr instanceof Reduced) { - return evaluate((Reduced) expr, bindings); - } else if (expr instanceof Group) { - return evaluate((Group) expr, bindings); - } else if (expr instanceof Order) { - return evaluate((Order) expr, bindings); - } else if (expr instanceof QueryRoot) { - // new query, reset shared return value for successive calls of - // NOW() - this.sharedValueOfNow = null; - return evaluate(expr.getArg(), bindings); - } else if (expr instanceof DescribeOperator) { - return evaluate((DescribeOperator) expr, bindings); - } else if (expr == null) { - throw new IllegalArgumentException("expr must not be null"); - } else { - throw new QueryEvaluationException("Unknown unary tuple operator type: " + expr.getClass()); - } - } - protected QueryEvaluationStep prepare(UnaryTupleOperator expr, QueryEvaluationContext context) throws QueryEvaluationException { if (expr instanceof Projection) { @@ -880,86 +816,6 @@ protected QueryEvaluationStep prepare(UnaryTupleOperator expr, QueryEvaluationCo } } - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(BindingSetAssignment bsa, - BindingSet bindings) throws QueryEvaluationException { - return precompile(bsa).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Projection projection, BindingSet bindings) - throws QueryEvaluationException { - return precompile(projection).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(MultiProjection multiProjection, - BindingSet bindings) throws QueryEvaluationException { - return precompile(multiProjection).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Filter filter, BindingSet bindings) - throws QueryEvaluationException { - return precompile(filter).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Slice slice, BindingSet bindings) - throws QueryEvaluationException { - return precompile(slice).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Extension extension, BindingSet bindings) - throws QueryEvaluationException { - return precompile(extension).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Distinct distinct, BindingSet bindings) - throws QueryEvaluationException { - return precompile(distinct).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Reduced reduced, BindingSet bindings) - throws QueryEvaluationException { - return new ReducedIteration<>(evaluate(reduced.getArg(), bindings)); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Group node, BindingSet bindings) - throws QueryEvaluationException { - return precompile(node).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Order node, BindingSet bindings) - throws QueryEvaluationException { - return precompile(node).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(BinaryTupleOperator expr, - BindingSet bindings) throws QueryEvaluationException { - if (expr instanceof Join) { - return evaluate((Join) expr, bindings); - } else if (expr instanceof LeftJoin) { - return evaluate((LeftJoin) expr, bindings); - } else if (expr instanceof Union) { - return evaluate((Union) expr, bindings); - } else if (expr instanceof Intersection) { - return evaluate((Intersection) expr, bindings); - } else if (expr instanceof Difference) { - return evaluate((Difference) expr, bindings); - } else if (expr == null) { - throw new IllegalArgumentException("expr must not be null"); - } else { - throw new QueryEvaluationException("Unsupported binary tuple operator type: " + expr.getClass()); - } - } - protected QueryEvaluationStep prepare(BinaryTupleOperator expr, QueryEvaluationContext context) throws QueryEvaluationException { if (expr instanceof Join) { @@ -979,69 +835,15 @@ protected QueryEvaluationStep prepare(BinaryTupleOperator expr, QueryEvaluationC } } - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(Join join, BindingSet bindings) - throws QueryEvaluationException { - return precompile(join).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(LeftJoin leftJoin, - final BindingSet bindings) throws QueryEvaluationException { - return precompile(leftJoin).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(final Union union, - final BindingSet bindings) throws QueryEvaluationException { - return precompile(union).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(final Intersection intersection, - final BindingSet bindings) throws QueryEvaluationException { - return precompile(intersection).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(final Difference difference, - final BindingSet bindings) throws QueryEvaluationException { - return precompile(difference).evaluate(bindings); - } - - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(SingletonSet singletonSet, - BindingSet bindings) throws QueryEvaluationException { - return new SingletonIteration<>(bindings); - } - protected QueryEvaluationStep prepare(SingletonSet singletonSet, QueryEvaluationContext context) throws QueryEvaluationException { - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bindings) { - return new SingletonIteration<>(bindings); - } - }; + return SingletonIteration::new; } - @Deprecated(forRemoval = true) - public CloseableIteration evaluate(EmptySet emptySet, BindingSet bindings) - throws QueryEvaluationException { - return new EmptyIteration<>(); - } - protected QueryEvaluationStep prepare(EmptySet emptySet, QueryEvaluationContext context) throws QueryEvaluationException { - return new QueryEvaluationStep() { - - @Override - public CloseableIteration evaluate(BindingSet bindings) { - return new EmptyIteration<>(); - } - }; + return bindings -> new EmptyIteration<>(); } @Override @@ -1087,8 +889,6 @@ public QueryValueEvaluationStep precompile(ValueExpr expr, return prepare((Regex) expr, context); } else if (expr instanceof Coalesce) { return prepare((Coalesce) expr, context); - } else if (expr instanceof Like) { - return new QueryValueEvaluationStep.Minimal(this, expr); } else if (expr instanceof FunctionCall) { return prepare((FunctionCall) expr, context); } else if (expr instanceof And) { @@ -1133,21 +933,6 @@ public Value evaluate(ValueExpr expr, BindingSet bindings) .evaluate(bindings); } - @Deprecated(forRemoval = true) - public Value evaluate(Var var, BindingSet bindings) throws QueryEvaluationException { - Value value = var.getValue(); - - if (value == null) { - value = bindings.getValue(var.getName()); - } - - if (value == null) { - throw new ValueExprEvaluationException(); - } - - return value; - } - protected QueryValueEvaluationStep prepare(Var var, QueryEvaluationContext context) throws QueryEvaluationException { @@ -1157,38 +942,22 @@ protected QueryValueEvaluationStep prepare(Var var, QueryEvaluationContext conte return new ConstantQueryValueEvaluationStep(value); } else { java.util.function.Function getValue = context.getValue(var.getName()); - return new QueryValueEvaluationStep() { - - @Override - public Value evaluate(BindingSet bindings) - throws QueryEvaluationException { - Value value = getValue.apply(bindings); - if (value == null) { - throw new ValueExprEvaluationException(); - } - return value; + return bindings -> { + Value value1 = getValue.apply(bindings); + if (value1 == null) { + throw new ValueExprEvaluationException(); } + return value1; }; } } - @Deprecated(forRemoval = true) - public Value evaluate(ValueConstant valueConstant, BindingSet bindings) - throws QueryEvaluationException { - return valueConstant.getValue(); - } - protected QueryValueEvaluationStep prepare(ValueConstant valueConstant, QueryEvaluationContext context) throws QueryEvaluationException { return new ConstantQueryValueEvaluationStep(valueConstant); } - @Deprecated(forRemoval = true) - public Value evaluate(BNodeGenerator node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(BNodeGenerator node, QueryEvaluationContext context) throws QueryEvaluationException { ValueFactory vf = tripleSource.getValueFactory(); @@ -1197,15 +966,10 @@ protected QueryValueEvaluationStep prepare(BNodeGenerator node, QueryEvaluationC QueryValueEvaluationStep nodeVes = precompile(nodeIdExpr, context); return QueryValueEvaluationStepSupplier.bnode(nodeVes, vf); } else { - return new QueryValueEvaluationStep.ApplyFunctionForEachBinding((bs) -> vf.createBNode()); + return new QueryValueEvaluationStep.ApplyFunctionForEachBinding(bs -> vf.createBNode()); } } - @Deprecated(forRemoval = true) - public Value evaluate(Bound node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(Bound node, QueryEvaluationContext context) throws QueryEvaluationException { try { @@ -1216,11 +980,6 @@ protected QueryValueEvaluationStep prepare(Bound node, QueryEvaluationContext co } } - @Deprecated(forRemoval = true) - public Value evaluate(Str node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(Str node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep arg = precompile(node.getArg(), context); @@ -1228,23 +987,12 @@ protected QueryValueEvaluationStep prepare(Str node, QueryEvaluationContext cont return QueryValueEvaluationStepSupplier.prepareStr(arg, valueFactory); } - @Deprecated(forRemoval = true) - public Value evaluate(Label node, BindingSet bindings) - throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(Label node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareLabel(arg, tripleSource.getValueFactory()); } - @Deprecated(forRemoval = true) - public Value evaluate(Lang node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(Lang node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareLang(arg, tripleSource.getValueFactory()); @@ -1259,99 +1007,36 @@ protected QueryValueEvaluationStep prepare(Datatype node, QueryEvaluationContext return QueryValueEvaluationStepSupplier.prepareDatatype(arg, context); } - @Deprecated(forRemoval = true) - public Value evaluate(Namespace node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(Namespace node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareNamespace(arg, tripleSource.getValueFactory()); } - @Deprecated(forRemoval = true) - public Value evaluate(LocalName node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(LocalName node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareLocalName(arg, tripleSource.getValueFactory()); } - /** - * Determines whether the operand (a variable) contains a Resource. - * - * @return true if the operand contains a Resource, false otherwise. - */ - @Deprecated(forRemoval = true) - public Value evaluate(IsResource node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(IsResource node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareIs(arg, v -> v instanceof Resource); } - /** - * Determines whether the operand (a variable) contains a URI. - * - * @return true if the operand contains a URI, false otherwise. - */ - @Deprecated(forRemoval = true) - public Value evaluate(IsURI node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(IsURI node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareIs(arg, v -> v instanceof IRI); } - /** - * Determines whether the operand (a variable) contains a BNode. - * - * @return true if the operand contains a BNode, false otherwise. - */ - @Deprecated(forRemoval = true) - public Value evaluate(IsBNode node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(IsBNode node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareIs(arg, v -> v instanceof BNode); } - /** - * Determines whether the operand (a variable) contains a Literal. - * - * @return true if the operand contains a Literal, false otherwise. - */ - @Deprecated(forRemoval = true) - public Value evaluate(IsLiteral node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(IsLiteral node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareIs(arg, v -> v instanceof Literal); } - /** - * Determines whether the operand (a variable) contains a numeric datatyped literal, i.e. a literal with datatype - * CoreDatatype.XSD:float, CoreDatatype.XSD:double, CoreDatatype.XSD:decimal, or a derived datatype of - * CoreDatatype.XSD:decimal. - * - * @return true if the operand contains a numeric datatyped literal, false otherwise. - */ - @Deprecated(forRemoval = true) - public Value evaluate(IsNumeric node, BindingSet bindings) - throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(IsNumeric node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareIs(arg, DefaultEvaluationStrategy::isNumeric); @@ -1360,27 +1045,13 @@ protected QueryValueEvaluationStep prepare(IsNumeric node, QueryEvaluationContex private static boolean isNumeric(Value argValue) { if (argValue instanceof Literal) { Literal lit = (Literal) argValue; - IRI datatype = lit.getDatatype(); - return XMLDatatypeUtil.isNumericDatatype(datatype); + CoreDatatype.XSD datatype = lit.getCoreDatatype().asXSDDatatypeOrNull(); + return datatype != null && datatype.isNumericDatatype(); } else { return false; } } - /** - * Creates a URI from the operand value (a plain literal or a URI). - * - * @param node represents an invocation of the SPARQL IRI function - * @param bindings used to generate the value that the URI is based on - * @return a URI generated from the given arguments - * @throws QueryEvaluationException - */ - @Deprecated(forRemoval = true) - public IRI evaluate(IRIFunction node, BindingSet bindings) - throws QueryEvaluationException { - return (IRI) prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(IRIFunction node, QueryEvaluationContext context) { QueryValueEvaluationStep arg = precompile(node.getArg(), context); return QueryValueEvaluationStepSupplier.prepareIriFunction(node, arg, tripleSource.getValueFactory()); @@ -1409,17 +1080,8 @@ protected QueryValueEvaluationStep prepare(Regex node, QueryEvaluationContext co return RegexValueEvaluationStepSupplier.make(this, node, context); } - @Deprecated(forRemoval = true) - public Value evaluate(LangMatches node, BindingSet bindings) - throws QueryEvaluationException { - Value langTagValue = evaluate(node.getLeftArg(), bindings); - Value langRangeValue = evaluate(node.getRightArg(), bindings); - - return evaluateLangMatch(langTagValue, langRangeValue); - } - protected QueryValueEvaluationStep prepare(LangMatches node, QueryEvaluationContext context) { - return supplyBinaryValueEvaluation(node, (leftVal, rightVal) -> evaluateLangMatch(leftVal, rightVal), context); + return supplyBinaryValueEvaluation(node, this::evaluateLangMatch, context); } private Value evaluateLangMatch(Value langTagValue, Value langRangeValue) { @@ -1436,130 +1098,6 @@ private Value evaluateLangMatch(Value langTagValue, Value langRangeValue) { throw new ValueExprEvaluationException(); } - /** - * Determines whether the two operands match according to the like operator. The operator is defined as - * a string comparison with the possible use of an asterisk (*) at the end and/or the start of the second operand to - * indicate substring matching. - * - * @return true if the operands match according to the like operator, false - * otherwise. - */ - @Deprecated(forRemoval = true) - public Value evaluate(Like node, BindingSet bindings) - throws QueryEvaluationException { - Value val = evaluate(node.getArg(), bindings); - String strVal = null; - - if (val instanceof IRI) { - strVal = val.toString(); - } else if (val instanceof Literal) { - strVal = ((Literal) val).getLabel(); - } - - if (strVal == null) { - throw new ValueExprEvaluationException(); - } - - if (!node.isCaseSensitive()) { - // Convert strVal to lower case, just like the pattern has been done - strVal = strVal.toLowerCase(); - } - - int valIndex = 0; - int prevPatternIndex = -1; - int patternIndex = node.getOpPattern().indexOf('*'); - - if (patternIndex == -1) { - // No wildcards - return BooleanLiteral.valueOf(node.getOpPattern().equals(strVal)); - } - - String snippet; - - if (patternIndex > 0) { - // Pattern does not start with a wildcard, first part must match - snippet = node.getOpPattern().substring(0, patternIndex); - if (!strVal.startsWith(snippet)) { - return BooleanLiteral.FALSE; - } - - valIndex += snippet.length(); - prevPatternIndex = patternIndex; - patternIndex = node.getOpPattern().indexOf('*', patternIndex + 1); - } - - while (patternIndex != -1) { - // Get snippet between previous wildcard and this wildcard - snippet = node.getOpPattern().substring(prevPatternIndex + 1, patternIndex); - - // Search for the snippet in the value - valIndex = strVal.indexOf(snippet, valIndex); - if (valIndex == -1) { - return BooleanLiteral.FALSE; - } - - valIndex += snippet.length(); - prevPatternIndex = patternIndex; - patternIndex = node.getOpPattern().indexOf('*', patternIndex + 1); - } - - // Part after last wildcard - snippet = node.getOpPattern().substring(prevPatternIndex + 1); - - if (snippet.length() > 0) { - // Pattern does not end with a wildcard. - - // Search last occurence of the snippet. - valIndex = strVal.indexOf(snippet, valIndex); - int i; - while ((i = strVal.indexOf(snippet, valIndex + 1)) != -1) { - // A later occurence was found. - valIndex = i; - } - - if (valIndex == -1) { - return BooleanLiteral.FALSE; - } - - valIndex += snippet.length(); - - if (valIndex < strVal.length()) { - // Some characters were not matched - return BooleanLiteral.FALSE; - } - } - - return BooleanLiteral.TRUE; - } - - /** - * Evaluates a function. - */ - @Deprecated(forRemoval = true) - public Value evaluate(FunctionCall node, BindingSet bindings) - throws QueryEvaluationException { - Function function = FunctionRegistry.getInstance() - .get(node.getURI()) - .orElseThrow(() -> new QueryEvaluationException("Unknown function '" + node.getURI() + "'")); - - // the NOW function is a special case as it needs to keep a shared - // return - // value for the duration of the query. - if (function instanceof Now) { - return evaluate((Now) function, bindings); - } - - List args = node.getArgs(); - - Value[] argValues = new Value[args.size()]; - - for (int i = 0; i < args.size(); i++) { - argValues[i] = evaluate(args.get(i), bindings); - } - - return function.evaluate(tripleSource, argValues); - } - public QueryValueEvaluationStep prepare(FunctionCall node, QueryEvaluationContext context) throws QueryEvaluationException { Function function = FunctionRegistry.getInstance() @@ -1587,14 +1125,9 @@ public QueryValueEvaluationStep prepare(FunctionCall node, QueryEvaluationContex return new QueryValueEvaluationStep.Fail("Constant failure: " + ex.getMessage()); } } else { - return new QueryValueEvaluationStep() { - - @Override - public Value evaluate(BindingSet bindings) - throws QueryEvaluationException { - Value[] argValues = evaluateAllArguments(args, argSteps, bindings); - return function.evaluate(tripleSource, argValues); - } + return bindings -> { + Value[] argValues = evaluateAllArguments(args, argSteps, bindings); + return function.evaluate(tripleSource, argValues); }; } } @@ -1636,11 +1169,6 @@ private Value[] evaluateAllArguments(List args, QueryValueEvaluationS return argValues; } - @Deprecated(forRemoval = true) - public Value evaluate(And node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - private QueryValueEvaluationStep prepare(And node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep leftStep = precompile(node.getLeftArg(), context); QueryValueEvaluationStep rightStep = precompile(node.getRightArg(), context); @@ -1648,11 +1176,6 @@ private QueryValueEvaluationStep prepare(And node, QueryEvaluationContext contex return AndValueEvaluationStep.supply(leftStep, rightStep); } - @Deprecated(forRemoval = true) - public Value evaluate(Or node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(Or node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep leftArg = null; @@ -1672,24 +1195,9 @@ protected QueryValueEvaluationStep prepare(Or node, QueryEvaluationContext conte return new OrValueEvaluationStep(leftArg, rightArg); } - @Deprecated(forRemoval = true) - public Value evaluate(Not node, BindingSet bindings) throws QueryEvaluationException { - Value argValue = evaluate(node.getArg(), bindings); - boolean argBoolean = QueryEvaluationUtil.getEffectiveBooleanValue(argValue); - return BooleanLiteral.valueOf(!argBoolean); - } - protected QueryValueEvaluationStep prepare(Not node, QueryEvaluationContext context) { return supplyUnaryValueEvaluation(node, - (v) -> BooleanLiteral.valueOf(!QueryEvaluationUtil.getEffectiveBooleanValue(v)), context); - } - - @Deprecated(forRemoval = true) - public Value evaluate(Now node, BindingSet bindings) throws QueryEvaluationException { - if (sharedValueOfNow == null) { - sharedValueOfNow = node.evaluate(tripleSource.getValueFactory()); - } - return sharedValueOfNow; + v -> BooleanLiteral.valueOf(!QueryEvaluationUtil.getEffectiveBooleanValue(v)), context); } /** @@ -1704,25 +1212,11 @@ protected QueryValueEvaluationStep prepare(Now node, QueryEvaluationContext cont return new QueryValueEvaluationStep.ConstantQueryValueEvaluationStep(context.getNow()); } - @Deprecated(forRemoval = true) - public Value evaluate(SameTerm node, BindingSet bindings) - throws QueryEvaluationException { - Value leftVal = evaluate(node.getLeftArg(), bindings); - Value rightVal = evaluate(node.getRightArg(), bindings); - - return BooleanLiteral.valueOf(leftVal != null && leftVal.equals(rightVal)); - } - protected QueryValueEvaluationStep prepare(SameTerm node, QueryEvaluationContext context) { return supplyBinaryValueEvaluation(node, (leftVal, rightVal) -> BooleanLiteral.valueOf(leftVal != null && leftVal.equals(rightVal)), context); } - @Deprecated(forRemoval = true) - public Value evaluate(Coalesce node, BindingSet bindings) throws ValueExprEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(sharedValueOfNow, dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(Coalesce node, QueryEvaluationContext context) throws QueryEvaluationException { List args = node.getArguments(); @@ -1735,35 +1229,21 @@ protected QueryValueEvaluationStep prepare(Coalesce node, QueryEvaluationContext } } - return new QueryValueEvaluationStep() { + return bindings -> { - @Override - public Value evaluate(BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException { - - for (QueryValueEvaluationStep expr : compiledArgs) { - try { - // return first result that does not produce an error on - // evaluation. - return expr.evaluate(bindings); + for (QueryValueEvaluationStep expr : compiledArgs) { + try { + // return first result that does not produce an error on + // evaluation. + return expr.evaluate(bindings); - } catch (QueryEvaluationException ignored) { - } + } catch (QueryEvaluationException ignored) { } - - throw new ValueExprEvaluationException( - "COALESCE arguments do not evaluate to a value: " + node.getSignature()); } - }; - } - - @Deprecated(forRemoval = true) - public Value evaluate(Compare node, BindingSet bindings) - throws QueryEvaluationException { - Value leftVal = evaluate(node.getLeftArg(), bindings); - Value rightVal = evaluate(node.getRightArg(), bindings); - boolean strict = QueryEvaluationMode.STRICT == getQueryEvaluationMode(); - return BooleanLiteral.valueOf(QueryEvaluationUtil.compare(leftVal, rightVal, node.getOperator(), strict)); + throw new ValueExprEvaluationException( + "COALESCE arguments do not evaluate to a value: " + node.getSignature()); + }; } protected QueryValueEvaluationStep prepare(Compare node, QueryEvaluationContext context) { @@ -1772,17 +1252,6 @@ protected QueryValueEvaluationStep prepare(Compare node, QueryEvaluationContext .valueOf(QueryEvaluationUtil.compare(leftVal, rightVal, node.getOperator(), strict)), context); } - @Deprecated(forRemoval = true) - public Value evaluate(MathExpr node, BindingSet bindings) - throws QueryEvaluationException { - // Do the math - Value leftVal = evaluate(node.getLeftArg(), bindings); - Value rightVal = evaluate(node.getRightArg(), bindings); - - return mathOperationApplier(node, getQueryEvaluationMode(), tripleSource.getValueFactory()).apply(leftVal, - rightVal); - } - private BiFunction mathOperationApplier(MathExpr node, QueryEvaluationMode queryEvaluationMode, ValueFactory vf) { final MathOp operator = node.getOperator(); @@ -1816,11 +1285,6 @@ protected QueryValueEvaluationStep prepare(MathExpr node, QueryEvaluationContext return supplyBinaryValueEvaluation(node, mathOperationApplier, context); } - @Deprecated(forRemoval = true) - public Value evaluate(If node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(sharedValueOfNow, dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(If node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep condition; @@ -1836,11 +1300,6 @@ protected QueryValueEvaluationStep prepare(If node, QueryEvaluationContext conte return new IfValueEvaluationStep(result, condition, alternative); } - @Deprecated(forRemoval = true) - public Value evaluate(In node, BindingSet bindings) throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(sharedValueOfNow, dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(In node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep left = precompile(node.getArg(), context); @@ -1848,12 +1307,6 @@ protected QueryValueEvaluationStep prepare(In node, QueryEvaluationContext conte return new InValueEvaluationStep(node, subquery, left); } - @Deprecated(forRemoval = true) - public Value evaluate(ListMemberOperator node, BindingSet bindings) - throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(sharedValueOfNow, dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(ListMemberOperator node, QueryEvaluationContext context) throws QueryEvaluationException { List args = node.getArguments(); @@ -1868,12 +1321,6 @@ protected QueryValueEvaluationStep prepare(ListMemberOperator node, QueryEvaluat return new ListMemberValueOperationStep(compiledArgs); } - @Deprecated(forRemoval = true) - public Value evaluate(CompareAny node, BindingSet bindings) - throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(sharedValueOfNow, dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(CompareAny node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep arg = precompile(node.getArg(), context); @@ -1881,12 +1328,6 @@ protected QueryValueEvaluationStep prepare(CompareAny node, QueryEvaluationConte return new CompareAnyValueEvaluationStep(arg, node, subquery, context); } - @Deprecated(forRemoval = true) - public Value evaluate(CompareAll node, BindingSet bindings) - throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(sharedValueOfNow, dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(CompareAll node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep arg = precompile(node.getArg(), context); @@ -1894,12 +1335,6 @@ protected QueryValueEvaluationStep prepare(CompareAll node, QueryEvaluationConte return new CompareAllQueryValueEvaluationStep(arg, node, subquery, context); } - @Deprecated(forRemoval = true) - public Value evaluate(Exists node, BindingSet bindings) - throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(sharedValueOfNow, dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(Exists node, QueryEvaluationContext context) throws QueryEvaluationException { QueryEvaluationStep subquery = precompile(node.getSubQuery(), context); @@ -1952,12 +1387,6 @@ protected long getLimit(QueryModelNode node) { return Long.MAX_VALUE; } - @Deprecated(forRemoval = true) - public Value evaluate(ValueExprTripleRef node, BindingSet bindings) - throws QueryEvaluationException { - return prepare(node, new QueryEvaluationContext.Minimal(sharedValueOfNow, dataset)).evaluate(bindings); - } - protected QueryValueEvaluationStep prepare(ValueExprTripleRef node, QueryEvaluationContext context) throws QueryEvaluationException { QueryValueEvaluationStep subject = precompile(node.getSubjectVar(), context); @@ -1976,7 +1405,7 @@ protected QueryValueEvaluationStep prepare(ValueExprTripleRef node, QueryEvaluat * @param bindings with the solutions * @return iteration over the solutions */ - public CloseableIteration evaluate(TripleRef ref, BindingSet bindings) { + public CloseableIteration evaluate(TripleRef ref, BindingSet bindings) { return precompile(ref).evaluate(bindings); } @@ -2001,12 +1430,12 @@ protected QueryEvaluationStep prepare(TripleRef ref, QueryEvaluationContext cont * This class wraps an iterator and increments the "resultSizeActual" of the query model node that the iterator * represents. This means we can track the number of tuples that have been retrieved from this node. */ - private static class ResultSizeCountingIterator extends IterationWrapper { + private static class ResultSizeCountingIterator extends IterationWrapper { - CloseableIteration iterator; + CloseableIteration iterator; QueryModelNode queryModelNode; - public ResultSizeCountingIterator(CloseableIteration iterator, + public ResultSizeCountingIterator(CloseableIteration iterator, QueryModelNode queryModelNode) { super(iterator); this.iterator = iterator; @@ -2029,14 +1458,14 @@ public BindingSet next() throws QueryEvaluationException { /** * This class wraps an iterator and tracks the time used to execute next() and hasNext() */ - private static class TimedIterator extends IterationWrapper { + private static class TimedIterator extends IterationWrapper { - CloseableIteration iterator; + CloseableIteration iterator; QueryModelNode queryModelNode; Stopwatch stopwatch = Stopwatch.createUnstarted(); - public TimedIterator(CloseableIteration iterator, + public TimedIterator(CloseableIteration iterator, QueryModelNode queryModelNode) { super(iterator); this.iterator = iterator; @@ -2101,37 +1530,22 @@ protected QueryValueEvaluationStep supplyBinaryValueEvaluation(BinaryValueOperat return new QueryValueEvaluationStep.ConstantQueryValueEvaluationStep(value); } else if (leftStep.isConstant()) { Value leftVal = leftStep.evaluate(EmptyBindingSet.getInstance()); - return new QueryValueEvaluationStep() { - - @Override - public Value evaluate(BindingSet bindings) - throws QueryEvaluationException { - Value rightVal = rightStep.evaluate(bindings); - return operation.apply(leftVal, rightVal); - } + return bindings -> { + Value rightVal = rightStep.evaluate(bindings); + return operation.apply(leftVal, rightVal); }; } else if (rightStep.isConstant()) { Value rightVal = rightStep.evaluate(EmptyBindingSet.getInstance()); - return new QueryValueEvaluationStep() { - - @Override - public Value evaluate(BindingSet bindings) - throws QueryEvaluationException { - Value leftVal = leftStep.evaluate(bindings); - Value result = operation.apply(leftVal, rightVal); - return result; - } + return bindings -> { + Value leftVal = leftStep.evaluate(bindings); + Value result = operation.apply(leftVal, rightVal); + return result; }; } else { - return new QueryValueEvaluationStep() { - - @Override - public Value evaluate(BindingSet bindings) - throws QueryEvaluationException { - Value leftVal = leftStep.evaluate(bindings); - Value rightVal = rightStep.evaluate(bindings); - return operation.apply(leftVal, rightVal); - } + return bindings -> { + Value leftVal = leftStep.evaluate(bindings); + Value rightVal = rightStep.evaluate(bindings); + return operation.apply(leftVal, rightVal); }; } } @@ -2152,14 +1566,9 @@ protected QueryValueEvaluationStep supplyUnaryValueEvaluation(UnaryValueOperator return new QueryValueEvaluationStep.ConstantQueryValueEvaluationStep(operation.apply(argValue)); } else { - return new QueryValueEvaluationStep() { - - @Override - public Value evaluate(BindingSet bindings) - throws QueryEvaluationException { - Value argValue = argStep.evaluate(bindings); - return operation.apply(argValue); - } + return bindings -> { + Value argValue = argStep.evaluate(bindings); + return operation.apply(argValue); }; } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/DisjunctiveConstraintOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/DisjunctiveConstraintOptimizer.java deleted file mode 100644 index bcebb978f34..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/DisjunctiveConstraintOptimizer.java +++ /dev/null @@ -1,91 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.algebra.And; -import org.eclipse.rdf4j.query.algebra.Filter; -import org.eclipse.rdf4j.query.algebra.Or; -import org.eclipse.rdf4j.query.algebra.SameTerm; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.Union; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; - -/** - * A query optimizer that optimize disjunctive constraints on tuple expressions. Currently, this optimizer {@link Union - * unions} a clone of the underlying tuple expression with the original expression for each {@link SameTerm} operator, - * moving the SameTerm to the cloned tuple expression. - * - * @author Arjohn Kampman - * @author James Leigh - * - * @deprecated since 4.1.0. Use - * {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.DisjunctiveConstraintOptimizer} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class DisjunctiveConstraintOptimizer extends - org.eclipse.rdf4j.query.algebra.evaluation.optimizer.DisjunctiveConstraintOptimizer implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class OrSameTermOptimizer extends AbstractQueryModelVisitor { - - @Override - public void meet(Filter filter) { - if (filter.getCondition() instanceof Or && containsSameTerm(filter.getCondition())) { - Or orNode = (Or) filter.getCondition(); - TupleExpr filterArg = filter.getArg(); - - ValueExpr leftConstraint = orNode.getLeftArg(); - ValueExpr rightConstraint = orNode.getRightArg(); - - // remove filter - filter.replaceWith(filterArg); - - // Push UNION down below other filters to avoid cloning them - TupleExpr node = findNotFilter(filterArg); - - Filter leftFilter = new Filter(node.clone(), leftConstraint); - Filter rightFilter = new Filter(node.clone(), rightConstraint); - Union union = new Union(leftFilter, rightFilter); - node.replaceWith(union); - - filter.getParentNode().visit(this); - } else { - super.meet(filter); - } - } - - private TupleExpr findNotFilter(TupleExpr node) { - if (node instanceof Filter) { - return findNotFilter(((Filter) node).getArg()); - } - return node; - } - - private boolean containsSameTerm(ValueExpr node) { - if (node instanceof SameTerm) { - return true; - } - if (node instanceof Or) { - Or or = (Or) node; - boolean left = containsSameTerm(or.getLeftArg()); - return left || containsSameTerm(or.getRightArg()); - } - if (node instanceof And) { - And and = (And) node; - boolean left = containsSameTerm(and.getLeftArg()); - return left || containsSameTerm(and.getRightArg()); - } - return false; - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStatistics.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStatistics.java index f58cd638ab1..8645802a68a 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStatistics.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStatistics.java @@ -102,7 +102,7 @@ public void meet(BindingSetAssignment node) { public void meet(ZeroLengthPath node) { Var subjVar = node.getSubjectVar(); Var objVar = node.getObjectVar(); - if ((subjVar != null && subjVar.hasValue()) || (objVar != null && objVar.hasValue())) { + if (subjVar != null && subjVar.hasValue() || objVar != null && objVar.hasValue()) { // subj = obj cardinality = 1.0; } else { @@ -148,7 +148,7 @@ public void meet(Service node) { } else { // only very selective statements should be better than this // => evaluate service expressions first - cardinality = 1 + (node.getServiceVars().size() * 0.1); + cardinality = 1 + node.getServiceVars().size() * 0.1; } } } @@ -251,7 +251,7 @@ protected double getContextCardinality(Var var) { } protected double getCardinality(double varCardinality, Var var) { - return (var == null || var.hasValue()) ? 1.0 : varCardinality; + return var == null || var.hasValue() ? 1.0 : varCardinality; } protected double getCardinality(double varCardinality, Collection vars) { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStrategyImpl.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStrategyImpl.java deleted file mode 100644 index 1891e571467..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStrategyImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource; -import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolver; - -/** - * @author Jeen Broekstra - * @deprecated Use {@link StrictEvaluationStrategy} instead. - */ -@Deprecated(since = "4.0") -public class EvaluationStrategyImpl extends StrictEvaluationStrategy { - - public EvaluationStrategyImpl(TripleSource tripleSource, Dataset dataset, - FederatedServiceResolver serviceResolver) { - super(tripleSource, dataset, serviceResolver); - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ExtendedEvaluationStrategy.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ExtendedEvaluationStrategy.java index e601b21893b..edcfd1b7a81 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ExtendedEvaluationStrategy.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ExtendedEvaluationStrategy.java @@ -10,19 +10,32 @@ *******************************************************************************/ package org.eclipse.rdf4j.query.algebra.evaluation.impl; +import java.util.List; + +import org.eclipse.rdf4j.common.iteration.CloseableIteration; +import org.eclipse.rdf4j.common.iteration.LookAheadIteration; import org.eclipse.rdf4j.common.transaction.QueryEvaluationMode; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.BooleanLiteral; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.Compare; import org.eclipse.rdf4j.query.algebra.MathExpr; +import org.eclipse.rdf4j.query.algebra.TupleExpr; +import org.eclipse.rdf4j.query.algebra.TupleFunctionCall; +import org.eclipse.rdf4j.query.algebra.ValueExpr; +import org.eclipse.rdf4j.query.algebra.Var; +import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; +import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.QueryValueEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolver; +import org.eclipse.rdf4j.query.algebra.evaluation.function.TupleFunction; +import org.eclipse.rdf4j.query.algebra.evaluation.function.TupleFunctionRegistry; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtil; import org.eclipse.rdf4j.query.algebra.evaluation.util.XMLDatatypeMathUtil; @@ -34,17 +47,71 @@ * @deprecated Use {@link DefaultEvaluationStrategy} instead. */ @Deprecated(since = "4.3.0", forRemoval = true) -public class ExtendedEvaluationStrategy extends TupleFunctionEvaluationStrategy { +public class ExtendedEvaluationStrategy extends StrictEvaluationStrategy { + + private final TupleFunctionRegistry tupleFuncRegistry; public ExtendedEvaluationStrategy(TripleSource tripleSource, Dataset dataset, FederatedServiceResolver serviceResolver, long iterationCacheSyncThreshold, EvaluationStatistics evaluationStatistics) { + this(tripleSource, dataset, serviceResolver, TupleFunctionRegistry.getInstance(), iterationCacheSyncThreshold, + evaluationStatistics); + + this.setQueryEvaluationMode(QueryEvaluationMode.STANDARD); + } + + public ExtendedEvaluationStrategy(TripleSource tripleSource, Dataset dataset, + FederatedServiceResolver serviceResolver, TupleFunctionRegistry tupleFuncRegistry, + long iterationCacheSyncThreshold, EvaluationStatistics evaluationStatistics) { super(tripleSource, dataset, serviceResolver, iterationCacheSyncThreshold, evaluationStatistics); + this.tupleFuncRegistry = tupleFuncRegistry; this.setQueryEvaluationMode(QueryEvaluationMode.STANDARD); } + public static CloseableIteration evaluate(TupleFunction func, + final List resultVars, final BindingSet bindings, ValueFactory valueFactory, Value... argValues) + throws QueryEvaluationException { + return new LookAheadIteration<>() { + private final CloseableIteration> iter = func + .evaluate(valueFactory, argValues); + + @Override + public BindingSet getNextElement() throws QueryEvaluationException { + QueryBindingSet resultBindings = null; + while (resultBindings == null && iter.hasNext()) { + resultBindings = new QueryBindingSet(bindings); + List values = iter.next(); + if (resultVars.size() != values.size()) { + throw new QueryEvaluationException("Incorrect number of result vars: require " + values.size()); + } + for (int i = 0; i < values.size(); i++) { + Value result = values.get(i); + Var resultVar = resultVars.get(i); + Value varValue = resultVar.getValue(); + String varName = resultVar.getName(); + Value boundValue = bindings.getValue(varName); + if ((varValue == null || result.equals(varValue)) + && (boundValue == null || result.equals(boundValue))) { + if (boundValue == null) { // if not already present + resultBindings.addBinding(varName, result); + } + } else { + resultBindings = null; + break; + } + } + } + return resultBindings; + } + + @Override + protected void handleClose() throws QueryEvaluationException { + iter.close(); + } + }; + } + @Deprecated(forRemoval = true) - @Override public Value evaluate(Compare node, BindingSet bindings) throws QueryEvaluationException { Value leftVal = evaluate(node.getLeftArg(), bindings); @@ -60,16 +127,6 @@ protected QueryValueEvaluationStep prepare(Compare node, QueryEvaluationContext .valueOf(QueryEvaluationUtil.compare(leftVal, rightVal, node.getOperator(), false)), context); } - @Deprecated(forRemoval = true) - @Override - public Value evaluate(MathExpr node, BindingSet bindings) - throws QueryEvaluationException { - Value leftVal = evaluate(node.getLeftArg(), bindings); - Value rightVal = evaluate(node.getRightArg(), bindings); - - return mathOperationApplier(node, leftVal, rightVal); - } - private Value mathOperationApplier(MathExpr node, Value leftVal, Value rightVal) { if (leftVal.isLiteral() && rightVal.isLiteral()) { return XMLDatatypeMathUtil.compute((Literal) leftVal, (Literal) rightVal, node.getOperator()); @@ -83,4 +140,51 @@ protected QueryValueEvaluationStep prepare(MathExpr node, QueryEvaluationContext return supplyBinaryValueEvaluation(node, (leftVal, rightVal) -> mathOperationApplier(node, leftVal, rightVal), context); } + + @Deprecated(forRemoval = true) + @Override + public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) + throws QueryEvaluationException { + if (expr instanceof TupleFunctionCall) { + return precompile(expr).evaluate(bindings); + } else { + return super.evaluate(expr, bindings); + } + } + + @Override + public QueryEvaluationStep precompile(TupleExpr expr, QueryEvaluationContext context) + throws QueryEvaluationException { + if (expr instanceof TupleFunctionCall) { + return prepare((TupleFunctionCall) expr, context); + } else { + return super.precompile(expr, context); + } + } + + protected QueryEvaluationStep prepare(TupleFunctionCall expr, QueryEvaluationContext context) + throws QueryEvaluationException { + TupleFunction func = tupleFuncRegistry.get(expr.getURI()) + .orElseThrow(() -> new QueryEvaluationException("Unknown tuple function '" + expr.getURI() + "'")); + + List args = expr.getArgs(); + QueryValueEvaluationStep[] argEpresions = new QueryValueEvaluationStep[args.size()]; + for (int i = 0; i < args.size(); i++) { + argEpresions[i] = precompile(args.get(i), context); + } + + return new QueryEvaluationStep() { + + @Override + public CloseableIteration evaluate(BindingSet bindings) { + Value[] argValues = new Value[args.size()]; + for (int i = 0; i < args.size(); i++) { + argValues[i] = argEpresions[i].evaluate(bindings); + } + + return ExtendedEvaluationStrategy.evaluate(func, expr.getResultVars(), bindings, + tripleSource.getValueFactory(), argValues); + } + }; + } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ExtensionQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ExtensionQueryEvaluationStep.java index 9a1f004e4aa..0603d430e20 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ExtensionQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ExtensionQueryEvaluationStep.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.MutableBindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.iterator.ExtensionIterator; @@ -33,8 +32,8 @@ public final class ExtensionQueryEvaluationStep implements QueryEvaluationStep { } @Override - public CloseableIteration evaluate(BindingSet bs) { - CloseableIteration result; + public CloseableIteration evaluate(BindingSet bs) { + CloseableIteration result; try { result = arg.evaluate(bs); } catch (ValueExprEvaluationException e) { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/FilterOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/FilterOptimizer.java deleted file mode 100644 index 16593f5096f..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/FilterOptimizer.java +++ /dev/null @@ -1,281 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import java.util.Set; - -import org.eclipse.rdf4j.query.algebra.And; -import org.eclipse.rdf4j.query.algebra.Difference; -import org.eclipse.rdf4j.query.algebra.Distinct; -import org.eclipse.rdf4j.query.algebra.EmptySet; -import org.eclipse.rdf4j.query.algebra.Extension; -import org.eclipse.rdf4j.query.algebra.Filter; -import org.eclipse.rdf4j.query.algebra.Intersection; -import org.eclipse.rdf4j.query.algebra.Join; -import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.Order; -import org.eclipse.rdf4j.query.algebra.QueryModelNode; -import org.eclipse.rdf4j.query.algebra.QueryRoot; -import org.eclipse.rdf4j.query.algebra.Reduced; -import org.eclipse.rdf4j.query.algebra.StatementPattern; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.Union; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; -import org.eclipse.rdf4j.query.algebra.helpers.collectors.VarNameCollector; - -/** - * Optimizes a query model by pushing {@link Filter}s as far down in the model tree as possible. - *

- * To make the first optimization succeed more often it splits filters which contains {@link And} conditions. - * - * - * SELECT * WHERE { - * ?s ?p ?o . - * ?s ?p ?o2 . - * FILTER(?o > '2'^^xsd:int && ?o2 < '4'^^xsd:int) - * } - * May be more efficient when decomposed into - * SELECT * WHERE { - * ?s ?p ?o . - * FILTER(?o > '2'^^xsd:int) - * ?s ?p ?o2 . - * FILTER(?o2 < '4'^^xsd:int) - * } - * - *

- * Then it optimizes a query model by merging adjacent {@link Filter}s. e.g. - * SELECT * WHERE { - * ?s ?p ?o . - * FILTER(?o > 2) . - * FILTER(?o < 4) . - * } - * may be merged into - * SELECT * WHERE { - * ?s ?p ?o . - * FILTER(?o > 2 && ?o < 4) . } - * - *

- * This optimization allows for sharing evaluation costs in the future and removes an iterator. This is done as a second - * step to not break the first optimization. In the case that the splitting was done but did not help it is now undone. - * - * @author Arjohn Kampman - * @author Jerven Bolleman - * - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.FilterOptimizer} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class FilterOptimizer extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.FilterOptimizer - implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class FilterFinder extends AbstractQueryModelVisitor { - - protected final TupleExpr tupleExpr; - - public FilterFinder(TupleExpr tupleExpr) { - this.tupleExpr = tupleExpr; - } - - @Override - public void meet(Filter filter) { - super.meet(filter); - FilterRelocator.relocate(filter); - } - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class FilterRelocator extends AbstractQueryModelVisitor { - - public static void relocate(Filter filter) { - filter.visit(new FilterRelocator(filter)); - } - - protected final Filter filter; - - protected final Set filterVars; - - public FilterRelocator(Filter filter) { - this.filter = filter; - filterVars = VarNameCollector.process(filter.getCondition()); - } - - @Override - protected void meetNode(QueryModelNode node) { - // By default, do not traverse - assert node instanceof TupleExpr; - relocate(filter, (TupleExpr) node); - } - - @Override - public void meet(Join join) { - if (join.getLeftArg().getBindingNames().containsAll(filterVars)) { - // All required vars are bound by the left expr - join.getLeftArg().visit(this); - } else if (join.getRightArg().getBindingNames().containsAll(filterVars)) { - // All required vars are bound by the right expr - join.getRightArg().visit(this); - } else { - relocate(filter, join); - } - } - - @Override - public void meet(StatementPattern sp) { - if (sp.getBindingNames().containsAll(filterVars)) { - // All required vars are bound by the left expr - relocate(filter, sp); - } - } - - @Override - public void meet(LeftJoin leftJoin) { - if (leftJoin.getLeftArg().getBindingNames().containsAll(filterVars)) { - leftJoin.getLeftArg().visit(this); - } else { - relocate(filter, leftJoin); - } - } - - @Override - public void meet(Union union) { - Filter clone = new Filter(); - clone.setCondition(filter.getCondition().clone()); - - relocate(filter, union.getLeftArg()); - relocate(clone, union.getRightArg()); - - FilterRelocator.relocate(filter); - FilterRelocator.relocate(clone); - } - - @Override - public void meet(Difference node) { - Filter clone = new Filter(); - clone.setCondition(filter.getCondition().clone()); - - relocate(filter, node.getLeftArg()); - relocate(clone, node.getRightArg()); - - FilterRelocator.relocate(filter); - FilterRelocator.relocate(clone); - } - - @Override - public void meet(Intersection node) { - Filter clone = new Filter(); - clone.setCondition(filter.getCondition().clone()); - - relocate(filter, node.getLeftArg()); - relocate(clone, node.getRightArg()); - - FilterRelocator.relocate(filter); - FilterRelocator.relocate(clone); - } - - @Override - public void meet(Extension node) { - if (node.getArg().getBindingNames().containsAll(filterVars)) { - node.getArg().visit(this); - } else { - relocate(filter, node); - } - } - - @Override - public void meet(EmptySet node) { - if (filter.getParentNode() != null) { - // Remove filter from its original location - filter.replaceWith(filter.getArg()); - } - } - - @Override - public void meet(Filter filter) { - // Filters are commutative - filter.getArg().visit(this); - } - - @Override - public void meet(Distinct node) { - node.getArg().visit(this); - } - - @Override - public void meet(Order node) { - node.getArg().visit(this); - } - - @Override - public void meet(QueryRoot node) { - node.getArg().visit(this); - } - - @Override - public void meet(Reduced node) { - node.getArg().visit(this); - } - - protected void relocate(Filter filter, TupleExpr newFilterArg) { - if (filter.getArg() != newFilterArg) { - if (filter.getParentNode() != null) { - // Remove filter from its original location - filter.replaceWith(filter.getArg()); - } - - // Insert filter at the new location - newFilterArg.replaceWith(filter); - filter.setArg(newFilterArg); - } - } - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class MergeFilterFinder extends AbstractQueryModelVisitor { - - @Override - public void meet(Filter filter) { - super.meet(filter); - if (filter.getParentNode() instanceof Filter) { - - Filter parentFilter = (Filter) filter.getParentNode(); - QueryModelNode grandParent = parentFilter.getParentNode(); - ValueExpr parentCondition = parentFilter.getCondition(); - ValueExpr thisCondition = filter.getCondition(); - And merge = new And(parentCondition, thisCondition); - filter.setCondition(merge); - grandParent.replaceChildNode(parentFilter, filter); - } - } - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class DeMergeFilterFinder extends AbstractQueryModelVisitor { - - @Override - public void meet(Filter filter) { - super.meet(filter); - if (filter.getCondition() instanceof And) { - - And and = (And) filter.getCondition(); - ValueExpr left = and.getLeftArg(); - ValueExpr right = and.getRightArg(); - filter.setCondition(left); - Filter newFilter = new Filter(filter.getArg(), right); - filter.replaceChildNode(filter.getArg(), newFilter); - meet(newFilter); - meet(filter); - } - } - } - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/IterativeEvaluationOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/IterativeEvaluationOptimizer.java deleted file mode 100644 index 6648359269d..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/IterativeEvaluationOptimizer.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.algebra.Join; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.Union; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; - -/** - * @author Arjohn Kampman - * - * @deprecated since 4.1.0. Use - * {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.IterativeEvaluationOptimizer} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class IterativeEvaluationOptimizer extends - org.eclipse.rdf4j.query.algebra.evaluation.optimizer.IterativeEvaluationOptimizer implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class IEOVisitor extends AbstractQueryModelVisitor { - - @Override - public void meet(Union union) { - super.meet(union); - - TupleExpr leftArg = union.getLeftArg(); - TupleExpr rightArg = union.getRightArg(); - - if (leftArg instanceof Join && rightArg instanceof Join) { - Join leftJoinArg = (Join) leftArg; - Join rightJoin = (Join) rightArg; - - if (leftJoinArg.getLeftArg().equals(rightJoin.getLeftArg())) { - // factor out the left-most join argument - Join newJoin = new Join(); - union.replaceWith(newJoin); - newJoin.setLeftArg(leftJoinArg.getLeftArg()); - newJoin.setRightArg(union); - union.setLeftArg(leftJoinArg.getRightArg()); - union.setRightArg(rightJoin.getRightArg()); - - union.visit(this); - } - } - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/OrderLimitOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/OrderLimitOptimizer.java deleted file mode 100644 index a6d6a574656..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/OrderLimitOptimizer.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.algebra.Distinct; -import org.eclipse.rdf4j.query.algebra.Order; -import org.eclipse.rdf4j.query.algebra.OrderElem; -import org.eclipse.rdf4j.query.algebra.Projection; -import org.eclipse.rdf4j.query.algebra.ProjectionElem; -import org.eclipse.rdf4j.query.algebra.QueryModelNode; -import org.eclipse.rdf4j.query.algebra.Reduced; -import org.eclipse.rdf4j.query.algebra.Var; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; - -/** - * Moves the Order node above the Projection when variables are projected. - * - * @author James Leigh - * - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.OrderLimitOptimizer} - * instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class OrderLimitOptimizer extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.OrderLimitOptimizer - implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class OrderOptimizer extends AbstractQueryModelVisitor { - - private boolean variablesProjected = true; - - private Projection projection; - - @Override - public void meet(Projection node) { - projection = node; - node.getArg().visit(this); - projection = null; - } - - @Override - public void meet(Order node) { - for (OrderElem e : node.getElements()) { - e.visit(this); - } - if (variablesProjected) { - QueryModelNode parent = node.getParentNode(); - if (projection == parent) { - node.replaceWith(node.getArg().clone()); - node.setArg(projection.clone()); - Order replacement = node.clone(); - projection.replaceWith(replacement); - QueryModelNode distinct = replacement.getParentNode(); - if (distinct instanceof Distinct) { - distinct.replaceWith(new Reduced(replacement.clone())); - } - } - } - } - - @Override - public void meet(Var node) { - if (projection != null) { - boolean projected = false; - for (ProjectionElem e : projection.getProjectionElemList().getElements()) { - if (node.getName().equals(e.getName())) { - projected = true; - break; - } - } - if (!projected) { - variablesProjected = false; - } - } - } - - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ParentReferenceCleaner.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ParentReferenceCleaner.java deleted file mode 100644 index c6c1b9ba07a..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ParentReferenceCleaner.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.algebra.QueryModelNode; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; - -/** - * Cleans up {@link QueryModelNode#getParentNode()} references that have become inconsistent with the actual algebra - * tree structure due to optimization operations. Typically used at the very end of the optimization pipeline. - * - * @author Jeen Broekstra - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ParentReferenceCleaner} - * instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class ParentReferenceCleaner extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ParentReferenceCleaner - implements QueryOptimizer { - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ProjectionRemovalOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ProjectionRemovalOptimizer.java deleted file mode 100644 index 45f6aa3da08..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ProjectionRemovalOptimizer.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; - -/** - * If a projection node in the algebra does not contribute or change the results it can be removed from the tree. - *

- * For example - * SELECT ?s ?p ?o - * WHERE {?s ?p ?o } - * Does not need a projection as the inner statement pattern returns the same result. - *

- * While - * * SELECT ?s ?p - * WHERE {?s ?p ?o } - * Does as the statement pattern has one more variable in use than the projection. - *

- * Note: this optimiser should run after optimisations ran that depend on Projections. e.g. - * - * @author Jerven Bolleman - * @see UnionScopeChangeOptimizer - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ProjectionRemovalOptimizer} - * instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class ProjectionRemovalOptimizer extends - org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ProjectionRemovalOptimizer implements QueryOptimizer { -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryEvaluationContext.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryEvaluationContext.java index e26cd5a2c3e..6ffb91ef3eb 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryEvaluationContext.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryEvaluationContext.java @@ -123,16 +123,16 @@ default MutableBindingSet createBindingSet() { } default Predicate hasBinding(String variableName) { - return (bs) -> bs.hasBinding(variableName); + return bs -> bs.hasBinding(variableName); } default Function getBinding(String variableName) { - return (bs) -> bs.getBinding(variableName); + return bs -> bs.getBinding(variableName); } default Function getValue(String variableName) { Function getBinding = getBinding(variableName); - return (bs) -> { + return bs -> { Binding binding = getBinding.apply(bs); if (binding == null) { return null; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryJoinOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryJoinOptimizer.java deleted file mode 100644 index 3f31a5b8a27..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryJoinOptimizer.java +++ /dev/null @@ -1,549 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.algebra.BindingSetAssignment; -import org.eclipse.rdf4j.query.algebra.Join; -import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.StatementPattern; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.Var; -import org.eclipse.rdf4j.query.algebra.ZeroLengthPath; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; -import org.eclipse.rdf4j.query.algebra.helpers.StatementPatternCollector; -import org.eclipse.rdf4j.query.algebra.helpers.TupleExprs; - -/** - * A query optimizer that re-orders nested Joins. - * - * @author Arjohn Kampman - * @author James Leigh - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.QueryJoinOptimizer} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class QueryJoinOptimizer extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.QueryJoinOptimizer - implements QueryOptimizer { - - public QueryJoinOptimizer() { - this(new EvaluationStatistics()); - } - - public QueryJoinOptimizer(EvaluationStatistics statistics) { - this(statistics, false); - } - - public QueryJoinOptimizer(EvaluationStatistics statistics, boolean trackResultSize) { - super(statistics, trackResultSize); - } - - public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) { - super.optimize(tupleExpr, dataset, bindings); - } - - /** - * @deprecated This class is protected for historic reasons only, and will be made private in a future major - * release. - */ - @Deprecated - protected class JoinVisitor extends AbstractQueryModelVisitor { - - Set boundVars = new HashSet<>(); - - @Override - public void meet(LeftJoin leftJoin) { - leftJoin.getLeftArg().visit(this); - - Set origBoundVars = boundVars; - try { - boundVars = new HashSet<>(boundVars); - boundVars.addAll(leftJoin.getLeftArg().getBindingNames()); - - leftJoin.getRightArg().visit(this); - } finally { - boundVars = origBoundVars; - } - } - - @Override - public void meet(StatementPattern node) throws RuntimeException { - super.meet(node); - node.setResultSizeEstimate(Math.max(statistics.getCardinality(node), node.getResultSizeEstimate())); - } - - private void optimizePriorityJoin(Set origBoundVars, TupleExpr join) { - - Set saveBoundVars = boundVars; - try { - boundVars = new HashSet<>(origBoundVars); - join.visit(this); - } finally { - boundVars = saveBoundVars; - } - } - - @Override - public void meet(Join node) { - - Set origBoundVars = boundVars; - try { - boundVars = new HashSet<>(boundVars); - - // Recursively get the join arguments - List joinArgs = getJoinArgs(node, new ArrayList<>()); - - // Reorder the (recursive) join arguments to a more optimal sequence - List orderedJoinArgs = new ArrayList<>(joinArgs.size()); - - // Reorder the subselects and extensions to a more optimal sequence - List priorityArgs = new ArrayList<>(joinArgs.size()); - - // get all extensions (BIND clause) - List orderedExtensions = getExtensions(joinArgs); - joinArgs.removeAll(orderedExtensions); - priorityArgs.addAll(orderedExtensions); - - // get all subselects and order them - List orderedSubselects = reorderSubselects(getSubSelects(joinArgs)); - joinArgs.removeAll(orderedSubselects); - priorityArgs.addAll(orderedSubselects); - - // We order all remaining join arguments based on cardinality and - // variable frequency statistics - if (joinArgs.size() > 0) { - // Build maps of cardinalities and vars per tuple expression - Map cardinalityMap = new HashMap<>(); - Map> varsMap = new HashMap<>(); - - for (TupleExpr tupleExpr : joinArgs) { - double cardinality = statistics.getCardinality(tupleExpr); - tupleExpr.setResultSizeEstimate(Math.max(cardinality, tupleExpr.getResultSizeEstimate())); - cardinalityMap.put(tupleExpr, cardinality); - if (tupleExpr instanceof ZeroLengthPath) { - varsMap.put(tupleExpr, ((ZeroLengthPath) tupleExpr).getVarList()); - } else { - varsMap.put(tupleExpr, getStatementPatternVars(tupleExpr)); - } - } - - // Build map of var frequences - Map varFreqMap = new HashMap<>(); - for (List varList : varsMap.values()) { - getVarFreqMap(varList, varFreqMap); - } - - // order all other join arguments based on available statistics - while (!joinArgs.isEmpty()) { - TupleExpr tupleExpr = selectNextTupleExpr(joinArgs, cardinalityMap, varsMap, varFreqMap, - boundVars - ); - - joinArgs.remove(tupleExpr); - orderedJoinArgs.add(tupleExpr); - - // Recursively optimize join arguments - tupleExpr.visit(this); - - boundVars.addAll(tupleExpr.getBindingNames()); - } - } - - // Build new join hierarchy - TupleExpr priorityJoins = null; - if (priorityArgs.size() > 0) { - priorityJoins = priorityArgs.get(0); - for (int i = 1; i < priorityArgs.size(); i++) { - priorityJoins = new Join(priorityJoins, priorityArgs.get(i)); - } - } - - if (orderedJoinArgs.size() > 0) { - // Note: generated hierarchy is right-recursive to help the - // IterativeEvaluationOptimizer to factor out the left-most join - // argument - int i = orderedJoinArgs.size() - 1; - TupleExpr replacement = orderedJoinArgs.get(i); - for (i--; i >= 0; i--) { - replacement = new Join(orderedJoinArgs.get(i), replacement); - } - - if (priorityJoins != null) { - replacement = new Join(priorityJoins, replacement); - } - - // Replace old join hierarchy - node.replaceWith(replacement); - - // we optimize after the replacement call above in case the optimize call below - // recurses back into this function and we need all the node's parent/child pointers - // set up correctly for replacement to work on subsequent calls - if (priorityJoins != null) { - optimizePriorityJoin(origBoundVars, priorityJoins); - } - - } else { - // only subselect/priority joins involved in this query. - node.replaceWith(priorityJoins); - } - } finally { - boundVars = origBoundVars; - } - } - - protected > L getJoinArgs(TupleExpr tupleExpr, L joinArgs) { - if (tupleExpr instanceof Join) { - Join join = (Join) tupleExpr; - getJoinArgs(join.getLeftArg(), joinArgs); - getJoinArgs(join.getRightArg(), joinArgs); - } else { - joinArgs.add(tupleExpr); - } - - return joinArgs; - } - - protected List getStatementPatternVars(TupleExpr tupleExpr) { - List stPatterns = StatementPatternCollector.process(tupleExpr); - List varList = new ArrayList<>(stPatterns.size() * 4); - for (StatementPattern sp : stPatterns) { - sp.getVars(varList); - } - return varList; - } - - protected > M getVarFreqMap(List varList, M varFreqMap) { - for (Var var : varList) { - Integer freq = varFreqMap.get(var); - freq = (freq == null) ? 1 : freq + 1; - varFreqMap.put(var, freq); - } - return varFreqMap; - } - - protected List getExtensions(List expressions) { - List extensions = new ArrayList<>(); - for (TupleExpr expr : expressions) { - if (TupleExprs.containsExtension(expr)) { - extensions.add(expr); - } - } - return extensions; - } - - protected List getSubSelects(List expressions) { - List subselects = new ArrayList<>(); - - for (TupleExpr expr : expressions) { - if (TupleExprs.containsSubquery(expr)) { - subselects.add(expr); - } - } - return subselects; - } - - /** - * Determines an optimal ordering of subselect join arguments, based on variable bindings. An ordering is - * considered optimal if for each consecutive element it holds that first of all its shared variables with all - * previous elements is maximized, and second, the union of all its variables with all previous elements is - * maximized. - *

- * Example: reordering - * - *

-		 *   [f] [a b c] [e f] [a d] [b e]
-		 * 
- *

- * should result in: - * - *

-		 *   [a b c] [a d] [b e] [e f] [f]
-		 * 
- * - * @param subselects the original ordering of expressions - * @return the optimized ordering of expressions - */ - protected List reorderSubselects(List subselects) { - - if (subselects.size() == 1) { - return subselects; - } - - List result = new ArrayList<>(); - if (subselects == null || subselects.isEmpty()) { - return result; - } - - // Step 1: determine size of join for each pair of arguments - HashMap> joinSizes = new HashMap<>(); - - int maxJoinSize = 0; - for (int i = 0; i < subselects.size(); i++) { - TupleExpr firstArg = subselects.get(i); - for (int j = i + 1; j < subselects.size(); j++) { - TupleExpr secondArg = subselects.get(j); - - Set firstArgBindingNames = firstArg.getBindingNames(); - Set secondArgBindingNames = secondArg.getBindingNames(); - int joinSize = getJoinSize(secondArgBindingNames, firstArgBindingNames); - - if (joinSize > maxJoinSize) { - maxJoinSize = joinSize; - } - - List l; - - if (joinSizes.containsKey(joinSize)) { - l = joinSizes.get(joinSize); - } else { - l = new ArrayList<>(); - } - TupleExpr[] tupleTuple = new TupleExpr[] { firstArg, secondArg }; - l.add(tupleTuple); - joinSizes.put(joinSize, l); - } - } - - // Step 2: find the first two elements for the ordered list by - // selecting the pair with first of all, - // the highest join size, and second, the highest union size. - - TupleExpr[] maxUnionTupleTuple = null; - int currentUnionSize = -1; - - // get a list of all argument pairs with the maximum join size - List list = joinSizes.get(maxJoinSize); - - // select the pair that has the highest union size. - for (TupleExpr[] tupleTuple : list) { - Set names = tupleTuple[0].getBindingNames(); - names.addAll(tupleTuple[1].getBindingNames()); - int unionSize = names.size(); - - if (unionSize > currentUnionSize) { - maxUnionTupleTuple = tupleTuple; - currentUnionSize = unionSize; - } - } - - // add the pair to the result list. - result.add(maxUnionTupleTuple[0]); - result.add(maxUnionTupleTuple[1]); - - // Step 3: sort the rest of the list by selecting and adding an element - // at a time. - while (result.size() < subselects.size()) { - result.add(getNextSubselect(result, subselects)); - } - - return result; - } - - private TupleExpr getNextSubselect(List currentList, List joinArgs) { - - // determine union of names of all elements currently in the list: this - // corresponds to the projection resulting from joining all these - // elements. - Set currentListNames = new HashSet<>(); - for (TupleExpr expr : currentList) { - currentListNames.addAll(expr.getBindingNames()); - } - - // select the next argument from the list, by checking that it has, - // first, the highest join size with the current list, and second, the - // highest union size. - TupleExpr selected = null; - int currentUnionSize = -1; - int currentJoinSize = -1; - for (TupleExpr candidate : joinArgs) { - if (!currentList.contains(candidate)) { - Set names = candidate.getBindingNames(); - int joinSize = getJoinSize(currentListNames, names); - - Set candidateBindingNames = candidate.getBindingNames(); - int unionSize = getUnionSize(currentListNames, candidateBindingNames); - - if (joinSize > currentJoinSize) { - selected = candidate; - currentJoinSize = joinSize; - currentUnionSize = unionSize; - } else if (joinSize == currentJoinSize) { - if (unionSize > currentUnionSize) { - selected = candidate; - currentJoinSize = joinSize; - currentUnionSize = unionSize; - } - } - } - } - - return selected; - } - - /** - * Selects from a list of tuple expressions the next tuple expression that should be evaluated. This method - * selects the tuple expression with highest number of bound variables, preferring variables that have been - * bound in other tuple expressions over variables with a fixed value. - */ - protected TupleExpr selectNextTupleExpr( - List expressions, Map cardinalityMap, - Map> varsMap, Map varFreqMap, Set boundVars - ) { - TupleExpr result = null; - double lowestCost = Double.POSITIVE_INFINITY; - - for (TupleExpr tupleExpr : expressions) { - // Calculate a score for this tuple expression - double cost = getTupleExprCost(tupleExpr, cardinalityMap, varsMap, varFreqMap, - boundVars - ); - - if (cost < lowestCost || result == null) { - // More specific path expression found - lowestCost = cost; - result = tupleExpr; - } - } - - result.setCostEstimate(lowestCost); - - return result; - } - - @Deprecated - protected double getTupleExprCardinality( - TupleExpr tupleExpr, Map cardinalityMap, - Map> varsMap, Map varFreqMap, Set boundVars - ) { - return getTupleExprCost(tupleExpr, cardinalityMap, varsMap, varFreqMap, boundVars); - } - - protected double getTupleExprCost( - TupleExpr tupleExpr, Map cardinalityMap, - Map> varsMap, Map varFreqMap, Set boundVars - ) { - - double cost = cardinalityMap.get(tupleExpr); - - List vars = varsMap.get(tupleExpr); - - // Compensate for variables that are bound earlier in the evaluation - List unboundVars = getUnboundVars(vars); - List constantVars = getConstantVars(vars); - - int nonConstantVarCount = vars.size() - constantVars.size(); - - if (nonConstantVarCount > 0) { - double exp = (double) unboundVars.size() / nonConstantVarCount; - cost = Math.pow(cost, exp); - } - - if (unboundVars.isEmpty()) { - // Prefer patterns with more bound vars - if (nonConstantVarCount > 0) { - cost /= nonConstantVarCount; - } - } else { - // Prefer patterns that bind variables from other tuple expressions - int foreignVarFreq = getForeignVarFreq(unboundVars, varFreqMap); - if (foreignVarFreq > 0) { - cost /= 1 + foreignVarFreq; - } - } - - // BindingSetAssignment has a typical constant cost. This cost is not based on statistics so is much more - // reliable. If the BindingSetAssignment binds to any of the other variables in the other tuple expressions - // to choose from, then the cost of the BindingSetAssignment should be set to 0 since it will always limit - // the upper bound of any other costs. This way the BindingSetAssignment will be chosen as the left - // argument. - if (tupleExpr instanceof BindingSetAssignment) { - - Set varsUsedInOtherExpressions = varFreqMap.keySet(); - - for (String assuredBindingName : tupleExpr.getAssuredBindingNames()) { - if (varsUsedInOtherExpressions.contains(new Var(assuredBindingName))) { - cost = 0; - break; - } - } - } - - return cost; - } - - protected List getConstantVars(Iterable vars) { - List constantVars = new ArrayList<>(); - - for (Var var : vars) { - if (var.hasValue()) { - constantVars.add(var); - } - } - - return constantVars; - } - - protected List getUnboundVars(Iterable vars) { - List unboundVars = new ArrayList<>(); - - for (Var var : vars) { - if (!var.hasValue() && !this.boundVars.contains(var.getName())) { - unboundVars.add(var); - } - } - - return unboundVars; - } - - protected int getForeignVarFreq(List ownUnboundVars, Map varFreqMap) { - int result = 0; - - Map ownFreqMap = getVarFreqMap(ownUnboundVars, new HashMap<>()); - - for (Map.Entry entry : ownFreqMap.entrySet()) { - Var var = entry.getKey(); - int ownFreq = entry.getValue(); - result += varFreqMap.get(var) - ownFreq; - } - - return result; - } - } - - private static int getUnionSize(Set currentListNames, Set candidateBindingNames) { - int count = 0; - for (String n : currentListNames) { - if (!candidateBindingNames.contains(n)) { - count++; - } - } - return candidateBindingNames.size() + count; - } - - private static int getJoinSize(Set currentListNames, Set names) { - int count = 0; - for (String name : names) { - if (currentListNames.contains(name)) { - count++; - } - } - return count; - } - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelNormalizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelNormalizer.java deleted file mode 100644 index 388f76e5a6c..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelNormalizer.java +++ /dev/null @@ -1,281 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import java.util.HashSet; -import java.util.Set; - -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.algebra.And; -import org.eclipse.rdf4j.query.algebra.Difference; -import org.eclipse.rdf4j.query.algebra.EmptySet; -import org.eclipse.rdf4j.query.algebra.Filter; -import org.eclipse.rdf4j.query.algebra.Intersection; -import org.eclipse.rdf4j.query.algebra.Join; -import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.Or; -import org.eclipse.rdf4j.query.algebra.QueryModelNode; -import org.eclipse.rdf4j.query.algebra.SingletonSet; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.UnaryTupleOperator; -import org.eclipse.rdf4j.query.algebra.Union; -import org.eclipse.rdf4j.query.algebra.ValueConstant; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; -import org.eclipse.rdf4j.query.algebra.helpers.collectors.VarNameCollector; - -/** - * A query optimizer that (partially) normalizes query models to a canonical form. Note: this implementation does not - * yet cover all query node types. - * - * @author Arjohn Kampman - * @deprecated since 4.1.0. Use - * {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.QueryModelNormalizerOptimizer} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class QueryModelNormalizer extends AbstractQueryModelVisitor implements QueryOptimizer { - - public QueryModelNormalizer() { - } - - @Override - public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) { - tupleExpr.visit(this); - } - - @Override - public void meet(Join join) { - super.meet(join); - - TupleExpr leftArg = join.getLeftArg(); - TupleExpr rightArg = join.getRightArg(); - - if (leftArg instanceof EmptySet || rightArg instanceof EmptySet) { - join.replaceWith(new EmptySet()); - } else if (leftArg instanceof SingletonSet) { - join.replaceWith(rightArg); - } else if (rightArg instanceof SingletonSet) { - join.replaceWith(leftArg); - } else if (leftArg instanceof Union) { - // sort unions above joins - Union union = (Union) leftArg; - Join leftJoin = new Join(union.getLeftArg(), rightArg.clone()); - Join rightJoin = new Join(union.getRightArg(), rightArg.clone()); - Union newUnion = new Union(leftJoin, rightJoin); - newUnion.setVariableScopeChange(union.isVariableScopeChange()); - join.replaceWith(newUnion); - newUnion.visit(this); - } else if (rightArg instanceof Union) { - // sort unions above joins - Union union = (Union) rightArg; - Join leftJoin = new Join(leftArg.clone(), union.getLeftArg()); - Join rightJoin = new Join(leftArg.clone(), union.getRightArg()); - Union newUnion = new Union(leftJoin, rightJoin); - newUnion.setVariableScopeChange(union.isVariableScopeChange()); - join.replaceWith(newUnion); - newUnion.visit(this); - } else if (leftArg instanceof LeftJoin && isWellDesigned(((LeftJoin) leftArg))) { - // sort left join above normal joins - LeftJoin leftJoin = (LeftJoin) leftArg; - join.replaceWith(leftJoin); - join.setLeftArg(leftJoin.getLeftArg()); - leftJoin.setLeftArg(join); - leftJoin.visit(this); - } else if (rightArg instanceof LeftJoin && isWellDesigned(((LeftJoin) rightArg))) { - // sort left join above normal joins - LeftJoin leftJoin = (LeftJoin) rightArg; - join.replaceWith(leftJoin); - join.setRightArg(leftJoin.getLeftArg()); - leftJoin.setLeftArg(join); - leftJoin.visit(this); - } - } - - @Override - public void meet(LeftJoin leftJoin) { - super.meet(leftJoin); - - TupleExpr leftArg = leftJoin.getLeftArg(); - TupleExpr rightArg = leftJoin.getRightArg(); - ValueExpr condition = leftJoin.getCondition(); - - if (leftArg instanceof EmptySet) { - leftJoin.replaceWith(leftArg); - } else if (rightArg instanceof EmptySet) { - leftJoin.replaceWith(leftArg); - } else if (rightArg instanceof SingletonSet) { - leftJoin.replaceWith(leftArg); - } else if (condition instanceof ValueConstant) { - boolean conditionValue = QueryEvaluationUtility - .getEffectiveBooleanValue(((ValueConstant) condition).getValue()) - .orElse(false); - - if (!conditionValue) { - // Constraint is always false - leftJoin.replaceWith(leftArg); - } else { - leftJoin.setCondition(null); - } - } - } - - @Override - public void meet(Union union) { - super.meet(union); - - TupleExpr leftArg = union.getLeftArg(); - TupleExpr rightArg = union.getRightArg(); - - if (leftArg instanceof EmptySet) { - union.replaceWith(rightArg); - } else if (rightArg instanceof EmptySet) { - union.replaceWith(leftArg); - } - } - - @Override - public void meet(Difference difference) { - super.meet(difference); - - TupleExpr leftArg = difference.getLeftArg(); - TupleExpr rightArg = difference.getRightArg(); - - if (leftArg instanceof EmptySet) { - difference.replaceWith(leftArg); - } else if (rightArg instanceof EmptySet) { - difference.replaceWith(leftArg); - } else if (leftArg instanceof SingletonSet && rightArg instanceof SingletonSet) { - difference.replaceWith(new EmptySet()); - } - } - - @Override - public void meet(Intersection intersection) { - super.meet(intersection); - - TupleExpr leftArg = intersection.getLeftArg(); - TupleExpr rightArg = intersection.getRightArg(); - - if (leftArg instanceof EmptySet || rightArg instanceof EmptySet) { - intersection.replaceWith(new EmptySet()); - } - } - - @Override - protected void meetUnaryTupleOperator(UnaryTupleOperator node) { - super.meetUnaryTupleOperator(node); - - if (node.getArg() instanceof EmptySet) { - node.replaceWith(node.getArg()); - } - } - - @Override - public void meet(Filter node) { - super.meet(node); - - TupleExpr arg = node.getArg(); - ValueExpr condition = node.getCondition(); - - if (arg instanceof EmptySet) { - // see #meetUnaryTupleOperator - } else if (condition instanceof ValueConstant) { - boolean conditionValue = QueryEvaluationUtility - .getEffectiveBooleanValue(((ValueConstant) condition).getValue()) - .orElse(false); - - if (!conditionValue) { - // Constraint is always false - node.replaceWith(new EmptySet()); - } else { - node.replaceWith(arg); - } - } - } - - @Override - public void meet(Or or) { - super.meet(or); - - if (or.getLeftArg().equals(or.getRightArg())) { - or.replaceWith(or.getLeftArg()); - } - } - - @Override - public void meet(And and) { - super.meet(and); - - if (and.getLeftArg().equals(and.getRightArg())) { - and.replaceWith(and.getLeftArg()); - } - } - - /** - * Checks whether the left join is "well designed" as defined in section 4.2 of "Semantics and Complexity of - * SPARQL", 2006, Jorge Pérez et al. - */ - private boolean isWellDesigned(LeftJoin leftJoin) { - VarNameCollector optionalVarCollector = new VarNameCollector(); - leftJoin.getRightArg().visit(optionalVarCollector); - if (leftJoin.hasCondition()) { - leftJoin.getCondition().visit(optionalVarCollector); - } - - Set problemVars = optionalVarCollector.getVarNames(); - problemVars.removeAll(leftJoin.getLeftArg().getBindingNames()); - - if (problemVars.isEmpty()) { - return true; - } - - // If any of the problematic variables are bound in the parent - // expression then the left join is not well designed - BindingCollector bindingCollector = new BindingCollector(); - QueryModelNode node = leftJoin; - QueryModelNode parent; - while ((parent = node.getParentNode()) != null) { - bindingCollector.setNodeToIgnore(node); - parent.visitChildren(bindingCollector); - node = parent; - } - - problemVars.retainAll(bindingCollector.getBindingNames()); - - return problemVars.isEmpty(); - } - - private static class BindingCollector extends AbstractQueryModelVisitor { - - private QueryModelNode nodeToIgnore; - - private final Set bindingNames = new HashSet<>(); - - public void setNodeToIgnore(QueryModelNode node) { - this.nodeToIgnore = node; - } - - public Set getBindingNames() { - return bindingNames; - } - - @Override - protected void meetNode(QueryModelNode node) { - if (node instanceof TupleExpr && node != nodeToIgnore) { - TupleExpr tupleExpr = (TupleExpr) node; - bindingNames.addAll(tupleExpr.getBindingNames()); - } - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelPruner.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelPruner.java deleted file mode 100644 index 84412b95917..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelPruner.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.algebra.Difference; -import org.eclipse.rdf4j.query.algebra.EmptySet; -import org.eclipse.rdf4j.query.algebra.Intersection; -import org.eclipse.rdf4j.query.algebra.Join; -import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.SingletonSet; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.Union; -import org.eclipse.rdf4j.query.algebra.ValueConstant; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; - -/** - * A query optimizer that prunes query model trees by removing superfluous parts and/or by reducing complex parts with - * simpler parts. - * - * @author Arjohn Kampman - * @deprecated Replaced by {@link QueryModelNormalizer}. - */ -@Deprecated -public class QueryModelPruner implements QueryOptimizer { - - public QueryModelPruner() { - } - - /** - * Applies generally applicable optimizations: path expressions are sorted from more to less specific. - * - * @param tupleExpr - */ - @Override - public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) { - tupleExpr.visit(new TreeSanitizer()); - } - - protected static class TreeSanitizer extends AbstractQueryModelVisitor { - - @Override - public void meet(Join join) { - super.meet(join); - - TupleExpr leftArg = join.getLeftArg(); - TupleExpr rightArg = join.getRightArg(); - - if (leftArg instanceof EmptySet || rightArg instanceof EmptySet) { - join.replaceWith(new EmptySet()); - } else if (leftArg instanceof SingletonSet) { - join.replaceWith(rightArg); - } else if (rightArg instanceof SingletonSet) { - join.replaceWith(leftArg); - } - } - - @Override - public void meet(LeftJoin leftJoin) { - super.meet(leftJoin); - - TupleExpr leftArg = leftJoin.getLeftArg(); - TupleExpr rightArg = leftJoin.getRightArg(); - ValueExpr condition = leftJoin.getCondition(); - - if (leftArg instanceof EmptySet) { - leftJoin.replaceWith(leftArg); - } else if (rightArg instanceof EmptySet) { - leftJoin.replaceWith(leftArg); - } else if (rightArg instanceof SingletonSet) { - leftJoin.replaceWith(leftArg); - } else if (condition instanceof ValueConstant) { - boolean conditionValue = QueryEvaluationUtility - .getEffectiveBooleanValue(((ValueConstant) condition).getValue()) - .orElse(false); - - if (!conditionValue) { - // Constraint is always false - leftJoin.replaceWith(leftArg); - } else { - leftJoin.setCondition(null); - } - } - } - - @Override - public void meet(Union union) { - super.meet(union); - - TupleExpr leftArg = union.getLeftArg(); - TupleExpr rightArg = union.getRightArg(); - - if (leftArg instanceof EmptySet) { - union.replaceWith(rightArg); - } else if (rightArg instanceof EmptySet) { - union.replaceWith(leftArg); - } else if (leftArg instanceof SingletonSet && rightArg instanceof SingletonSet) { - union.replaceWith(leftArg); - } - } - - @Override - public void meet(Difference difference) { - super.meet(difference); - - TupleExpr leftArg = difference.getLeftArg(); - TupleExpr rightArg = difference.getRightArg(); - - if (leftArg instanceof EmptySet) { - difference.replaceWith(leftArg); - } else if (rightArg instanceof EmptySet) { - difference.replaceWith(leftArg); - } else if (leftArg instanceof SingletonSet && rightArg instanceof SingletonSet) { - difference.replaceWith(new EmptySet()); - } - } - - @Override - public void meet(Intersection intersection) { - super.meet(intersection); - - TupleExpr leftArg = intersection.getLeftArg(); - TupleExpr rightArg = intersection.getRightArg(); - - if (leftArg instanceof EmptySet || rightArg instanceof EmptySet) { - intersection.replaceWith(new EmptySet()); - } - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/RegexAsStringFunctionOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/RegexAsStringFunctionOptimizer.java deleted file mode 100644 index e9a71ef0df0..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/RegexAsStringFunctionOptimizer.java +++ /dev/null @@ -1,111 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.vocabulary.FN; -import org.eclipse.rdf4j.query.algebra.Compare; -import org.eclipse.rdf4j.query.algebra.FunctionCall; -import org.eclipse.rdf4j.query.algebra.Regex; -import org.eclipse.rdf4j.query.algebra.ValueConstant; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; - -/** - * A query optimizer that replaces REGEX with {@link FunctionCall}s that are equivalent operators - * - * @author Jerven Bolleman - * @deprecated since 4.1.0. Use - * {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.RegexAsStringFunctionOptimizer} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class RegexAsStringFunctionOptimizer extends - org.eclipse.rdf4j.query.algebra.evaluation.optimizer.RegexAsStringFunctionOptimizer implements QueryOptimizer { - - private final ValueFactory factory; - - public RegexAsStringFunctionOptimizer(ValueFactory vf) { - super(vf); - this.factory = vf; - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected class RegexAsStringFunctionVisitor extends AbstractQueryModelVisitor { - - @Override - public void meet(Regex node) { - final ValueExpr flagsArg = node.getFlagsArg(); - if (flagsArg == null || flagsArg.toString().isEmpty()) { - // if we have no flags then we can not be in case insensitive mode - if (node.getPatternArg() instanceof ValueConstant) { - ValueConstant vc = (ValueConstant) node.getPatternArg(); - String regex = vc.getValue().stringValue(); - final boolean anchoredAtStart = regex.startsWith("^"); - final boolean anchoredAtEnd = regex.endsWith("$"); - - if (anchoredAtStart && anchoredAtEnd) { - equalsCandidate(node, regex); - } else if (anchoredAtStart) { - strstartsCandidate(node, regex); - } else if (anchoredAtEnd) { - strendsCandidate(node, regex); - } else { - containsCandidate(node, regex); - } - } - } - super.meet(node); - } - - private void containsCandidate(Regex node, String potential) { - if (plain(potential)) { - node.replaceWith(new FunctionCall(FN.CONTAINS.stringValue(), node.getArg(), node.getPatternArg())); - } - } - - // If we have one of these chars it is likely to be an real regex. - // If we are willing to peek in a Pattern object we could be sure - // this seems a valid start with no regexes marked as simple strings - private boolean plain(String potential) { - for (int not : new char[] { '?', '*', '+', '{', '|', '\\', '.', '[', ']', '&', '(', ')' }) { - if (potential.indexOf(not) != -1) { - return false; - } - } - return true; - } - - private void strendsCandidate(Regex node, String regex) { - final String potential = regex.substring(0, regex.length() - 1); - if (plain(potential)) { - ValueConstant vc = new ValueConstant(factory.createLiteral(potential)); - node.replaceWith(new FunctionCall(FN.ENDS_WITH.stringValue(), node.getArg(), vc)); - } - } - - private void strstartsCandidate(Regex node, String regex) { - final String potential = regex.substring(1, regex.length()); - if (plain(potential)) { - ValueConstant vc = new ValueConstant(factory.createLiteral(potential)); - node.replaceWith(new FunctionCall(FN.STARTS_WITH.stringValue(), node.getArg(), vc)); - } - } - - private void equalsCandidate(Regex node, String regex) { - final String potential = regex.substring(1, regex.length() - 1); - if (plain(potential)) { - ValueConstant vc = new ValueConstant(factory.createLiteral(potential)); - node.replaceWith(new Compare(node.getArg(), vc, Compare.CompareOp.EQ)); - } - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/SameTermFilterOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/SameTermFilterOptimizer.java deleted file mode 100644 index 07dc28815f6..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/SameTermFilterOptimizer.java +++ /dev/null @@ -1,226 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.query.algebra.ArbitraryLengthPath; -import org.eclipse.rdf4j.query.algebra.BindingSetAssignment; -import org.eclipse.rdf4j.query.algebra.EmptySet; -import org.eclipse.rdf4j.query.algebra.Extension; -import org.eclipse.rdf4j.query.algebra.ExtensionElem; -import org.eclipse.rdf4j.query.algebra.Filter; -import org.eclipse.rdf4j.query.algebra.ProjectionElem; -import org.eclipse.rdf4j.query.algebra.SameTerm; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.ValueConstant; -import org.eclipse.rdf4j.query.algebra.ValueExpr; -import org.eclipse.rdf4j.query.algebra.Var; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; - -/** - * A query optimizer that embeds {@link Filter}s with {@link SameTerm} operators in statement patterns as much as - * possible. Operators like sameTerm(X, Y) are processed by renaming X to Y (or vice versa). Operators like sameTerm(X, - * ) are processed by assigning the URI to all occurring variables with name X. - * - * @author Arjohn Kampman - * @author James Leigh - * - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.SameTermFilterOptimizer} - * instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class SameTermFilterOptimizer - extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.SameTermFilterOptimizer implements QueryOptimizer { - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class SameTermFilterVisitor extends AbstractQueryModelVisitor { - - @Override - public void meet(Filter filter) { - super.meet(filter); - - if (filter.getCondition() instanceof SameTerm) { - // SameTerm applies to the filter's argument - SameTerm sameTerm = (SameTerm) filter.getCondition(); - TupleExpr filterArg = filter.getArg(); - - ValueExpr leftArg = sameTerm.getLeftArg(); - ValueExpr rightArg = sameTerm.getRightArg(); - - // Verify that vars are (potentially) bound by filterArg - Set bindingNames = filterArg.getBindingNames(); - if (isUnboundVar(leftArg, bindingNames) || isUnboundVar(rightArg, bindingNames)) { - // One or both var(s) are unbound, this expression will never - // return any results - filter.replaceWith(new EmptySet()); - return; - } - - Set assuredBindingNames = filterArg.getAssuredBindingNames(); - if (isUnboundVar(leftArg, assuredBindingNames) || isUnboundVar(rightArg, assuredBindingNames)) { - // One or both var(s) are potentially unbound, inlining could - // invalidate the result e.g. in case of left joins - return; - } - - if (leftArg instanceof Var || rightArg instanceof Var) { - if (filterArg instanceof ArbitraryLengthPath && leftArg instanceof Var && rightArg instanceof Var) { - final ArbitraryLengthPath alp = (ArbitraryLengthPath) filterArg; - final List sameTermArgs = Arrays.asList((Var) leftArg, (Var) rightArg); - - if (sameTermArgs.contains(alp.getSubjectVar()) && sameTermArgs.contains(alp.getObjectVar())) { - // SameTerm provides a deferred mapping to allow arbitrary-length property path to produce - // cyclic paths. See SES-1685. - // we can not inline. - return; - } - } - - BindingSetAssignmentCollector collector = new BindingSetAssignmentCollector(); - filterArg.visit(collector); - - for (BindingSetAssignment bsa : collector.getBindingSetAssignments()) { - // check if the VALUES clause / bindingsetassignment contains - // one of the arguments of the sameTerm. - // if so, we can not inline. - Set names = bsa.getAssuredBindingNames(); - if (leftArg instanceof Var) { - if (names.contains(((Var) leftArg).getName())) { - return; - } - } - if (rightArg instanceof Var) { - if (names.contains(((Var) rightArg).getName())) { - return; - } - } - } - } - - Value leftValue = getValue(leftArg); - Value rightValue = getValue(rightArg); - - if (leftValue != null && rightValue != null) { - // ConstantOptimizer should have taken care of this - } else if (leftValue != null && rightArg instanceof Var) { - bindVar((Var) rightArg, leftValue, filter); - } else if (rightValue != null && leftArg instanceof Var) { - bindVar((Var) leftArg, rightValue, filter); - } else if (leftArg instanceof Var && rightArg instanceof Var) { - // Two unbound variables, rename rightArg to leftArg - renameVar((Var) rightArg, (Var) leftArg, filter); - } - } - } - - private boolean isUnboundVar(ValueExpr valueExpr, Set bindingNames) { - if (valueExpr instanceof Var) { - Var var = (Var) valueExpr; - return !var.hasValue() && !bindingNames.contains(var.getName()); - } - return false; - } - - private Value getValue(ValueExpr valueExpr) { - if (valueExpr instanceof ValueConstant) { - return ((ValueConstant) valueExpr).getValue(); - } else if (valueExpr instanceof Var) { - return ((Var) valueExpr).getValue(); - } else { - return null; - } - } - - private void renameVar(Var oldVar, Var newVar, Filter filter) { - filter.getArg().visit(new VarRenamer(oldVar, newVar)); - - // TODO: skip this step if old variable name is not used - // Replace SameTerm-filter with an Extension, the old variable name - // might still be relevant to nodes higher in the tree - Extension extension = new Extension(filter.getArg()); - extension.addElement(new ExtensionElem(new Var(newVar.getName()), oldVar.getName())); - filter.replaceWith(extension); - } - - private void bindVar(Var var, Value value, Filter filter) { - // Set the value on all occurences of the variable - filter.getArg().visit(new VarBinder(var.getName(), value)); - } - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class VarRenamer extends AbstractQueryModelVisitor { - - private final Var oldVar; - - private final Var newVar; - - public VarRenamer(Var oldVar, Var newVar) { - this.oldVar = oldVar; - this.newVar = newVar; - } - - @Override - public void meet(Var var) { - if (var.equals(oldVar)) { - var.replaceWith(newVar.clone()); - } - } - - @Override - public void meet(ProjectionElem projElem) throws RuntimeException { - if (projElem.getName().equals(oldVar.getName())) { - projElem.setName(newVar.getName()); - } - } - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class BindingSetAssignmentCollector extends AbstractQueryModelVisitor { - - private final List assignments = new ArrayList<>(); - - @Override - public void meet(BindingSetAssignment bsa) { - assignments.add(bsa); - } - - public List getBindingSetAssignments() { - return assignments; - } - } - - @Deprecated(forRemoval = true, since = "4.1.0") - protected static class VarBinder extends AbstractQueryModelVisitor { - - private final String varName; - - private final Value value; - - public VarBinder(String varName, Value value) { - this.varName = varName; - this.value = value; - } - - @Override - public void meet(Var var) { - if (var.getName().equals(varName)) { - var.setValue(value); - } - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/SimpleEvaluationStrategy.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/SimpleEvaluationStrategy.java deleted file mode 100644 index d5c01793ee3..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/SimpleEvaluationStrategy.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource; -import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolver; - -/** - * @deprecated renamed to {@link StrictEvaluationStrategy}. - */ -@Deprecated -public class SimpleEvaluationStrategy extends StrictEvaluationStrategy { - - /** - * @param tripleSource - * @param serviceResolver - */ - public SimpleEvaluationStrategy(TripleSource tripleSource, FederatedServiceResolver serviceResolver) { - super(tripleSource, serviceResolver); - } - - /** - * @param tripleSource - * @param dataset - * @param serviceResolver - */ - public SimpleEvaluationStrategy(TripleSource tripleSource, Dataset dataset, - FederatedServiceResolver serviceResolver) { - super(tripleSource, dataset, serviceResolver); - } - - /** - * @param tripleSource - * @param dataset - * @param serviceResolver - * @param iterationCacheSyncTreshold - */ - public SimpleEvaluationStrategy(TripleSource tripleSource, Dataset dataset, - FederatedServiceResolver serviceResolver, long iterationCacheSyncTreshold) { - super(tripleSource, dataset, serviceResolver, iterationCacheSyncTreshold, new EvaluationStatistics()); - } - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/StandardQueryOptimizerPipeline.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/StandardQueryOptimizerPipeline.java deleted file mode 100644 index 6f33e54137d..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/StandardQueryOptimizerPipeline.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; -import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategyFactory; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizerPipeline; -import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource; - -/** - * A standard pipeline with the default {@link QueryOptimizer}s that will be used by {@link StrictEvaluationStrategy} - * and its subclasses, unless specifically overridden. - * - * @author Jeen Broekstra - * @see EvaluationStrategyFactory#setOptimizerPipeline(QueryOptimizerPipeline) - * - * @deprecated since 4.1.0. Use - * {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.StandardQueryOptimizerPipeline} instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class StandardQueryOptimizerPipeline - extends org.eclipse.rdf4j.query.algebra.evaluation.optimizer.StandardQueryOptimizerPipeline - implements QueryOptimizerPipeline { - - public StandardQueryOptimizerPipeline(EvaluationStrategy strategy, TripleSource tripleSource, - EvaluationStatistics evaluationStatistics) { - super(strategy, tripleSource, evaluationStatistics); - } - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/TupleFunctionEvaluationStrategy.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/TupleFunctionEvaluationStrategy.java index 094b5f3e2fb..21726c766d3 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/TupleFunctionEvaluationStrategy.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/TupleFunctionEvaluationStrategy.java @@ -77,7 +77,7 @@ public TupleFunctionEvaluationStrategy(TripleSource tripleSource, Dataset datase @Deprecated(forRemoval = true) @Override - public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) + public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) throws QueryEvaluationException { if (expr instanceof TupleFunctionCall) { return evaluate((TupleFunctionCall) expr, bindings); @@ -97,7 +97,7 @@ public QueryEvaluationStep precompile(TupleExpr expr, QueryEvaluationContext con } @Deprecated(forRemoval = true) - public CloseableIteration evaluate(TupleFunctionCall expr, + public CloseableIteration evaluate(TupleFunctionCall expr, BindingSet bindings) throws QueryEvaluationException { return precompile(expr).evaluate(bindings); } @@ -116,7 +116,7 @@ protected QueryEvaluationStep prepare(TupleFunctionCall expr, QueryEvaluationCon return new QueryEvaluationStep() { @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { Value[] argValues = new Value[args.size()]; for (int i = 0; i < args.size(); i++) { argValues[i] = argEpresions[i].evaluate(bindings); @@ -128,11 +128,11 @@ public CloseableIteration evaluate(Binding }; } - public static CloseableIteration evaluate(TupleFunction func, + public static CloseableIteration evaluate(TupleFunction func, final List resultVars, final BindingSet bindings, ValueFactory valueFactory, Value... argValues) throws QueryEvaluationException { return new LookAheadIteration<>() { - private final CloseableIteration, QueryEvaluationException> iter = func + private final CloseableIteration> iter = func .evaluate(valueFactory, argValues); @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/UnionScopeChangeOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/UnionScopeChangeOptimizer.java deleted file mode 100644 index 4fdff781c07..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/UnionScopeChangeOptimizer.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.impl; - -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; - -/** - * Inspect Union clauses to check if scope change can be avoided (allowing injection of pre-bound vars into union - * arguments). - * - * @author Jeen Broekstra - * @deprecated since 4.1.0. Use {@link org.eclipse.rdf4j.query.algebra.evaluation.optimizer.UnionScopeChangeOptimizer} - * instead. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class UnionScopeChangeOptimizer extends - org.eclipse.rdf4j.query.algebra.evaluation.optimizer.UnionScopeChangeOptimizer implements QueryOptimizer { -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/BindingSetAssignmentQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/BindingSetAssignmentQueryEvaluationStep.java index b4da972fbe9..10eb79540fc 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/BindingSetAssignmentQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/BindingSetAssignmentQueryEvaluationStep.java @@ -34,7 +34,7 @@ public BindingSetAssignmentQueryEvaluationStep(BindingSetAssignment node, QueryE } @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { final Iterator assignments = node.getBindingSets().iterator(); if (bindings.size() == 0) { // we can just return the assignments directly without checking existing bindings @@ -42,9 +42,9 @@ public CloseableIteration evaluate(Binding } // we need to verify that new binding assignments do not overwrite existing bindings - CloseableIteration result; + CloseableIteration result; - result = new LookAheadIteration() { + result = new LookAheadIteration() { @Override protected BindingSet getNextElement() throws QueryEvaluationException { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/IntersectionQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/IntersectionQueryEvaluationStep.java index aa24ca5fdc8..d495984f5ec 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/IntersectionQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/IntersectionQueryEvaluationStep.java @@ -17,7 +17,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.IntersectIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; /** @@ -37,7 +36,7 @@ public IntersectionQueryEvaluationStep(QueryEvaluationStep leftArg, QueryEvaluat } @Override - public CloseableIteration evaluate(BindingSet bs) { + public CloseableIteration evaluate(BindingSet bs) { return new IntersectIteration<>(leftArg.evaluate(bs), rightArgDelayed.apply(bs), setMaker); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/JoinQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/JoinQueryEvaluationStep.java index 0941ba239b1..66c726afa29 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/JoinQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/JoinQueryEvaluationStep.java @@ -12,7 +12,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.Join; import org.eclipse.rdf4j.query.algebra.Service; import org.eclipse.rdf4j.query.algebra.TupleExpr; @@ -26,7 +25,7 @@ public class JoinQueryEvaluationStep implements QueryEvaluationStep { - private final java.util.function.Function> eval; + private final java.util.function.Function> eval; public JoinQueryEvaluationStep(EvaluationStrategy strategy, Join join, QueryEvaluationContext context) { // efficient computation of a SERVICE join using vectored evaluation @@ -34,28 +33,28 @@ public JoinQueryEvaluationStep(EvaluationStrategy strategy, Join join, QueryEval QueryEvaluationStep leftPrepared = strategy.precompile(join.getLeftArg(), context); QueryEvaluationStep rightPrepared = strategy.precompile(join.getRightArg(), context); if (join.getRightArg() instanceof Service) { - eval = (bindings) -> new ServiceJoinIterator(leftPrepared.evaluate(bindings), + eval = bindings -> new ServiceJoinIterator(leftPrepared.evaluate(bindings), (Service) join.getRightArg(), bindings, strategy); join.setAlgorithm(ServiceJoinIterator.class.getSimpleName()); } else if (isOutOfScopeForLeftArgBindings(join.getRightArg())) { String[] joinAttributes = HashJoinIteration.hashJoinAttributeNames(join); - eval = (bindings) -> new HashJoinIteration(leftPrepared, rightPrepared, bindings, false, + eval = bindings -> new HashJoinIteration(leftPrepared, rightPrepared, bindings, false, joinAttributes, context); join.setAlgorithm(HashJoinIteration.class.getSimpleName()); } else { - eval = (bindings) -> new JoinIterator(strategy, leftPrepared, rightPrepared, join, bindings); + eval = bindings -> new JoinIterator(leftPrepared, rightPrepared, bindings); join.setAlgorithm(JoinIterator.class.getSimpleName()); } } @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { return eval.apply(bindings); } private static boolean isOutOfScopeForLeftArgBindings(TupleExpr expr) { - return (TupleExprs.isVariableScopeChange(expr) || TupleExprs.containsSubquery(expr)); + return TupleExprs.isVariableScopeChange(expr) || TupleExprs.containsSubquery(expr); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/LeftJoinQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/LeftJoinQueryEvaluationStep.java index 902b5077711..669b00d814a 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/LeftJoinQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/LeftJoinQueryEvaluationStep.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.LeftJoin; import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; @@ -61,34 +60,6 @@ public static QueryEvaluationStep supply(EvaluationStrategy strategy, LeftJoin l return new LeftJoinQueryEvaluationStep(right, condition, left, leftJoin, optionalVarCollector.getVarNames()); } - @Deprecated(forRemoval = true, since = "4.1.0") - public LeftJoinQueryEvaluationStep(QueryEvaluationStep right, QueryValueEvaluationStep condition, - QueryEvaluationStep left, LeftJoin leftJoin, - org.eclipse.rdf4j.query.algebra.helpers.VarNameCollector optionalVarCollector) { - this.right = right; - this.condition = condition; - this.left = left; - this.leftJoin = leftJoin; - // This is used to determine if the left join is well designed. - - Set leftBindingNames = leftJoin.getLeftArg().getBindingNames(); - Set optionalVars = optionalVarCollector.getVarNames(); - - boolean optionalVarsContainLeftBindingName = false; - for (String leftBindingName : leftBindingNames) { - if (!optionalVarsContainLeftBindingName && optionalVars.contains(leftBindingName)) { - optionalVars = new HashSet<>(optionalVars); - optionalVarsContainLeftBindingName = true; - } - if (optionalVarsContainLeftBindingName) { - optionalVars.remove(leftBindingName); - } - } - - this.optionalVars = optionalVars; - - } - public LeftJoinQueryEvaluationStep(QueryEvaluationStep right, QueryValueEvaluationStep condition, QueryEvaluationStep left, LeftJoin leftJoin, Set optionalVars) { this.right = right; @@ -118,7 +89,7 @@ public LeftJoinQueryEvaluationStep(QueryEvaluationStep right, QueryValueEvaluati } @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { boolean containsNone = true; Set bindingNames = bindings.getBindingNames(); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/MinusQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/MinusQueryEvaluationStep.java index 0da91ef5485..868f33f320f 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/MinusQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/MinusQueryEvaluationStep.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.iterator.SPARQLMinusIteration; @@ -28,7 +27,7 @@ public MinusQueryEvaluationStep(QueryEvaluationStep leftQes, QueryEvaluationStep } @Override - public CloseableIteration evaluate(BindingSet bindings) { - return new SPARQLMinusIteration<>(leftQes.evaluate(bindings), rightQes.apply(bindings)); + public CloseableIteration evaluate(BindingSet bindings) { + return new SPARQLMinusIteration(leftQes.evaluate(bindings), rightQes.apply(bindings)); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/OrderQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/OrderQueryEvaluationStep.java index 09ec52ed90a..1b8d6bfc727 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/OrderQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/OrderQueryEvaluationStep.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.iterator.OrderIterator; @@ -37,7 +36,7 @@ public OrderQueryEvaluationStep(Comparator cmp, long limit, boolean } @Override - public CloseableIteration evaluate(BindingSet bs) { + public CloseableIteration evaluate(BindingSet bs) { return new OrderIterator(preparedArg.evaluate(bs), cmp, limit, reduced, iterationCacheSyncThreshold); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ProjectionQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ProjectionQueryEvaluationStep.java index ba07b753cb8..c2f3f0c963d 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ProjectionQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ProjectionQueryEvaluationStep.java @@ -12,7 +12,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.Projection; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; @@ -31,7 +30,18 @@ public ProjectionQueryEvaluationStep(Projection projection, QueryEvaluationStep } @Override - public CloseableIteration evaluate(BindingSet bindings) { - return new ProjectionIterator(projection, qes.evaluate(bindings), bindings, context); + public CloseableIteration evaluate(BindingSet bindings) { + CloseableIteration evaluate = null; + + try { + evaluate = qes.evaluate(bindings); + return new ProjectionIterator(projection, evaluate, bindings, context); + } catch (Throwable t) { + if (evaluate != null) { + evaluate.close(); + } + throw t; + } + } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/RdfStarQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/RdfStarQueryEvaluationStep.java index cd3b2df389c..57608c574b5 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/RdfStarQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/RdfStarQueryEvaluationStep.java @@ -45,7 +45,7 @@ public RdfStarQueryEvaluationStep(Var subjVar, Var predVar, Var objVar, Var extV } @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { final Value subjValue = StrictEvaluationStrategy.getVarValue(subjVar, bindings); final Value predValue = StrictEvaluationStrategy.getVarValue(predVar, bindings); final Value objValue = StrictEvaluationStrategy.getVarValue(objVar, bindings); @@ -69,10 +69,10 @@ public CloseableIteration evaluate(Binding } // in case the - CloseableIteration sourceIter = tripleSource + CloseableIteration sourceIter = tripleSource .getRdfStarTriples((Resource) subjValue, (IRI) predValue, objValue); - FilterIteration filterIter = new FilterIteration( + FilterIteration filterIter = new FilterIteration<>( sourceIter) { @Override protected boolean accept(Triple triple) throws QueryEvaluationException { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ReificationRdfStarQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ReificationRdfStarQueryEvaluationStep.java index e4957b10356..4ec734e749d 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ReificationRdfStarQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ReificationRdfStarQueryEvaluationStep.java @@ -46,14 +46,14 @@ public ReificationRdfStarQueryEvaluationStep(Var subjVar, Var predVar, Var objVa } @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { final Value subjValue = StrictEvaluationStrategy.getVarValue(subjVar, bindings); final Value predValue = StrictEvaluationStrategy.getVarValue(predVar, bindings); final Value objValue = StrictEvaluationStrategy.getVarValue(objVar, bindings); final Value extValue = StrictEvaluationStrategy.getVarValue(extVar, bindings); // standard reification iteration // 1. walk over resources used as subjects of (x rdf:type rdf:Statement) - final CloseableIteration iter = new ConvertingIteration( + final CloseableIteration iter = new ConvertingIteration( tripleSource.getStatements((Resource) extValue, RDF.TYPE, RDF.STATEMENT)) { @Override @@ -107,7 +107,7 @@ protected BindingSet getNextElement() // private boolean matchValue(Resource theNode, Value value, Var var, MutableBindingSet result, IRI predicate) { - try (CloseableIteration valueIter = tripleSource + try (CloseableIteration valueIter = tripleSource .getStatements(theNode, predicate, null)) { while (valueIter.hasNext()) { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ServiceQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ServiceQueryEvaluationStep.java index a1e5d6cbd8d..9ef245ce747 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ServiceQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ServiceQueryEvaluationStep.java @@ -38,7 +38,7 @@ public ServiceQueryEvaluationStep(Service service, Var serviceRef, FederatedServ } @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { String serviceUri; if (serviceRef.hasValue()) { serviceUri = serviceRef.getValue().stringValue(); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/SliceQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/SliceQueryEvaluationStep.java index 02a1f662a88..8fa057daa19 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/SliceQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/SliceQueryEvaluationStep.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.common.iteration.LimitIteration; import org.eclipse.rdf4j.common.iteration.OffsetIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.Slice; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; @@ -45,7 +44,7 @@ public OnlyOffsetQueryEvaluationStep(long offset, QueryEvaluationStep argument) } @Override - public CloseableIteration evaluate(BindingSet bs) { + public CloseableIteration evaluate(BindingSet bs) { return new OffsetIteration<>(argument.evaluate(bs), offset); } } @@ -63,8 +62,8 @@ public OffSetAndLimitQueryEvaluationStep(long offset, long limit, QueryEvaluatio } @Override - public CloseableIteration evaluate(BindingSet bs) { - CloseableIteration evaluate = argument.evaluate(bs); + public CloseableIteration evaluate(BindingSet bs) { + CloseableIteration evaluate = argument.evaluate(bs); return new LimitIteration<>(new OffsetIteration<>(evaluate, offset), limit); } } @@ -80,7 +79,7 @@ public OnlyLimitQueryEvaluationStep(long limit, QueryEvaluationStep argument) { } @Override - public CloseableIteration evaluate(BindingSet bs) { + public CloseableIteration evaluate(BindingSet bs) { return new LimitIteration<>(argument.evaluate(bs), limit); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/StatementPatternQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/StatementPatternQueryEvaluationStep.java index 201acb284a4..53c712b76db 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/StatementPatternQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/StatementPatternQueryEvaluationStep.java @@ -43,7 +43,7 @@ public class StatementPatternQueryEvaluationStep implements QueryEvaluationStep public static final Resource[] DEFAULT_CONTEXT = { null }; public static final Resource[] ALL_CONTEXT = new Resource[0]; - private static final Function RETURN_NULL_VALUE_RESOURCE_ARRAY = (v) -> null; + private static final Function RETURN_NULL_VALUE_RESOURCE_ARRAY = v -> null; private final StatementPattern statementPattern; private final TripleSource tripleSource; @@ -188,7 +188,7 @@ private static Predicate getUnboundTest(QueryEvaluationContext conte return UnboundTest.c(context, c); } - return (b) -> false; + return b -> false; } @@ -197,14 +197,14 @@ private static Function makeGetVarValue(Var var, QueryEvaluat return null; } else if (var.hasValue()) { Value value = var.getValue(); - return (b) -> value; + return b -> value; } else { return context.getValue(var.getName()); } } @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { if (emptyGraph) { return EMPTY_ITERATION; } else if (bindings.isEmpty()) { @@ -250,7 +250,7 @@ private JoinStatementWithBindingSetIterator getIteration(BindingSet bindings) { Value object = getObjectVar != null ? getObjectVar.apply(bindings) : null; - CloseableIteration iteration = null; + CloseableIteration iteration = null; try { iteration = tripleSource.getStatements((Resource) subject, (IRI) predicate, object, contexts); if (iteration instanceof EmptyIteration) { @@ -284,11 +284,11 @@ private ConvertStatementToBindingSetIterator getIteration() { Value predicate = statementPattern.getPredicateVar().getValue(); Value object = statementPattern.getObjectVar().getValue(); - if ((subject != null && !subject.isResource()) || (predicate != null && !predicate.isIRI())) { + if (subject != null && !subject.isResource() || predicate != null && !predicate.isIRI()) { return null; } - CloseableIteration iteration = null; + CloseableIteration iteration = null; try { iteration = tripleSource.getStatements((Resource) subject, (IRI) predicate, object, contexts); if (iteration instanceof EmptyIteration) { @@ -309,16 +309,16 @@ private ConvertStatementToBindingSetIterator getIteration() { } } - private CloseableIteration handleFilter(Resource[] contexts, + private CloseableIteration handleFilter(Resource[] contexts, Resource subject, IRI predicate, Value object, - CloseableIteration iteration) { + CloseableIteration iteration) { Predicate filter = filterContextOrEqualVariables(statementPattern, subject, predicate, object, contexts); if (filter != null) { // Only if there is filter code to execute do we make this filter iteration. - return new FilterIteration(iteration) { + return new FilterIteration(iteration) { @Override protected boolean accept(Statement object) throws QueryEvaluationException { @@ -339,7 +339,7 @@ protected static Predicate filterContextOrEqualVariables(StatementPat Value subjValue, Value predValue, Value objValue, Resource[] contexts) { Predicate filter = null; if (contexts.length == 0 && statementPattern.getScope() == Scope.NAMED_CONTEXTS) { - filter = (st) -> st.getContext() != null; + filter = st -> st.getContext() != null; } return filterSameVariable(statementPattern, subjValue, predValue, objValue, filter); } @@ -376,7 +376,7 @@ private static Predicate filterSameVariable(StatementPattern statemen if (objVar != null && objValue == null) { boolean objEqConVar = objVar.equals(conVar); if (objEqConVar) { - filter = andThen(filter, (st) -> { + filter = andThen(filter, st -> { Value obj = st.getObject(); Resource context = st.getContext(); return obj.equals(context); @@ -390,10 +390,10 @@ private static Predicate filterSameVariable(StatementPattern statemen private static Predicate predicateVariableHasEquals(boolean predEqObjVar, boolean predEqConVar) { Predicate eq = null; if (predEqObjVar) { - eq = (st) -> st.getPredicate().equals(st.getObject()); + eq = st -> st.getPredicate().equals(st.getObject()); } if (predEqConVar) { - eq = andThen(eq, (st) -> st.getPredicate().equals(st.getContext())); + eq = andThen(eq, st -> st.getPredicate().equals(st.getContext())); } return eq; } @@ -402,13 +402,13 @@ private static Predicate subjectVariableHasEquals(boolean subEqPredVa boolean subEqConVar) { Predicate eq = null; if (subEqPredVar) { - eq = (st) -> st.getSubject().equals(st.getPredicate()); + eq = st -> st.getSubject().equals(st.getPredicate()); } if (subEqObjVar) { - eq = andThen(eq, (st) -> st.getSubject().equals(st.getObject())); + eq = andThen(eq, st -> st.getSubject().equals(st.getObject())); } if (subEqConVar) { - eq = andThen(eq, (st) -> st.getSubject().equals(st.getContext())); + eq = andThen(eq, st -> st.getSubject().equals(st.getContext())); } return eq; } @@ -430,11 +430,11 @@ protected static Function extractContextsFromDatasets(Var con Resource[] filled = fillContextsFromDatasSetGraphs(graphs); // if contextVar is null contextValue must always be null; if (contextVar == null) { - return (contextValue) -> filled; + return contextValue -> filled; } else { - return (contextValue) -> { + return contextValue -> { if (contextValue != null) { - if (contextValue.isIRI() && graphs.contains(((IRI) contextValue))) { + if (contextValue.isIRI() && graphs.contains((IRI) contextValue)) { return new Resource[] { (Resource) contextValue }; } else { // Statement pattern specifies a context that is not part of @@ -488,15 +488,15 @@ private static Resource[] fillContextsFromDatasSetGraphs(Set graphs) { * it of course is an unneeded expense. */ private static final class ConvertStatementToBindingSetIterator - implements CloseableIteration { + implements CloseableIteration { private final BiConsumer action; private final QueryEvaluationContext context; - private final CloseableIteration iteration; + private final CloseableIteration iteration; private boolean closed = false; private ConvertStatementToBindingSetIterator( - CloseableIteration iteration, + CloseableIteration iteration, BiConsumer action, QueryEvaluationContext context) { assert iteration != null; this.iteration = iteration; @@ -535,16 +535,16 @@ public void close() throws QueryEvaluationException { } private static final class JoinStatementWithBindingSetIterator - implements CloseableIteration { + implements CloseableIteration { private final BiConsumer action; private final QueryEvaluationContext context; private final BindingSet bindings; - private final CloseableIteration iteration; + private final CloseableIteration iteration; private boolean closed = false; private JoinStatementWithBindingSetIterator( - CloseableIteration iteration, + CloseableIteration iteration, BiConsumer action, BindingSet bindings, QueryEvaluationContext context) { assert iteration != null; this.iteration = iteration; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/UnionQueryEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/UnionQueryEvaluationStep.java index 70a6c318e6c..63dbd1a1e28 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/UnionQueryEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/UnionQueryEvaluationStep.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.common.iteration.DualUnionIteration; import org.eclipse.rdf4j.common.iteration.EmptyIteration; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; public class UnionQueryEvaluationStep implements QueryEvaluationStep { @@ -28,9 +27,9 @@ public UnionQueryEvaluationStep(QueryEvaluationStep leftQes, QueryEvaluationStep } @Override - public CloseableIteration evaluate(BindingSet bindings) { - CloseableIteration evaluate = null; - CloseableIteration evaluate1 = null; + public CloseableIteration evaluate(BindingSet bindings) { + CloseableIteration evaluate = null; + CloseableIteration evaluate1 = null; try { evaluate = leftQes.evaluate(bindings); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ZeroLengthPathEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ZeroLengthPathEvaluationStep.java index 04c40278bd5..74a9849e33f 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ZeroLengthPathEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/ZeroLengthPathEvaluationStep.java @@ -43,7 +43,7 @@ public ZeroLengthPathEvaluationStep(Var subjectVar, Var objVar, Var contextVar, } @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { Value subj = null; try { subj = subPrep.evaluate(bindings); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/CompareAllQueryValueEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/CompareAllQueryValueEvaluationStep.java index 0f79b80fde9..79dc9d1d44c 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/CompareAllQueryValueEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/CompareAllQueryValueEvaluationStep.java @@ -44,7 +44,7 @@ public Value evaluate(BindingSet bindings) throws ValueExprEvaluationException, Value leftValue = arg.evaluate(bindings); // Result is true until a mismatch has been found boolean result = true; - try (CloseableIteration iter = subquery.evaluate(bindings)) { + try (CloseableIteration iter = subquery.evaluate(bindings)) { while (result && iter.hasNext()) { BindingSet bindingSet = iter.next(); Value rightValue = getValue.apply(bindingSet); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/CompareAnyValueEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/CompareAnyValueEvaluationStep.java index 99f55bade52..2654a827e4a 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/CompareAnyValueEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/CompareAnyValueEvaluationStep.java @@ -46,7 +46,7 @@ public Value evaluate(BindingSet bindings) throws ValueExprEvaluationException, // Result is false until a match has been found boolean result = false; - try (CloseableIteration iter = subquery.evaluate(bindings)) { + try (CloseableIteration iter = subquery.evaluate(bindings)) { while (!result && iter.hasNext()) { BindingSet bindingSet = iter.next(); Value rightValue = getValue.apply(bindingSet); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/ExistsQueryValueEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/ExistsQueryValueEvaluationStep.java index fbd5fb36d62..2033befcc37 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/ExistsQueryValueEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/ExistsQueryValueEvaluationStep.java @@ -28,8 +28,8 @@ public ExistsQueryValueEvaluationStep(QueryEvaluationStep subquery) { @Override public Value evaluate(BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException { - try (CloseableIteration iter = subquery.evaluate(bindings)) { + try (CloseableIteration iter = subquery.evaluate(bindings)) { return BooleanLiteral.valueOf(iter.hasNext()); } } -} \ No newline at end of file +} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/InValueEvaluationStep.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/InValueEvaluationStep.java index bbec514f5dc..4b5cd9cca0d 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/InValueEvaluationStep.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/InValueEvaluationStep.java @@ -40,7 +40,7 @@ public Value evaluate(BindingSet bindings) throws ValueExprEvaluationException, boolean result = false; // Use first binding name from tuple expr to compare values String bindingName = node.getSubQuery().getBindingNames().iterator().next(); - try (CloseableIteration iter = subquery.evaluate(bindings)) { + try (CloseableIteration iter = subquery.evaluate(bindings)) { while (!result && iter.hasNext()) { BindingSet bindingSet = iter.next(); Value rightValue = bindingSet.getValue(bindingName); @@ -50,4 +50,4 @@ public Value evaluate(BindingSet bindings) throws ValueExprEvaluationException, } return BooleanLiteral.valueOf(result); } -} \ No newline at end of file +} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/QueryValueEvaluationStepSupplier.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/QueryValueEvaluationStepSupplier.java index aca5a7f9d5d..da0f8aeed6a 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/QueryValueEvaluationStepSupplier.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/evaluationsteps/values/QueryValueEvaluationStepSupplier.java @@ -77,11 +77,11 @@ public static QueryValueEvaluationStep prepareBound(QueryValueEvaluationStep arg public static QueryValueEvaluationStep prepareDatatype(QueryValueEvaluationStep arg, QueryEvaluationContext context) { - return make(arg, "datatype called on constant that throws", (bs) -> datatype(arg, bs)); + return make(arg, "datatype called on constant that throws", bs -> datatype(arg, bs)); } public static QueryValueEvaluationStep prepareLabel(QueryValueEvaluationStep arg, ValueFactory vf) { - return make(arg, "label called on constant that throws", (bs) -> label(arg, bs, vf)); + return make(arg, "label called on constant that throws", bs -> label(arg, bs, vf)); } private static QueryValueEvaluationStep make(QueryValueEvaluationStep arg, String errorMessage, @@ -200,13 +200,13 @@ public static QueryValueEvaluationStep bnode(QueryValueEvaluationStep nodeVes, V if (nodeId instanceof Literal) { String nodeLabel = nodeId.stringValue(); return new QueryValueEvaluationStep.ApplyFunctionForEachBinding( - (bs) -> vf.createBNode(nodeLabel + (bs.toString().hashCode()))); + bs -> vf.createBNode(nodeLabel + bs.toString().hashCode())); } else { return new QueryValueEvaluationStep.Fail("BNODE function argument must be a literal"); } } else { return new QueryValueEvaluationStep.ApplyFunctionForEachBinding( - (bs) -> vf.createBNode(nodeVes.evaluate(bs).stringValue() + bs.toString().hashCode())); + bs -> vf.createBNode(nodeVes.evaluate(bs).stringValue() + bs.toString().hashCode())); } } catch (ValueExprEvaluationException e) { return new QueryValueEvaluationStep.Fail("BNODE function argument must be a literal"); @@ -309,7 +309,7 @@ private static IRI iriFunction(String baseURI, Value argValue, ValueFactory vf) } return result; } else if (argValue instanceof IRI) { - return ((IRI) argValue); + return (IRI) argValue; } throw new ValueExprEvaluationException(); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/BottomUpJoinIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/BottomUpJoinIterator.java deleted file mode 100644 index 7f4a991ed9c..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/BottomUpJoinIterator.java +++ /dev/null @@ -1,271 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.iterator; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.LookAheadIteration; -import org.eclipse.rdf4j.query.Binding; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.algebra.Join; -import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; -import org.eclipse.rdf4j.query.impl.EmptyBindingSet; - -/** - * Join Iterator that executes a basic bottom-up hash-join algorithm. To be used in cases where interleaved iteration - * joining is not appropriate (e.g. when the join arguments are subselects). - * - * @author jeen - * @deprecated replaced by HashJoinIteration - */ -@Deprecated -public class BottomUpJoinIterator extends LookAheadIteration { - - /*-----------* - * Variables * - *-----------*/ - - private final CloseableIteration leftIter; - - private final CloseableIteration rightIter; - - private List scanList; - - private CloseableIteration restIter; - - private Map> hashTable; - - private final Set joinAttributes; - - private BindingSet currentScanElem; - - private List hashTableValues; - - /*--------------* - * Constructors * - *--------------*/ - - public BottomUpJoinIterator(EvaluationStrategy strategy, Join join, BindingSet bindings) - throws QueryEvaluationException { - leftIter = strategy.evaluate(join.getLeftArg(), bindings); - rightIter = strategy.evaluate(join.getRightArg(), bindings); - - Set rightBindingNames = join.getRightArg().getBindingNames(); - joinAttributes = join.getLeftArg() - .getBindingNames() - .stream() - .filter(rightBindingNames::contains) - .collect(Collectors.toSet()); - - hashTable = null; - } - - /*---------* - * Methods * - *---------*/ - - @Override - protected BindingSet getNextElement() throws QueryEvaluationException { - if (hashTable == null) { - setupHashTable(); - } - - while (currentScanElem == null) { - if (scanList.size() > 0) { - currentScanElem = removeFirstElement(scanList); - } else { - if (restIter.hasNext()) { - currentScanElem = restIter.next(); - } else { - // no more elements available - return null; - } - } - - if (currentScanElem instanceof EmptyBindingSet) { - // the empty bindingset should be merged with all bindingset in the - // hash table - hashTableValues = makeList(); - for (Map.Entry> key : hashTable.entrySet()) { - addAll(hashTableValues, key.getValue()); - } - } else { - BindingSet key = calcKey(currentScanElem, joinAttributes); - - if (hashTable.containsKey(key)) { - hashTableValues = makeList(hashTable.get(key)); - } else { - currentScanElem = null; - hashTableValues = null; - } - } - } - - BindingSet nextHashTableValue = removeFirstElement(hashTableValues); - - QueryBindingSet result = new QueryBindingSet(currentScanElem); - - for (String name : nextHashTableValue.getBindingNames()) { - Binding b = nextHashTableValue.getBinding(name); - if (!result.hasBinding(name)) { - result.addBinding(b); - } - } - - if (hashTableValues.isEmpty()) { - // we've exhausted the current scanlist entry - currentScanElem = null; - hashTableValues = null; - } - - return result; - } - - @Override - protected void handleClose() throws QueryEvaluationException { - try { - super.handleClose(); - } finally { - try { - leftIter.close(); - } finally { - try { - CloseableIteration toCloseRightIter = rightIter; - if (toCloseRightIter != null) { - toCloseRightIter.close(); - } - } finally { - hashTable = null; - hashTableValues = null; - scanList = null; - } - } - } - } - - /** - * @return the size that the hashtable had before clearing it. - */ - protected long clearHashTable() { - int size = hashTable.size(); - hashTable.clear(); - return size; - } - - private BindingSet calcKey(BindingSet bindings, Set commonVars) { - QueryBindingSet q = new QueryBindingSet(); - for (String varName : commonVars) { - Binding b = bindings.getBinding(varName); - if (b != null) { - q.addBinding(b); - } - } - return q; - } - - private void setupHashTable() throws QueryEvaluationException { - - hashTable = makeMap(); - - List leftArgResults = makeList(); - List rightArgResults = makeList(); - - while (leftIter.hasNext() && rightIter.hasNext()) { - add(leftArgResults, leftIter.next()); - add(rightArgResults, rightIter.next()); - } - - List smallestResult; - - if (leftIter.hasNext()) { // leftArg is the greater relation - smallestResult = rightArgResults; - scanList = leftArgResults; - restIter = leftIter; - } else { // rightArg is the greater relation (or they are equal) - smallestResult = leftArgResults; - scanList = rightArgResults; - restIter = rightIter; - } - - // create the hash table for our join - for (BindingSet b : smallestResult) { - BindingSet hashKey = calcKey(b, joinAttributes); - - List hashValue; - if (hashTable.containsKey(hashKey)) { - hashValue = hashTable.get(hashKey); - } else { - hashValue = makeList(); - } - add(hashValue, b); - put(hashTable, hashKey, hashValue); - } - - } - - protected void put(Map> hashTable, BindingSet hashKey, List hashValue) - throws QueryEvaluationException { - hashTable.put(hashKey, hashValue); - } - - protected void addAll(List hashTableValues, List values) throws QueryEvaluationException { - hashTableValues.addAll(values); - } - - protected void add(List leftArgResults, BindingSet b) throws QueryEvaluationException { - leftArgResults.add(b); - } - - /** - * Utility methods to make it easier to inserted custom store dependent maps - * - * @return map - */ - protected Map> makeMap() { - return new HashMap<>(); - } - - /** - * Utility methods to make it easier to inserted custom store dependent list - * - * @return list - */ - protected List makeList() { - return new ArrayList<>(); - } - - /** - * Utility methods to make it easier to inserted custom store dependent list - * - * @return list - */ - protected List makeList(List key) { - return new ArrayList<>(key); - } - - /** - * Remove the first (0 index) element from a BindingSet list. - * - * @param list which is worked on. - * @return the removed BindingSet - */ - protected BindingSet removeFirstElement(List list) throws QueryEvaluationException { - return list.remove(0); - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CollectionIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CollectionIteration.java deleted file mode 100644 index 00395dd1e06..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CollectionIteration.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.iterator; - -import java.util.Collection; - -/** - * An iteration to access a materialized {@link Collection} of BindingSets. - * - * @author Andreas Schwarte - * @deprecated since 2.3 use {@link org.eclipse.rdf4j.repository.sparql.federation.CollectionIteration} - */ -@Deprecated -public class CollectionIteration - extends org.eclipse.rdf4j.repository.sparql.federation.CollectionIteration { - - public CollectionIteration(Collection collection) { - super(collection); - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CompatibleBindingSetFilter.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CompatibleBindingSetFilter.java deleted file mode 100644 index fcff042d71f..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CompatibleBindingSetFilter.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.iterator; - -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.FilterIteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.QueryResults; - -/** - * @author Arjohn Kampman - * @deprecated - */ -@Deprecated -public class CompatibleBindingSetFilter extends FilterIteration { - - private final BindingSet inputBindings; - - public CompatibleBindingSetFilter(CloseableIteration iter, - BindingSet inputBindings) { - super(iter); - - assert inputBindings != null; - this.inputBindings = inputBindings; - } - - @Override - protected boolean accept(BindingSet outputBindings) throws QueryEvaluationException { - return QueryResults.bindingSetsCompatible(inputBindings, outputBindings); - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CrossProductIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CrossProductIteration.java index 8335dd99ea8..566d3320f14 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CrossProductIteration.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/CrossProductIteration.java @@ -26,17 +26,17 @@ * * @author Andreas Schwarte */ -public class CrossProductIteration extends LookAheadIteration { +public class CrossProductIteration extends LookAheadIteration { protected final List inputBindings; - protected final CloseableIteration resultIteration; + protected final CloseableIteration resultIteration; protected Iterator inputBindingsIterator = null; protected BindingSet currentInputBinding = null; - public CrossProductIteration(CloseableIteration resultIteration, + public CrossProductIteration(CloseableIteration resultIteration, List inputBindings) { super(); this.resultIteration = resultIteration; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/DelayedEvaluationIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/DelayedEvaluationIteration.java deleted file mode 100644 index 5227ffdd5ee..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/DelayedEvaluationIteration.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2022 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ - -package org.eclipse.rdf4j.query.algebra.evaluation.iterator; - -import java.util.NoSuchElementException; - -import org.eclipse.rdf4j.common.iteration.AbstractCloseableIteration; -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; - -/** - * Utility class that removes code duplication and makes a precompiled QueryEvaluationStep available as an iteration - * that may be created and used later. - */ -public class DelayedEvaluationIteration extends AbstractCloseableIteration { - - private final QueryEvaluationStep arg; - private final BindingSet bs; - private CloseableIteration iter; - - public DelayedEvaluationIteration(QueryEvaluationStep arg, BindingSet bs) { - super(); - this.arg = arg; - this.bs = bs; - } - - protected CloseableIteration createIteration() - throws QueryEvaluationException { - return arg.evaluate(bs); - } - - /** - * Calls the hasNext method of the underlying iteration. - */ - @Override - public boolean hasNext() throws QueryEvaluationException { - if (isClosed()) { - return false; - } - - initialise(); - - return iter.hasNext(); - } - - /** - * Calls the next method of the underlying iteration. - */ - @Override - public BindingSet next() throws QueryEvaluationException { - if (isClosed()) { - throw new NoSuchElementException("Iteration has been closed"); - } - initialise(); - - return iter.next(); - } - - private void initialise() throws QueryEvaluationException { - if (iter == null) { - // Underlying iterator has not yet been initialized - iter = createIteration(); - } - } - - /** - * Calls the remove method of the underlying iteration. - */ - @Override - public void remove() throws QueryEvaluationException { - if (isClosed()) { - throw new IllegalStateException("The iteration has been closed."); - } - if (iter == null) { - throw new IllegalStateException("Underlying iteration was null"); - } - - iter.remove(); - } - - /** - * Closes this iteration as well as the underlying iteration if it has already been created and happens to be a - * {@link CloseableIteration}. - */ - @Override - protected final void handleClose() throws QueryEvaluationException { - if (iter != null) { - iter.close(); - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/DescribeIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/DescribeIteration.java index 5c6ddaa830d..929cb0a5d26 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/DescribeIteration.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/DescribeIteration.java @@ -19,7 +19,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.EmptyIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.LookAheadIteration; import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.Value; @@ -37,7 +36,7 @@ * @see Concise Bounded Description - alternatives */ @Deprecated(since = "4.1.0") -public class DescribeIteration extends LookAheadIteration { +public class DescribeIteration extends LookAheadIteration { protected final static String VARNAME_SUBJECT = "subject"; @@ -55,7 +54,7 @@ public class DescribeIteration extends LookAheadIteration processedNodes = new HashSet<>(); - private CloseableIteration currentDescribeExprIter; + private CloseableIteration currentDescribeExprIter; private enum Mode { OUTGOING_LINKS, @@ -64,9 +63,9 @@ private enum Mode { private Mode currentMode = Mode.OUTGOING_LINKS; - private final Iteration sourceIter; + private final CloseableIteration sourceIter; - public DescribeIteration(Iteration sourceIter, EvaluationStrategy strategy, + public DescribeIteration(CloseableIteration sourceIter, EvaluationStrategy strategy, Set describeExprNames, BindingSet parentBindings) { this.strategy = strategy; this.sourceIter = sourceIter; @@ -206,7 +205,7 @@ protected BindingSet getNextElement() throws QueryEvaluationException { return null; } - protected CloseableIteration createNextIteration(Value subject, Value object) + protected CloseableIteration createNextIteration(Value subject, Value object) throws QueryEvaluationException { if (subject == null && object == null) { return new EmptyIteration<>(); @@ -227,12 +226,11 @@ protected void handleClose() throws QueryEvaluationException { } finally { try { - if (currentDescribeExprIter != null) + if (currentDescribeExprIter != null) { currentDescribeExprIter.close(); - } finally { - if (sourceIter instanceof CloseableIteration) { - ((CloseableIteration) sourceIter).close(); } + } finally { + sourceIter.close(); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ExtensionIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ExtensionIterator.java index 0acb522f9cf..fed881bf324 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ExtensionIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ExtensionIterator.java @@ -29,19 +29,19 @@ import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; @Deprecated(since = "4.1.0") -public class ExtensionIterator extends ConvertingIteration { +public class ExtensionIterator extends ConvertingIteration { private final Consumer setter; private final QueryEvaluationContext context; - public ExtensionIterator(Extension extension, CloseableIteration iter, + public ExtensionIterator(Extension extension, CloseableIteration iter, EvaluationStrategy strategy, QueryEvaluationContext context) throws QueryEvaluationException { super(iter); this.context = context; this.setter = buildLambdaToEvaluateTheExpressions(extension, strategy, context); } - public ExtensionIterator(CloseableIteration iter, + public ExtensionIterator(CloseableIteration iter, Consumer setter, QueryEvaluationContext context) throws QueryEvaluationException { super(iter); this.setter = setter; @@ -56,11 +56,11 @@ public static Consumer buildLambdaToEvaluateTheExpressions(Ex if (!(expr instanceof AggregateOperator)) { QueryValueEvaluationStep prepared = strategy.precompile(extElem.getExpr(), context); BiConsumer setBinding = context.setBinding(extElem.getName()); - consumer = andThen(consumer, (targetBindings) -> setValue(setBinding, prepared, targetBindings)); + consumer = andThen(consumer, targetBindings -> setValue(setBinding, prepared, targetBindings)); } } if (consumer == null) { - return (bs) -> { + return bs -> { }; } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/FilterIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/FilterIterator.java index c164e46550b..2c3d6beb308 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/FilterIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/FilterIterator.java @@ -31,7 +31,7 @@ import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; @Deprecated(since = "4.1.0") -public class FilterIterator extends FilterIteration { +public class FilterIterator extends FilterIteration { private final QueryValueEvaluationStep condition; private final EvaluationStrategy strategy; @@ -40,7 +40,7 @@ public class FilterIterator extends FilterIteration iter, + public FilterIterator(Filter filter, CloseableIteration iter, QueryValueEvaluationStep condition, EvaluationStrategy strategy) throws QueryEvaluationException { super(iter); this.condition = condition; @@ -58,20 +58,6 @@ protected boolean accept(BindingSet bindings) throws QueryEvaluationException { } } - @Deprecated(forRemoval = true, since = "4.2.1") - public static boolean isPartOfSubQuery(QueryModelNode node) { - if (node instanceof SubQueryValueOperator) { - return true; - } - - QueryModelNode parent = node.getParentNode(); - if (parent == null) { - return false; - } else { - return isPartOfSubQuery(parent); - } - } - /** * This is used to make sure that no variable is seen by the filter that are not in scope. Historically important in * subquery cases. @@ -100,7 +86,7 @@ public Predicate hasBinding(String variableName) { if (isVariableInScope(variableName)) { return context.hasBinding(variableName); } else { - return (bs) -> false; + return bs -> false; } } @@ -113,7 +99,7 @@ public java.util.function.Function getBinding(String variab if (isVariableInScope(variableName)) { return context.getBinding(variableName); } else { - return (bs) -> null; + return bs -> null; } } @@ -122,7 +108,7 @@ public java.util.function.Function getValue(String variableNa if (isVariableInScope(variableName)) { return context.getValue(variableName); } else { - return (bs) -> null; + return bs -> null; } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/GroupIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/GroupIterator.java index b16dafdc372..d0bb8764341 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/GroupIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/GroupIterator.java @@ -36,7 +36,6 @@ import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.base.CoreDatatype; -import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.MutableBindingSet; @@ -75,7 +74,7 @@ * @author Jerven Bolleman * @author Tomas Kovachev */ -public class GroupIterator extends CloseableIteratorIteration { +public class GroupIterator extends CloseableIteratorIteration { /*-----------* * Constants * @@ -177,7 +176,8 @@ private Iterator createIterator() throws QueryEvaluationException { BiConsumer bindSolution = makeBindSolution(aggregates); Collection entries = buildEntries(aggregates); - Set bindingSets = cf.createSetOfBindingSets(); + Set bindingSets = cf.createSetOfBindingSets(context::createBindingSet, context::hasBinding, + context::getValue, context::setBinding); BiConsumer setValues = makeSetValues(getValues, setBindings); for (Entry entry : entries) { MutableBindingSet sol = makeNewBindingSet.get(); @@ -289,7 +289,7 @@ private Collection buildEntries(List entries = new LinkedHashMap<>(); + Map entries = cf.createGroupByMap(); // Make an optimized hash function valid during this query evaluation step. ToIntFunction hashMaker = cf.hashOfBindingSetFuntion(getValues); while (iter.hasNext()) { @@ -384,8 +384,7 @@ private static class AggregatePredicateCollectorSupplier makeAggregateCollector; public AggregatePredicateCollectorSupplier(AggregateFunction agg, - Supplier> makePotentialDistinctTest, - Supplier makeAggregateCollector, String name) { + Supplier> makePotentialDistinctTest, Supplier makeAggregateCollector, String name) { super(); this.agg = agg; this.makePotentialDistinctTest = makePotentialDistinctTest; @@ -398,8 +397,8 @@ private void operate(BindingSet bs, Predicate predicate, Object t) { } } - private static final Predicate ALWAYS_TRUE_BINDING_SET = (t) -> true; - private static final Predicate ALWAYS_TRUE_VALUE = (t) -> true; + private static final Predicate ALWAYS_TRUE_BINDING_SET = t -> true; + private static final Predicate ALWAYS_TRUE_VALUE = t -> true; private static final Supplier> ALWAYS_TRUE_VALUE_SUPPLIER = () -> ALWAYS_TRUE_VALUE; private AggregatePredicateCollectorSupplier create(GroupElem ge, ValueFactory vf) @@ -409,12 +408,10 @@ private void operate(BindingSet bs, Predicate predicate, Object t) { if (operator instanceof Count) { if (((Count) operator).getArg() == null) { WildCardCountAggregate wildCardCountAggregate = new WildCardCountAggregate(); - Supplier> potentialDistinctTest = operator.isDistinct() - ? DistinctBindingSets::new + Supplier> potentialDistinctTest = operator.isDistinct() ? DistinctBindingSets::new : () -> ALWAYS_TRUE_BINDING_SET; return new AggregatePredicateCollectorSupplier<>(wildCardCountAggregate, potentialDistinctTest, - () -> new CountCollector(vf), - ge.getName()); + () -> new CountCollector(vf), ge.getName()); } else { QueryStepEvaluator f = new QueryStepEvaluator( strategy.precompile(((Count) operator).getArg(), context)); @@ -473,8 +470,7 @@ private void operate(BindingSet bs, Predicate predicate, Object t) { var function = factory.orElseThrow( () -> new QueryEvaluationException("Unknown aggregate function '" + aggOperator.getIRI() + "'")) .buildFunction(new QueryStepEvaluator(strategy.precompile(aggOperator.getArg(), context))); - return new AggregatePredicateCollectorSupplier<>(function, predicate, - () -> factory.get().getCollector(), + return new AggregatePredicateCollectorSupplier<>(function, predicate, () -> factory.get().getCollector(), ge.getName()); } @@ -702,8 +698,8 @@ public void processAggregate(BindingSet s, Predicate distinctValue, Integ if (v.isLiteral()) { if (distinctValue.test(v)) { Literal literal = (Literal) v; - CoreDatatype coreDatatype = literal.getCoreDatatype(); - if (coreDatatype.isXSDDatatype() && ((CoreDatatype.XSD) coreDatatype).isNumericDatatype()) { + CoreDatatype.XSD coreDatatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); + if (coreDatatype != null && coreDatatype.isNumericDatatype()) { sum.value = MathUtil.compute(sum.value, literal, MathOp.PLUS); } else { sum.setTypeError(new ValueExprEvaluationException("not a number: " + v)); @@ -736,8 +732,9 @@ public void processAggregate(BindingSet s, Predicate distinctValue, AvgCo if (v instanceof Literal) { Literal nextLiteral = (Literal) v; // check if the literal is numeric. - if (nextLiteral.getDatatype() != null - && XMLDatatypeUtil.isNumericDatatype(nextLiteral.getDatatype())) { + CoreDatatype.XSD datatype = nextLiteral.getCoreDatatype().asXSDDatatypeOrNull(); + + if (datatype != null && datatype.isNumericDatatype()) { avg.sum = MathUtil.compute(avg.sum, nextLiteral, MathOp.PLUS); } else { avg.setTypeError(new ValueExprEvaluationException("not a number: " + v)); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/HashJoinIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/HashJoinIteration.java index c52e1f40814..09b302ebdfa 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/HashJoinIteration.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/HashJoinIteration.java @@ -31,8 +31,6 @@ import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.Join; import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; @@ -43,15 +41,15 @@ * * @author MJAHale */ -public class HashJoinIteration extends LookAheadIteration { +public class HashJoinIteration extends LookAheadIteration { protected final String[] joinAttributes; - private final CloseableIteration leftIter; - private final CloseableIteration rightIter; + private final CloseableIteration leftIter; + private final CloseableIteration rightIter; private final boolean leftJoin; private Iterator scanList; - private CloseableIteration restIter; + private CloseableIteration restIter; private Map> hashTable; private BindingSet currentScanElem; private Iterator hashTableValues; @@ -65,26 +63,6 @@ public class HashJoinIteration extends LookAheadIteration leftIter, Set leftBindingNames, - CloseableIteration rightIter, Set rightBindingNames, + CloseableIteration leftIter, Set leftBindingNames, + CloseableIteration rightIter, Set rightBindingNames, boolean leftJoin ) throws QueryEvaluationException { this.leftIter = leftIter; @@ -114,24 +93,6 @@ public HashJoinIteration( this.bsMaker = QueryBindingSet::new; } - @Deprecated(forRemoval = true) - public HashJoinIteration( - CloseableIteration leftIter, Set leftBindingNames, - CloseableIteration rightIter, Set rightBindingNames, - boolean leftJoin, IntFunction>> mapMaker, - IntFunction> mapValueMaker - ) throws QueryEvaluationException { - this.leftIter = leftIter; - this.rightIter = rightIter; - this.mapMaker = mapMaker; - - joinAttributes = leftBindingNames.stream().filter(rightBindingNames::contains).toArray(String[]::new); - - this.leftJoin = leftJoin; - this.mapValueMaker = mapValueMaker; - this.bsMaker = QueryBindingSet::new; - } - /*---------* * Methods * *---------*/ @@ -298,7 +259,7 @@ private Map> setupHashTable() throws QueryEv BindingSetHashKey hashKey = BindingSetHashKey.create(joinAttributes, b); List hashValue = resultHashTable.get(hashKey); - boolean newEntry = (hashValue == null); + boolean newEntry = hashValue == null; if (newEntry) { hashValue = mapValueMaker.apply(maxListSize); } @@ -326,7 +287,7 @@ protected void putHashTableEntry(Map> nextHa * * @return list */ - protected Collection makeIterationCache(CloseableIteration iter) { + protected Collection makeIterationCache(CloseableIteration iter) { return new ArrayList<>(); } @@ -343,7 +304,7 @@ protected Map> makeHashTable(int initialSize // when we have more than one value per entry nextHashTable = new HashMap<>(initialSize); } else { - List l = (initialSize > 0) ? new ArrayList<>(initialSize) : null; + List l = initialSize > 0 ? new ArrayList<>(initialSize) : null; nextHashTable = Collections.singletonMap(BindingSetHashKey.EMPTY, l); } return nextHashTable; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/JoinIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/JoinIterator.java index d60ceb4655a..0501ceb997c 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/JoinIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/JoinIterator.java @@ -17,10 +17,7 @@ import org.eclipse.rdf4j.common.iteration.LookAheadIteration; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.algebra.Join; -import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; -import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; /** * Interleaved join iterator. @@ -31,15 +28,15 @@ * * @author Jeen Broekstra */ -public class JoinIterator extends LookAheadIteration { +public class JoinIterator extends LookAheadIteration { /*-----------* * Variables * *-----------*/ - private final CloseableIteration leftIter; + private final CloseableIteration leftIter; - private CloseableIteration rightIter; + private CloseableIteration rightIter; private final QueryEvaluationStep preparedRight; @@ -47,8 +44,8 @@ public class JoinIterator extends LookAheadIteration(); - preparedRight = strategy.precompile(join.getRightArg(), context); - join.setAlgorithm(this); - } +// public JoinIterator(EvaluationStrategy strategy, Join join, BindingSet bindings, QueryEvaluationContext context) +// throws QueryEvaluationException { +// leftIter = strategy.evaluate(join.getLeftArg(), bindings); +// +// // Initialize with empty iteration so that var is never null +// rightIter = new EmptyIteration<>(); +// preparedRight = strategy.precompile(join.getRightArg(), context); +// join.setAlgorithm(this); +// } /*---------* * Methods * diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/LeftJoinIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/LeftJoinIterator.java index 26bedf25f09..15c853319fd 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/LeftJoinIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/LeftJoinIterator.java @@ -30,7 +30,7 @@ import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; import org.eclipse.rdf4j.query.algebra.evaluation.util.QueryEvaluationUtility; -public class LeftJoinIterator extends LookAheadIteration { +public class LeftJoinIterator extends LookAheadIteration { /*-----------* * Variables * @@ -42,9 +42,9 @@ public class LeftJoinIterator extends LookAheadIteration scopeBindingNames; - private final CloseableIteration leftIter; + private final CloseableIteration leftIter; - private CloseableIteration rightIter; + private CloseableIteration rightIter; private final QueryEvaluationStep prepareRightArg; @@ -96,7 +96,7 @@ public LeftJoinIterator(QueryEvaluationStep left, QueryEvaluationStep right, Que @Override protected BindingSet getNextElement() throws QueryEvaluationException { try { - CloseableIteration nextRightIter = rightIter; + CloseableIteration nextRightIter = rightIter; while (nextRightIter.hasNext() || leftIter.hasNext()) { BindingSet leftBindings = null; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/MultiProjectionIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/MultiProjectionIterator.java index 4575367807a..d292617c287 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/MultiProjectionIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/MultiProjectionIterator.java @@ -24,7 +24,7 @@ * @author Arjohn Kampman * @author James Leigh */ -public class MultiProjectionIterator extends LookAheadIteration { +public class MultiProjectionIterator extends LookAheadIteration { /*------------* * Attributes * @@ -32,7 +32,7 @@ public class MultiProjectionIterator extends LookAheadIteration projections; - private final CloseableIteration iter; + private final CloseableIteration iter; private final BindingSet parentBindings; @@ -47,7 +47,7 @@ public class MultiProjectionIterator extends LookAheadIteration iter, BindingSet bindings) { + CloseableIteration iter, BindingSet bindings) { this.projections = multiProjection.getProjections(); this.iter = iter; this.parentBindings = bindings; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/OrderIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/OrderIterator.java index 3a21224aa12..dd5cd489328 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/OrderIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/OrderIterator.java @@ -33,7 +33,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.CloseableIteratorIteration; import org.eclipse.rdf4j.common.iteration.DelayedIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.LimitIteration; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryEvaluationException; @@ -45,7 +44,7 @@ * @author Arjohn Kampman */ @Deprecated(since = "4.1.0") -public class OrderIterator extends DelayedIteration { +public class OrderIterator extends DelayedIteration { private static class SerializedQueue extends AbstractQueue implements Closeable { @@ -228,7 +227,7 @@ private void advance(int i) { * Variables * *-----------*/ - private final CloseableIteration iter; + private final CloseableIteration iter; private final Comparator comparator; @@ -248,17 +247,17 @@ private void advance(int i) { * Constructors * *--------------*/ - public OrderIterator(CloseableIteration iter, + public OrderIterator(CloseableIteration iter, Comparator comparator) { this(iter, comparator, Long.MAX_VALUE, false); } - public OrderIterator(CloseableIteration iter, + public OrderIterator(CloseableIteration iter, Comparator comparator, long limit, boolean distinct) { this(iter, comparator, limit, distinct, Integer.MAX_VALUE); } - public OrderIterator(CloseableIteration iter, + public OrderIterator(CloseableIteration iter, Comparator comparator, long limit, boolean distinct, long iterationSyncThreshold) { this.iter = iter; this.comparator = comparator; @@ -272,7 +271,7 @@ public OrderIterator(CloseableIteration it *---------*/ @Override - protected Iteration createIteration() throws QueryEvaluationException { + protected CloseableIteration createIteration() throws QueryEvaluationException { BindingSet threshold = null; List list = new LinkedList<>(); int limit2 = limit >= Integer.MAX_VALUE / 2 ? Integer.MAX_VALUE : (int) limit * 2; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/PathIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/PathIteration.java index b151121e42c..0caf5294097 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/PathIteration.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/PathIteration.java @@ -15,7 +15,6 @@ import java.util.Set; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.common.iteration.LookAheadIteration; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; @@ -30,7 +29,7 @@ import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; -public class PathIteration extends LookAheadIteration { +public class PathIteration extends LookAheadIteration { /** * @@ -39,7 +38,7 @@ public class PathIteration extends LookAheadIteration currentIter; + private CloseableIteration currentIter; private final BindingSet bindings; @@ -97,7 +96,7 @@ public PathIteration(EvaluationStrategy strategy, Scope scope, Var startVar, protected BindingSet getNextElement() throws QueryEvaluationException { again: while (true) { while (currentIter != null && !currentIter.hasNext()) { - Iterations.closeCloseable(currentIter); + currentIter.close(); createIteration(); // stop condition: if the iter is an EmptyIteration if (currentIter == null) { @@ -219,7 +218,9 @@ protected void handleClose() throws QueryEvaluationException { try { super.handleClose(); } finally { - Iterations.closeCloseable(currentIter); + if (currentIter != null) { + currentIter.close(); + } } } @@ -277,7 +278,8 @@ private void createIteration() throws QueryEvaluationException { TupleExpr pathExprClone = pathExpression.clone(); if (startVarFixed && endVarFixed) { - Var replacement = createAnonVar(JOINVAR_PREFIX + currentLength + "_" + this.hashCode()); + String varName = JOINVAR_PREFIX + currentLength + "_" + this.hashCode(); + Var replacement = createAnonVar(varName, null, true); VarReplacer replacer = new VarReplacer(endVar, replacement, 0, false); pathExprClone.visit(replacer); @@ -294,13 +296,10 @@ private void createIteration() throws QueryEvaluationException { if (startVarFixed && endVarFixed) { - Var startReplacement = createAnonVar(JOINVAR_PREFIX + currentLength + "_" + this.hashCode()); - Var endReplacement = createAnonVar("END_" + JOINVAR_PREFIX + this.hashCode()); - startReplacement.setAnonymous(false); - endReplacement.setAnonymous(false); - Value v = currentVp.getEndValue(); - startReplacement.setValue(v); + Var startReplacement = createAnonVar(JOINVAR_PREFIX + currentLength + "_" + this.hashCode(), v, + false); + Var endReplacement = createAnonVar("END_" + JOINVAR_PREFIX + this.hashCode(), null, false); VarReplacer replacer = new VarReplacer(startVar, startReplacement, 0, false); pathExprClone.visit(replacer); @@ -318,8 +317,8 @@ private void createIteration() throws QueryEvaluationException { v = currentVp.getStartValue(); } - Var replacement = createAnonVar(JOINVAR_PREFIX + currentLength + "-" + this.hashCode()); - replacement.setValue(v); + String varName = JOINVAR_PREFIX + currentLength + "-" + this.hashCode(); + Var replacement = createAnonVar(varName, v, true); VarReplacer replacer = new VarReplacer(toBeReplaced, replacement, 0, false); pathExprClone.visit(replacer); @@ -430,7 +429,8 @@ public void meet(Var var) { QueryModelNode parent = var.getParentNode(); parent.replaceChildNode(var, replacement.clone()); } else if (replaceAnons && var.isAnonymous() && !var.hasValue()) { - Var replacementVar = createAnonVar("anon-replace-" + var.getName() + index); + String varName = "anon-replace-" + var.getName() + index; + Var replacementVar = createAnonVar(varName, null, true); QueryModelNode parent = var.getParentNode(); parent.replaceChildNode(var, replacementVar); } @@ -440,10 +440,7 @@ public void meet(Var var) { private Var createAnonVar(String varName, Value v, boolean anonymous) { namedIntermediateJoins.add(varName); - return new Var(varName, null, anonymous, false); + return new Var(varName, v, anonymous, false); } - public Var createAnonVar(String varName) { - return createAnonVar(varName, null, true); - } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ProjectionIterator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ProjectionIterator.java index 75af95945d0..efb3176f309 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ProjectionIterator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ProjectionIterator.java @@ -29,7 +29,7 @@ import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; @Deprecated(since = "4.1.0") -public class ProjectionIterator extends ConvertingIteration { +public class ProjectionIterator extends ConvertingIteration { /*-----------* * Constants * @@ -43,7 +43,7 @@ public class ProjectionIterator extends ConvertingIteration iter, + public ProjectionIterator(Projection projection, CloseableIteration iter, BindingSet parentBindings, QueryEvaluationContext context) throws QueryEvaluationException { super(iter); ProjectionElemList projectionElemList = projection.getProjectionElemList(); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/QueryContextIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/QueryContextIteration.java index 9b11f39e5b3..4983891a013 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/QueryContextIteration.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/QueryContextIteration.java @@ -21,13 +21,13 @@ /** * Makes a {@link QueryContext} available during iteration. */ -public class QueryContextIteration extends AbstractCloseableIteration { +public class QueryContextIteration extends AbstractCloseableIteration { - private final CloseableIteration iter; + private final CloseableIteration iter; private final QueryContext queryContext; - public QueryContextIteration(CloseableIteration iter, + public QueryContextIteration(CloseableIteration iter, QueryContext queryContext) { this.iter = iter; this.queryContext = queryContext; diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SPARQLMinusIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SPARQLMinusIteration.java index 6f532ce80d4..ce3e4a0cf42 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SPARQLMinusIteration.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SPARQLMinusIteration.java @@ -14,8 +14,8 @@ import java.util.LinkedHashSet; import java.util.Set; +import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.FilterIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryResults; @@ -29,13 +29,13 @@ * @see SPARQL Algebra Documentation */ @Deprecated(since = "4.1.0") -public class SPARQLMinusIteration extends FilterIteration { +public class SPARQLMinusIteration extends FilterIteration { /*-----------* * Variables * *-----------*/ - private final Iteration rightArg; + private final CloseableIteration rightArg; private boolean initialized; @@ -52,7 +52,7 @@ public class SPARQLMinusIteration extends FilterIteration leftArg, Iteration rightArg) { + public SPARQLMinusIteration(CloseableIteration leftArg, CloseableIteration rightArg) { super(leftArg); assert rightArg != null; @@ -61,26 +61,13 @@ public SPARQLMinusIteration(Iteration leftArg, Iteration leftArg, Iteration rightArg, boolean distinct) { - this(leftArg, rightArg); - } - /*--------------* * Constructors * *--------------*/ // implements LookAheadIteration.getNextElement() @Override - protected boolean accept(BindingSet bindingSet) throws X { + protected boolean accept(BindingSet bindingSet) { if (!initialized) { // Build set of elements-to-exclude from right argument excludeSet = makeSet(getRightArg()); @@ -116,31 +103,33 @@ protected boolean accept(BindingSet bindingSet) throws X { return true; } - protected Set makeSet() throws X { + protected Set makeSet() { return new LinkedHashSet<>(); } - protected Set makeSet(Set set) throws X { + protected Set makeSet(Set set) { return new HashSet<>(set); } - protected Set makeSet(Iteration rightArg) throws X { + protected Set makeSet(CloseableIteration rightArg) { return Iterations.asSet(rightArg); } @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { - Iterations.closeCloseable(getRightArg()); + if (rightArg != null) { + rightArg.close(); + } } } /** * @return Returns the rightArg. */ - protected Iteration getRightArg() { + protected CloseableIteration getRightArg() { return rightArg; } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SilentIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SilentIteration.java deleted file mode 100644 index 2d3266ca75d..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SilentIteration.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.iterator; - -import org.eclipse.rdf4j.common.annotation.InternalUseOnly; -import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; - -/** - * Wrap an inner iteration and suppress exceptions silently - * - * @author Andreas Schwarte - * @deprecated Use {@link org.eclipse.rdf4j.common.iteration.SilentIteration } instead. - */ -@Deprecated(since = "3.1.2") -@InternalUseOnly -public class SilentIteration - extends org.eclipse.rdf4j.common.iteration.SilentIteration { - - public SilentIteration(CloseableIteration iter) { - super(iter); - } - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ZeroLengthPathIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ZeroLengthPathIteration.java index a8f490ee7a7..03dfecaedec 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ZeroLengthPathIteration.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ZeroLengthPathIteration.java @@ -31,7 +31,7 @@ import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; -public class ZeroLengthPathIteration extends LookAheadIteration { +public class ZeroLengthPathIteration extends LookAheadIteration { private static final Literal OBJECT = SimpleValueFactory.getInstance().createLiteral("object"); @@ -53,7 +53,7 @@ public class ZeroLengthPathIteration extends LookAheadIteration iter; + private CloseableIteration iter; private Set reportedValues; @@ -164,14 +164,12 @@ protected BindingSet getNextElement() throws QueryEvaluationException { } } - private CloseableIteration createIteration() throws QueryEvaluationException { - CloseableIteration iter = precompile.evaluate(bindings); + private CloseableIteration createIteration() throws QueryEvaluationException { + CloseableIteration iter = precompile.evaluate(bindings); return iter; } public Var createAnonVar(String varName) { - Var var = new Var(varName); - var.setAnonymous(true); - return var; + return new Var(varName, true); } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/LimitedSizeEvaluationStrategy.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/LimitedSizeEvaluationStrategy.java deleted file mode 100644 index 7a6aa3d676b..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/LimitedSizeEvaluationStrategy.java +++ /dev/null @@ -1,158 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.limited; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; - -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource; -import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolver; -import org.eclipse.rdf4j.query.algebra.evaluation.impl.StrictEvaluationStrategy; - -/** - * @author Jerven Bolleman, SIB Swiss Institute of Bioinformatics - * - * @deprecated since 4.2.4. See https://github.com/eclipse/rdf4j/issues/3983 - */ -@Deprecated(forRemoval = true, since = "4.2.4") -public class LimitedSizeEvaluationStrategy extends StrictEvaluationStrategy { - - private final AtomicLong used = new AtomicLong(); - - private final long maxSize; - - /** - * @param tripleSource - */ - public LimitedSizeEvaluationStrategy(TripleSource tripleSource, long maxSize, - FederatedServiceResolver serviceManager) { - super(tripleSource, serviceManager); - this.maxSize = maxSize; - } - - /** - * @param tripleSource - * @param dataset - * @param maxCollectionsSize - */ - public LimitedSizeEvaluationStrategy(TripleSource tripleSource, Dataset dataset, int maxCollectionsSize, - FederatedServiceResolver serviceManager) { - super(tripleSource, dataset, serviceManager); - this.maxSize = maxCollectionsSize; - } - - @Override - public Set makeSet() { - Set wrapped = super.makeSet(); - return new Set<>() { - - @Override - public boolean add(B e) { - final boolean add = wrapped.add(e); - if (add && used.incrementAndGet() > maxSize) { - throw new QueryEvaluationException("Set size is to large"); - } - return add; - } - - @Override - public boolean remove(Object o) { - - final boolean removed = wrapped.remove(o); - if (removed) { - used.decrementAndGet(); - } - return removed; - } - - @Override - public void clear() { - int size = size(); - used.getAndAdd(-size); - wrapped.clear(); - } - - @Override - public int size() { - return wrapped.size(); - } - - @Override - public boolean isEmpty() { - return wrapped.isEmpty(); - } - - @Override - public boolean contains(Object o) { - return wrapped.contains(o); - } - - @Override - public Iterator iterator() { - return wrapped.iterator(); - } - - @Override - public Object[] toArray() { - return wrapped.toArray(); - } - - @Override - public T[] toArray(T[] a) { - return wrapped.toArray(a); - } - - @Override - public boolean containsAll(Collection c) { - return wrapped.containsAll(c); - } - - @Override - public boolean addAll(Collection c) { - boolean all = true; - for (B b : c) { - boolean added = wrapped.add(b); - if (!added) { - all = false; - } - } - return all; - } - - @Override - public boolean retainAll(Collection c) { - int prevSize = wrapped.size(); - boolean changed = wrapped.retainAll(c); - if (changed) { - int newSize = wrapped.size(); - used.addAndGet(-(prevSize - newSize)); - } - return changed; - } - - @Override - public boolean removeAll(Collection c) { - int prevSize = wrapped.size(); - boolean changed = wrapped.removeAll(c); - if (changed) { - int newSize = wrapped.size(); - used.addAndGet(-(prevSize - newSize)); - } - return changed; - } - - }; - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/iterator/LimitedSizeDistinctIteration.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/iterator/LimitedSizeDistinctIteration.java deleted file mode 100644 index 20a1ac7dbe8..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/iterator/LimitedSizeDistinctIteration.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.limited.iterator; - -import java.util.concurrent.atomic.AtomicLong; - -import org.eclipse.rdf4j.common.iteration.DistinctIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; - -/** - * @author Jerven Bolleman, SIB Swiss Institute of Bioinformatics - */ -@Deprecated(since = "4.1.0") -public class LimitedSizeDistinctIteration extends DistinctIteration { - - private final AtomicLong used; - - private final long maxSize; - - /** - * @param iter - */ - public LimitedSizeDistinctIteration(Iteration iter, - AtomicLong used, long maxSize) { - super(iter); - this.used = used; - this.maxSize = maxSize; - } - - @Override - protected boolean add(BindingSet object) throws QueryEvaluationException { - boolean add = super.add(object); - if (add && used.incrementAndGet() > maxSize) { - throw new QueryEvaluationException("Size limited reached inside query operator."); - } - return add; - } - -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/iterator/LimitedSizeIteratorUtil.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/iterator/LimitedSizeIteratorUtil.java deleted file mode 100644 index e9b310ba06a..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/limited/iterator/LimitedSizeIteratorUtil.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.limited.iterator; - -import java.util.Collection; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; - -import org.eclipse.rdf4j.common.iteration.Iteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; - -/** - * @author Jerven Bolleman, SIB Swiss Institute of Bioinformatics - */ -@Deprecated(since = "4.1.0", forRemoval = true) -public class LimitedSizeIteratorUtil { - - /** - * @param arg2 the iteration with elements to add to the includeSet - * @param includeSet the set that should have all unique elements of arg2 - * @param used the collection size counter of all collections used in answering a query - * @param maxSize the point at which we throw a new query exception - * @return the includeSet - * @throws QueryEvaluationException trigerred when maxSize is smaller than the used value - */ - public static Set addAll(Iteration arg2, - Set includeSet, AtomicLong used, long maxSize) throws QueryEvaluationException { - while (arg2.hasNext()) { - if (includeSet.add(arg2.next()) && used.incrementAndGet() > maxSize) { - throw new QueryEvaluationException("Size limited reached inside intersect operator"); - } - } - return includeSet; - } - - /** - * @param object object to put in set if not there already. - * @param excludeSet set that we need to store object in. - * @param used AtomicLong tracking how many elements we have in storage. - * @param maxSize - * @throws QueryEvaluationException when the object is added to the set and the total elements in all limited size - * collections exceed the allowed maxSize. - */ - public static boolean add(V object, Collection excludeSet, AtomicLong used, long maxSize) - throws QueryEvaluationException { - boolean add = excludeSet.add(object); - if (add && used.incrementAndGet() > maxSize) { - throw new QueryEvaluationException("Size limited reached inside query operator."); - } - return add; - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/ConstantOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/ConstantOptimizer.java index d83dff07ac9..675ee395546 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/ConstantOptimizer.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/ConstantOptimizer.java @@ -292,7 +292,7 @@ private boolean isConstantZeroArgFunction(FunctionCall functionCall) { // we treat constant functions as the 'regular case' and make // exceptions for specific SPARQL built-in functions that require // different treatment. - return !(function.mustReturnDifferentResult()); + return !function.mustReturnDifferentResult(); } @Override diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/ParentReferenceChecker.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/ParentReferenceChecker.java index a42a2aed746..05a7d0b97d8 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/ParentReferenceChecker.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/ParentReferenceChecker.java @@ -56,7 +56,7 @@ public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) } verifySerializable(tupleExpr); - tupleExpr.visit(new ParentCheckingVisitor()); + tupleExpr.visit(new ParentCheckingVisitor(ParentReferenceChecker.this.previousOptimizerInPipeline)); } private void verifySerializable(QueryModelNode tupleExpr) { @@ -89,24 +89,24 @@ private Object bytesToObject(byte[] str) { } } - private class ParentCheckingVisitor extends AbstractQueryModelVisitor { + private final static class ParentCheckingVisitor extends AbstractQueryModelVisitor { private final ArrayDeque ancestors = new ArrayDeque<>(); + private final String previousOptimizer; + + public ParentCheckingVisitor(QueryOptimizer previousOptimizerInPipeline) { + if (previousOptimizerInPipeline != null) { + this.previousOptimizer = previousOptimizerInPipeline.getClass().getSimpleName(); + } else + this.previousOptimizer = "query parsing"; + } @Override protected void meetNode(QueryModelNode node) throws RuntimeException { QueryModelNode expectedParent = ancestors.peekLast(); if (node.getParentNode() != expectedParent) { - String previousOptimizer; - if (ParentReferenceChecker.this.previousOptimizerInPipeline != null) { - previousOptimizer = ParentReferenceChecker.this.previousOptimizerInPipeline.getClass() - .getSimpleName(); - } else { - previousOptimizer = "query parsing"; - } String message = "After " + previousOptimizer + " there was an unexpected parent for node " + node + ": " + node.getParentNode() + " (expected " + expectedParent + ")"; - assert node.getParentNode() == expectedParent : message; } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/QueryJoinOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/QueryJoinOptimizer.java index ef1710493bc..c587cac8742 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/QueryJoinOptimizer.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/QueryJoinOptimizer.java @@ -565,27 +565,6 @@ private int countConstantVars(List vars) { return size; } - @Deprecated(forRemoval = true, since = "4.1.0") - protected List getUnboundVars(Iterable vars) { - - List ret = null; - - for (Var var : vars) { - if (!var.hasValue() && var.getName() != null && !boundVars.contains(var.getName())) { - if (ret == null) { - ret = Collections.singletonList(var); - } else { - if (ret.size() == 1) { - ret = new ArrayList<>(ret); - } - ret.add(var); - } - } - } - - return ret != null ? ret : Collections.emptyList(); - } - protected List getUnboundVars(List vars) { int size = vars.size(); if (size == 0) { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/QueryModelNormalizerOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/QueryModelNormalizerOptimizer.java index a86adbd097f..de58215a621 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/QueryModelNormalizerOptimizer.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/QueryModelNormalizerOptimizer.java @@ -86,14 +86,14 @@ public void meet(Join join) { newUnion.setVariableScopeChange(union.isVariableScopeChange()); join.replaceWith(newUnion); newUnion.visit(this); - } else if (leftArg instanceof LeftJoin && isWellDesigned(((LeftJoin) leftArg))) { + } else if (leftArg instanceof LeftJoin && isWellDesigned((LeftJoin) leftArg)) { // sort left join above normal joins LeftJoin leftJoin = (LeftJoin) leftArg; join.replaceWith(leftJoin); join.setLeftArg(leftJoin.getLeftArg()); leftJoin.setLeftArg(join); leftJoin.visit(this); - } else if (rightArg instanceof LeftJoin && isWellDesigned(((LeftJoin) rightArg))) { + } else if (rightArg instanceof LeftJoin && isWellDesigned((LeftJoin) rightArg)) { // sort left join above normal joins LeftJoin leftJoin = (LeftJoin) rightArg; join.replaceWith(leftJoin); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/RegexAsStringFunctionOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/RegexAsStringFunctionOptimizer.java index fcb231b7967..dd3580b3053 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/RegexAsStringFunctionOptimizer.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/RegexAsStringFunctionOptimizer.java @@ -49,11 +49,6 @@ public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) private static class RegexAsStringFunctionVisitor extends AbstractSimpleQueryModelVisitor { private final ValueFactory vf; - @Deprecated(forRemoval = true, since = "4.1.0") - protected RegexAsStringFunctionVisitor() { - vf = SimpleValueFactory.getInstance(); - } - protected RegexAsStringFunctionVisitor(ValueFactory vf) { super(false); this.vf = vf; @@ -112,7 +107,7 @@ private void strendsCandidate(Regex node, String regex) { } private void strstartsCandidate(Regex node, String regex) { - final String potential = regex.substring(1, regex.length()); + final String potential = regex.substring(1); if (plain(potential)) { ValueConstant vc = new ValueConstant(vf.createLiteral(potential)); node.replaceWith(new FunctionCall(FN.STARTS_WITH.stringValue(), node.getArg().clone(), vc)); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/SameTermFilterOptimizer.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/SameTermFilterOptimizer.java index 4f34ab4049b..9c544a84c71 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/SameTermFilterOptimizer.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/optimizer/SameTermFilterOptimizer.java @@ -230,7 +230,7 @@ public VarBinder(String varName, Value value) { @Override public void meet(Var var) { if (var.getName().equals(varName)) { - var.setValue(value); + var.replaceWith(new Var(varName, value, var.isAnonymous(), var.isConstant())); } } } diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/EvaluationStrategies.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/EvaluationStrategies.java deleted file mode 100644 index 83f9b25a420..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/EvaluationStrategies.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.util; - -import java.util.Map; -import java.util.UUID; - -import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; -import org.eclipse.rdf4j.util.UUIDable; - -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; - -/** - * Registry for currently active {@link EvaluationStrategy} objects. The internal registry uses soft references to allow - * entries to be garbage-collected when no longer used. Currently, the primary purpose of this is to support - * (de)serialization of objects (over the lifetime of the VM) that depend on an EvaluationStrategy - * - * @author Jeen Broekstra - */ -@Deprecated(forRemoval = true, since = "4.0.0") -public class EvaluationStrategies { - - private static final Cache registry = CacheBuilder.newBuilder().weakValues().build(); - - /** - * Retrieve the EvaluationStrategy registered with the supplied key. - * - * @param key the key - * @return the registered EvaluationStrategy, or null if no matching EvaluationStrategy can be found. - */ - public static EvaluationStrategy get(UUID key) { - return registry.getIfPresent(key); - } - - /** - * Retrieve the registry key for the given EvaluationStrategy - * - * @param strategy the EvaluationStrategy for which to retrieve the registry key - * @return the registry key with which the supplied strategy can be retrieved, or null if the supplied - * strategy is not in the registry. - */ - public static UUID getKey(EvaluationStrategy strategy) { - Map map = registry.asMap(); - - // we could make this lookup more efficient with a WeakHashMap-based - // reverse index, but we currently prefer this slower but more robust - // approach (less chance of accidental lingering references that prevent - // GC) - for (UUID key : map.keySet()) { - // we use identity comparison in line with how guava caches behave - // when softValues are used. - if (strategy == map.get(key)) { - return key; - } - } - return null; - } - - /** - * Add a strategy to the registry and returns the registry key. If the strategy is already present, the operation - * simply returns the key with which it is currently registered. - * - * @param strategy the EvaluationStrategy to register - * @return the key with which the strategy is registered. - */ - public static UUID register(EvaluationStrategy strategy) { - UUID key; - if (strategy instanceof UUIDable) { - key = ((UUIDable) strategy).getUUID(); - if (get(key) == null) { - registry.put(key, strategy); - } - } else { - key = getKey(strategy); - if (key == null) { - key = UUID.randomUUID(); - registry.put(key, strategy); - } - } - return key; - } - - /** - * Prevent instantiation: util class - */ - private EvaluationStrategies() { - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/OrderComparator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/OrderComparator.java index f21e472ae9f..5086cdb3e6b 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/OrderComparator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/OrderComparator.java @@ -142,8 +142,8 @@ public int compare(BindingSet o1, BindingSet o2) { } // binding set sizes are equal. compare on binding names. - if ((o2bindingNamesOrdered != null && !sortedEquals(o1bindingNamesOrdered, o2bindingNamesOrdered)) - || (!o1.getBindingNames().equals(o2.getBindingNames()))) { + if (o2bindingNamesOrdered != null && !sortedEquals(o1bindingNamesOrdered, o2bindingNamesOrdered) + || !o1.getBindingNames().equals(o2.getBindingNames())) { if (o2bindingNamesOrdered == null) { o2bindingNamesOrdered = getSortedBindingNames(o2.getBindingNames()); diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryEvaluationUtil.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryEvaluationUtil.java index 2e8c09491c4..7f2d6acf1a7 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryEvaluationUtil.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryEvaluationUtil.java @@ -65,7 +65,7 @@ public static boolean getEffectiveBooleanValue(Value value) throws ValueExprEval if (value.isLiteral()) { Literal literal = (Literal) value; String label = literal.getLabel(); - CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatype().orElse(null); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); if (datatype == CoreDatatype.XSD.STRING) { return label.length() > 0; @@ -162,8 +162,8 @@ public static boolean compareLiterals(Literal leftLit, Literal rightLit, Compare // - CoreDatatype.XSD:string // - RDF term (equal and unequal only) - CoreDatatype.XSD leftCoreDatatype = leftLit.getCoreDatatype().asXSDDatatype().orElse(null); - CoreDatatype.XSD rightCoreDatatype = rightLit.getCoreDatatype().asXSDDatatype().orElse(null); + CoreDatatype.XSD leftCoreDatatype = leftLit.getCoreDatatype().asXSDDatatypeOrNull(); + CoreDatatype.XSD rightCoreDatatype = rightLit.getCoreDatatype().asXSDDatatypeOrNull(); boolean leftLangLit = Literals.isLanguageLiteral(leftLit); boolean rightLangLit = Literals.isLanguageLiteral(rightLit); @@ -432,13 +432,13 @@ private static boolean compareWithOperator(CompareOp operator, int i) { */ public static boolean isPlainLiteral(Value v) { if (v.isLiteral()) { - return isPlainLiteral(((Literal) v)); + return isPlainLiteral((Literal) v); } return false; } public static boolean isPlainLiteral(Literal l) { - assert l.getLanguage().isEmpty() || (l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING); + assert l.getLanguage().isEmpty() || l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING; return l.getCoreDatatype() == CoreDatatype.XSD.STRING || l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING; } @@ -510,10 +510,10 @@ public static boolean compatibleArguments(Literal arg1, Literal arg2) { // 3. The first argument is a language literal and the second // argument is a literal typed as CoreDatatype.XSD:string - return (isSimpleLiteral(arg1) && isSimpleLiteral(arg2)) - || (Literals.isLanguageLiteral(arg1) && Literals.isLanguageLiteral(arg2) - && arg1.getLanguage().equals(arg2.getLanguage())) - || (Literals.isLanguageLiteral(arg1) && isSimpleLiteral(arg2)); + return isSimpleLiteral(arg1) && isSimpleLiteral(arg2) + || Literals.isLanguageLiteral(arg1) && Literals.isLanguageLiteral(arg2) + && arg1.getLanguage().equals(arg2.getLanguage()) + || Literals.isLanguageLiteral(arg1) && isSimpleLiteral(arg2); } /** diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryEvaluationUtility.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryEvaluationUtility.java index fca43bbd49b..ea04b96990d 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryEvaluationUtility.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryEvaluationUtility.java @@ -56,7 +56,7 @@ public static Result getEffectiveBooleanValue(Value value) { if (value.isLiteral()) { Literal literal = (Literal) value; String label = literal.getLabel(); - CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatype().orElse(null); + CoreDatatype.XSD datatype = literal.getCoreDatatype().asXSDDatatypeOrNull(); if (datatype == CoreDatatype.XSD.STRING) { return Result.fromBoolean(label.length() > 0); @@ -333,13 +333,13 @@ private static CoreDatatype.XSD getCommonDatatype(boolean strict, CoreDatatype.X */ public static boolean isPlainLiteral(Value v) { if (v.isLiteral()) { - return isPlainLiteral(((Literal) v)); + return isPlainLiteral((Literal) v); } return false; } public static boolean isPlainLiteral(Literal l) { - assert l.getLanguage().isEmpty() || (l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING); + assert l.getLanguage().isEmpty() || l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING; return l.getCoreDatatype() == CoreDatatype.XSD.STRING || l.getCoreDatatype() == CoreDatatype.RDF.LANGSTRING; } @@ -411,10 +411,10 @@ public static boolean compatibleArguments(Literal arg1, Literal arg2) { // 3. The first argument is a language literal and the second // argument is a literal typed as CoreDatatype.XSD:string - return (isSimpleLiteral(arg1) && isSimpleLiteral(arg2)) - || (Literals.isLanguageLiteral(arg1) && Literals.isLanguageLiteral(arg2) - && arg1.getLanguage().equals(arg2.getLanguage())) - || (Literals.isLanguageLiteral(arg1) && isSimpleLiteral(arg2)); + return isSimpleLiteral(arg1) && isSimpleLiteral(arg2) + || Literals.isLanguageLiteral(arg1) && Literals.isLanguageLiteral(arg2) + && arg1.getLanguage().equals(arg2.getLanguage()) + || Literals.isLanguageLiteral(arg1) && isSimpleLiteral(arg2); } /** diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryOptimizerList.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryOptimizerList.java deleted file mode 100644 index c005bb95e80..00000000000 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/QueryOptimizerList.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.util; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizer; - -/** - * A query optimizer that contains a list of other query optimizers, which are called consecutively when the list's - * {@link #optimize(TupleExpr, Dataset, BindingSet)} method is called. - * - * @author Arjohn Kampman - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class QueryOptimizerList implements QueryOptimizer { - - protected List optimizers; - - public QueryOptimizerList() { - this.optimizers = new ArrayList<>(8); - } - - public QueryOptimizerList(List optimizers) { - this.optimizers = new ArrayList<>(optimizers); - } - - public QueryOptimizerList(QueryOptimizer... optimizers) { - this.optimizers = new ArrayList<>(optimizers.length); - for (QueryOptimizer optimizer : optimizers) { - this.optimizers.add(optimizer); - } - } - - public void add(QueryOptimizer optimizer) { - optimizers.add(optimizer); - } - - @Override - public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) { - for (QueryOptimizer optimizer : optimizers) { - optimizer.optimize(tupleExpr, dataset, bindings); - } - } -} diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/TripleSources.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/TripleSources.java index 3a058edb3bc..e4b8177fbdb 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/TripleSources.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/TripleSources.java @@ -13,7 +13,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.ConvertingIteration; import org.eclipse.rdf4j.common.iteration.FilterIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Resource; @@ -31,7 +30,8 @@ */ // TODO this duplicates a lot of functionality already found in classes like Models and RDFCollections. // Closer integration and/or rewriting of these utilities may be required. -@Deprecated(since = "4.1.0", forRemoval = true) +@Deprecated(since = "4.1.0", forRemoval = true) // there is still a decent amount of work left before this class can be + // removed public class TripleSources { private static final ValueFactory vf = SimpleValueFactory.getInstance(); @@ -39,14 +39,14 @@ public class TripleSources { TripleSources() { } - public static Iteration listResources(final Resource subj, + public static CloseableIteration listResources(final Resource subj, final TripleSource store) throws QueryEvaluationException { - return new ConvertingIteration( - new FilterIteration(list(subj, store)) { + return new ConvertingIteration<>( + new FilterIteration(list(subj, store)) { @Override protected boolean accept(Value v) throws QueryEvaluationException { - return (v instanceof Resource); + return v instanceof Resource; } }) { @@ -57,12 +57,12 @@ protected Resource convert(Value v) throws QueryEvaluationException { }; } - public static Iteration list(final Resource subj, + public static CloseableIteration list(final Resource subj, final TripleSource store) throws QueryEvaluationException { if (subj == null) { throw new NullPointerException("RDF list subject cannot be null"); } - return new Iteration() { + return new CloseableIteration<>() { Resource list = subj; @@ -89,6 +89,11 @@ public Value next() throws QueryEvaluationException { public void remove() throws QueryEvaluationException { throw new UnsupportedOperationException(); } + + @Override + public void close() { + // no-op + } }; } @@ -110,7 +115,7 @@ public static boolean booleanValue(Resource subj, IRI pred, TripleSource store) public static Value singleValue(Resource subj, IRI pred, TripleSource store) throws QueryEvaluationException { Statement stmt = single(subj, pred, null, store); - return (stmt != null) ? stmt.getObject() : null; + return stmt != null ? stmt.getObject() : null; } /** @@ -125,7 +130,7 @@ public static Value singleValue(Resource subj, IRI pred, TripleSource store) thr public static Statement single(Resource subj, IRI pred, Value obj, TripleSource store) throws QueryEvaluationException { Statement stmt; - try (CloseableIteration stmts = store.getStatements(subj, pred, + try (CloseableIteration stmts = store.getStatements(subj, pred, obj)) { if (stmts.hasNext()) { stmt = stmts.next(); @@ -143,14 +148,14 @@ public static Statement single(Resource subj, IRI pred, Value obj, TripleSource return stmt; } - public static CloseableIteration getSubjectURIs(IRI predicate, + public static CloseableIteration getSubjectURIs(IRI predicate, Value object, TripleSource store) throws QueryEvaluationException { - return new ConvertingIteration( - new FilterIteration(store.getStatements(null, predicate, object)) { + return new ConvertingIteration<>( + new FilterIteration(store.getStatements(null, predicate, object)) { @Override protected boolean accept(Statement stmt) throws QueryEvaluationException { - return (stmt.getSubject() instanceof IRI); + return stmt.getSubject() instanceof IRI; } }) { @@ -161,15 +166,15 @@ protected IRI convert(Statement stmt) throws QueryEvaluationException { }; } - public static CloseableIteration getObjectResources(Resource subject, + public static CloseableIteration getObjectResources(Resource subject, IRI predicate, TripleSource store) throws QueryEvaluationException { - return new ConvertingIteration( - new FilterIteration( + return new ConvertingIteration<>( + new FilterIteration( store.getStatements(subject, predicate, null)) { @Override protected boolean accept(Statement stmt) throws QueryEvaluationException { - return (stmt.getObject() instanceof Resource); + return stmt.getObject() instanceof Resource; } }) { @@ -180,15 +185,15 @@ protected Resource convert(Statement stmt) throws QueryEvaluationException { }; } - public static CloseableIteration getObjectURIs(Resource subject, + public static CloseableIteration getObjectURIs(Resource subject, IRI predicate, TripleSource store) throws QueryEvaluationException { - return new ConvertingIteration( - new FilterIteration( + return new ConvertingIteration<>( + new FilterIteration( store.getStatements(subject, predicate, null)) { @Override protected boolean accept(Statement stmt) throws QueryEvaluationException { - return (stmt.getObject() instanceof IRI); + return stmt.getObject() instanceof IRI; } }) { @@ -199,15 +204,15 @@ protected IRI convert(Statement stmt) throws QueryEvaluationException { }; } - public static CloseableIteration getObjectLiterals(Resource subject, + public static CloseableIteration getObjectLiterals(Resource subject, IRI predicate, TripleSource store) throws QueryEvaluationException { - return new ConvertingIteration( - new FilterIteration( + return new ConvertingIteration<>( + new FilterIteration( store.getStatements(subject, predicate, null)) { @Override protected boolean accept(Statement stmt) throws QueryEvaluationException { - return (stmt.getObject() instanceof Literal); + return stmt.getObject() instanceof Literal; } }) { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/ValueComparator.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/ValueComparator.java index c01a7f9e8f6..fc5b709e004 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/ValueComparator.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/ValueComparator.java @@ -145,8 +145,8 @@ private int comparePlainLiterals(Literal leftLit, Literal rightLit) { if (leftDatatype != null) { if (rightDatatype != null) { // Both literals have datatypes - CoreDatatype.XSD leftXmlDatatype = leftLit.getCoreDatatype().asXSDDatatype().orElse(null); - CoreDatatype.XSD rightXmlDatatype = rightLit.getCoreDatatype().asXSDDatatype().orElse(null); + CoreDatatype.XSD leftXmlDatatype = leftLit.getCoreDatatype().asXSDDatatypeOrNull(); + CoreDatatype.XSD rightXmlDatatype = rightLit.getCoreDatatype().asXSDDatatypeOrNull(); result = compareDatatypes(leftXmlDatatype, rightXmlDatatype, leftDatatype, rightDatatype); if (result != 0) { diff --git a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/XMLDatatypeMathUtil.java b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/XMLDatatypeMathUtil.java index bfd0f1c4aea..812a6198250 100644 --- a/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/XMLDatatypeMathUtil.java +++ b/core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/util/XMLDatatypeMathUtil.java @@ -53,8 +53,8 @@ public static Literal compute(Literal leftLit, Literal rightLit, MathOp op) thro */ public static Literal compute(Literal leftLit, Literal rightLit, MathOp op, ValueFactory vf) throws ValueExprEvaluationException { - CoreDatatype.XSD leftDatatype = leftLit.getCoreDatatype().asXSDDatatype().orElse(null); - CoreDatatype.XSD rightDatatype = rightLit.getCoreDatatype().asXSDDatatype().orElse(null); + CoreDatatype.XSD leftDatatype = leftLit.getCoreDatatype().asXSDDatatypeOrNull(); + CoreDatatype.XSD rightDatatype = rightLit.getCoreDatatype().asXSDDatatypeOrNull(); if (leftDatatype != null && rightDatatype != null) { if (leftDatatype.isNumericDatatype() && rightDatatype.isNumericDatatype()) { diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/NowTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/NowTest.java index 07e0282c401..251e79e7e54 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/NowTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/NowTest.java @@ -33,18 +33,16 @@ public class NowTest { private ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { now = new Now(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/TimezoneTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/TimezoneTest.java index 770350fedf7..073224f4a83 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/TimezoneTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/TimezoneTest.java @@ -33,18 +33,16 @@ public class TimezoneTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { timezone = new Timezone(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/TzTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/TzTest.java index b907d48d95d..cc163aaa10e 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/TzTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/datetime/TzTest.java @@ -33,18 +33,16 @@ public class TzTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { tz = new Tz(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/HashLeadingZeroTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/HashLeadingZeroTest.java index 970b0385505..f510c96fa80 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/HashLeadingZeroTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/HashLeadingZeroTest.java @@ -20,10 +20,9 @@ public class HashLeadingZeroTest extends HashFunctionTest { * Test if hash function adds multiple leading zeros (if needed). Test value and expected result provided by Vassil * Momtchev.. * - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { setHashFunction(new MD5()); setToHash("363"); setExpectedDigest("00411460f7c92d2124a67ea0f4cb5f85"); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/MD5Test.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/MD5Test.java index 6c52040a304..480e07c2a90 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/MD5Test.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/MD5Test.java @@ -18,10 +18,9 @@ public class MD5Test extends HashFunctionTest { /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { setHashFunction(new MD5()); setToHash("abc"); setExpectedDigest("900150983cd24fb0d6963f7d28e17f72"); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA1Test.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA1Test.java index f717b286a0a..e973836fd6f 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA1Test.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA1Test.java @@ -18,10 +18,9 @@ public class SHA1Test extends HashFunctionTest { /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { setHashFunction(new SHA1()); setToHash("abc"); setExpectedDigest("a9993e364706816aba3e25717850c26c9cd0d89d"); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA256Test.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA256Test.java index f7c3ee27a45..b8807bcdfb7 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA256Test.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA256Test.java @@ -18,10 +18,9 @@ public class SHA256Test extends HashFunctionTest { /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { setHashFunction(new SHA256()); setToHash("abc"); setExpectedDigest("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA384Test.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA384Test.java index 8f4fa0ed97e..22e8c2fb2c7 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA384Test.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA384Test.java @@ -18,10 +18,9 @@ public class SHA384Test extends HashFunctionTest { /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { setHashFunction(new SHA384()); setToHash("abc"); setExpectedDigest( diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA512Test.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA512Test.java index 641e6945043..f0402c95889 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA512Test.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/SHA512Test.java @@ -18,10 +18,9 @@ public class SHA512Test extends HashFunctionTest { /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { setHashFunction(new SHA512()); setToHash("abc"); setExpectedDigest( diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/RandTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/RandTest.java index 9c967c99e0d..9e90bc7917c 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/RandTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/RandTest.java @@ -50,18 +50,16 @@ public class RandTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { rand = new Rand(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test @@ -92,7 +90,7 @@ public ValueFactory getValueFactory() { } @Override - public CloseableIteration getStatements(Resource subj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { // TODO Auto-generated method stub return null; diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/RoundTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/RoundTest.java index e2884ad16a2..a52dfbdb0d3 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/RoundTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/numeric/RoundTest.java @@ -34,18 +34,16 @@ public class RoundTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { round = new Round(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test @@ -56,7 +54,7 @@ public void testEvaluateDouble() { double roundValue = rounded.doubleValue(); - assertEquals((double) 2.0, roundValue, 0.001d); + assertEquals(2.0, roundValue, 0.001d); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/ConcatTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/ConcatTest.java index b45b493f7e9..9286d14d973 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/ConcatTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/ConcatTest.java @@ -40,7 +40,7 @@ public class ConcatTest { private static final Literal foo_nl = vf.createLiteral("foo", "nl"); @BeforeEach - public void setUp() throws Exception { + public void setUp() { concatFunc = new Concat(); } diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/LowerCaseTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/LowerCaseTest.java index cd447b76700..b31fb70aab7 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/LowerCaseTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/LowerCaseTest.java @@ -31,18 +31,16 @@ public class LowerCaseTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { lcaseFunc = new LowerCase(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/ReplaceTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/ReplaceTest.java index 167ef721b85..1a74d5d80eb 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/ReplaceTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/ReplaceTest.java @@ -31,18 +31,16 @@ public class ReplaceTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { replaceFunc = new Replace(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrAfterTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrAfterTest.java index bac3cf51460..8fb1538797a 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrAfterTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrAfterTest.java @@ -34,18 +34,16 @@ public class StrAfterTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { strAfterFunc = new StrAfter(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrBeforeTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrBeforeTest.java index 888633271b9..0e14d8eb189 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrBeforeTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/StrBeforeTest.java @@ -34,18 +34,16 @@ public class StrBeforeTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { strBeforeFunc = new StrBefore(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/SubstringTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/SubstringTest.java index 2959bd34007..aad46b824a0 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/SubstringTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/SubstringTest.java @@ -32,18 +32,16 @@ public class SubstringTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { substrFunc = new Substring(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/UpperCaseTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/UpperCaseTest.java index b55122fae2e..9bda384332b 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/UpperCaseTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/string/UpperCaseTest.java @@ -31,18 +31,16 @@ public class UpperCaseTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { ucaseFunc = new UpperCase(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/IsTripleFunctionTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/IsTripleFunctionTest.java index 45c2a281f04..eef798970de 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/IsTripleFunctionTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/IsTripleFunctionTest.java @@ -37,18 +37,16 @@ public class IsTripleFunctionTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { function = new IsTripleFunction(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/StatementFunctionTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/StatementFunctionTest.java index c9b314a33e4..b491dd19312 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/StatementFunctionTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/StatementFunctionTest.java @@ -40,18 +40,16 @@ public class StatementFunctionTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { function = new StatementFunction(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TripleObjectFunctionTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TripleObjectFunctionTest.java index 5debe44177f..79a453a3ae4 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TripleObjectFunctionTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TripleObjectFunctionTest.java @@ -37,18 +37,16 @@ public class TripleObjectFunctionTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { function = new TripleObjectFunction(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TriplePredicateFunctionTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TriplePredicateFunctionTest.java index 0f9d8f2d8d5..e0cd78cccc1 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TriplePredicateFunctionTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TriplePredicateFunctionTest.java @@ -37,18 +37,16 @@ public class TriplePredicateFunctionTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { function = new TriplePredicateFunction(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TripleSubjectFunctionTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TripleSubjectFunctionTest.java index 2e82add1961..48e2bf397f3 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TripleSubjectFunctionTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/triple/TripleSubjectFunctionTest.java @@ -37,18 +37,16 @@ public class TripleSubjectFunctionTest { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { function = new TripleSubjectFunction(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestDateTimeCast.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestDateTimeCast.java index 81622f40b04..e9a99c9d666 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestDateTimeCast.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestDateTimeCast.java @@ -35,18 +35,16 @@ public class TestDateTimeCast { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { dtCast = new DateTimeCast(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestIntegerDatatypeCast.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestIntegerDatatypeCast.java index bf1cf90e0a8..dfcea454c71 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestIntegerDatatypeCast.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestIntegerDatatypeCast.java @@ -35,7 +35,7 @@ public abstract class TestIntegerDatatypeCast { @Test public void testCastBelowMinValue() { - getMinValue().ifPresent((min) -> { + getMinValue().ifPresent(min -> { BigInteger below = min.subtract(BigInteger.ONE); try { getCastFunction().evaluate(vf, vf.createLiteral(below)); @@ -48,7 +48,7 @@ public void testCastBelowMinValue() { @Test public void testCastAboveMaxValue() { - getMaxValue().ifPresent((max) -> { + getMaxValue().ifPresent(max -> { BigInteger above = max.add(BigInteger.ONE); try { getCastFunction().evaluate(vf, vf.createLiteral(above)); @@ -88,7 +88,7 @@ public void testCastPositiveDouble() { try { Literal result = getCastFunction().evaluate(vf, dbl); assertNotNull(result); - assertEquals(getCastFunction().getXsdDatatype(), result.getDatatype()); + assertEquals(getCastFunction().getCoreXsdDatatype(), result.getCoreDatatype()); assertEquals(100, result.intValue()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); @@ -104,7 +104,7 @@ public void testCastPositiveDoubleWithLargeFraction() { try { Literal result = getCastFunction().evaluate(vf, dbl); assertNotNull(result); - assertEquals(getCastFunction().getXsdDatatype(), result.getDatatype()); + assertEquals(getCastFunction().getCoreXsdDatatype(), result.getCoreDatatype()); assertEquals(100, result.intValue()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestStringCast.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestStringCast.java index 94a1cfd7453..983c9129b32 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestStringCast.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/function/xsd/TestStringCast.java @@ -35,18 +35,16 @@ public class TestStringCast { private final ValueFactory f = SimpleValueFactory.getInstance(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { stringCast = new StringCast(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConstantOptimizerTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConstantOptimizerTest.java index d23ad0ecf88..b9110523dfe 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConstantOptimizerTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/ConstantOptimizerTest.java @@ -20,7 +20,6 @@ import org.eclipse.rdf4j.model.impl.BooleanLiteral; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.algebra.And; import org.eclipse.rdf4j.query.algebra.FunctionCall; @@ -31,7 +30,7 @@ import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizerTest; import org.eclipse.rdf4j.query.algebra.evaluation.optimizer.BindingAssignerOptimizer; import org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ConstantOptimizer; -import org.eclipse.rdf4j.query.algebra.helpers.QueryModelVisitorBase; +import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; import org.eclipse.rdf4j.query.impl.EmptyBindingSet; import org.eclipse.rdf4j.query.parser.ParsedQuery; import org.eclipse.rdf4j.query.parser.QueryParserUtil; @@ -67,8 +66,7 @@ public void testAndOptimization() throws RDF4JException { optimized.visit(finder); assertThat(finder.logicalAndfound).isFalse(); - CloseableIteration result = strategy.evaluate(optimized, - new EmptyBindingSet()); + CloseableIteration result = strategy.precompile(optimized).evaluate(new EmptyBindingSet()); assertNotNull(result); assertTrue(result.hasNext()); BindingSet bindings = result.next(); @@ -102,8 +100,9 @@ public void testFunctionOptimization() throws RDF4JException { optimized.visit(finder); assertThat(finder.functionCallFound).isFalse(); - CloseableIteration result = strategy.evaluate(optimized, - new EmptyBindingSet()); + CloseableIteration result = strategy.precompile(optimized) + .evaluate( + new EmptyBindingSet()); assertNotNull(result); assertTrue(result.hasNext()); BindingSet bindings = result.next(); @@ -113,7 +112,7 @@ public void testFunctionOptimization() throws RDF4JException { } - private class AlgebraFinder extends QueryModelVisitorBase { + private class AlgebraFinder extends AbstractQueryModelVisitor { public boolean logicalAndfound = false; diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EmptyTripleSource.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EmptyTripleSource.java index 1c7fe009b69..76d2b78cffe 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EmptyTripleSource.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EmptyTripleSource.java @@ -39,7 +39,7 @@ public ValueFactory getValueFactory() { } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { return new EmptyIteration<>(); } diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStatisticsTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStatisticsTest.java index 168c4b6c196..6fa2a954de7 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStatisticsTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStatisticsTest.java @@ -32,7 +32,7 @@ public class EvaluationStatisticsTest { @Test - public void testGetCardinality_ParentReferences() throws Exception { + public void testGetCardinality_ParentReferences() { ParsedTupleQuery query = QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, "select * where {?a ?b ?c. ?c * ?d}", null); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStrategyWithRDFStarTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStrategyWithRDFStarTest.java index 65108a2f69a..00eedda651a 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStrategyWithRDFStarTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/EvaluationStrategyWithRDFStarTest.java @@ -64,10 +64,10 @@ public class EvaluationStrategyWithRDFStarTest { * @author damyan.ognyanov */ class CommonBaseSource { - public CloseableIteration getRdfStarTriples(Resource subj, + public CloseableIteration getRdfStarTriples(Resource subj, IRI pred, Value obj) throws QueryEvaluationException { - return new AbstractCloseableIteration() { + return new AbstractCloseableIteration() { final Iterator iter = triples.iterator(); @Override @@ -89,7 +89,7 @@ public void remove() }; } - public CloseableIteration getStatements(Resource subj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { // handle only arguments with reification vocabulary @@ -97,7 +97,7 @@ public CloseableIteration getStat // handle (*, rdf:type, rdf:Statement) if (pred != null && pred.equals(RDF.TYPE) && obj != null && obj.equals(RDF.STATEMENT)) { - return new ConvertingIteration( + return new ConvertingIteration( getRdfStarTriples(null, null, null)) { @Override protected Statement convert(Triple sourceObject) @@ -107,7 +107,7 @@ protected Statement convert(Triple sourceObject) }; } else if (pred != null && pred.equals(RDF.SUBJECT)) { // handle (*, rdf:subject, *) - return new ConvertingIteration( + return new ConvertingIteration( getRdfStarTriples(null, null, null)) { @Override protected Statement convert(Triple sourceObject) @@ -117,7 +117,7 @@ protected Statement convert(Triple sourceObject) }; } else if (pred != null && pred.equals(RDF.PREDICATE)) { // handle (*, rdf:predicate, *) - return new ConvertingIteration( + return new ConvertingIteration( getRdfStarTriples(null, null, null)) { @Override protected Statement convert(Triple sourceObject) @@ -127,7 +127,7 @@ protected Statement convert(Triple sourceObject) }; } else if (pred != null && pred.equals(RDF.OBJECT)) { // handle (*, rdf:object, *) - return new ConvertingIteration( + return new ConvertingIteration( getRdfStarTriples(null, null, null)) { @Override protected Statement convert(Triple sourceObject) @@ -143,7 +143,7 @@ protected Statement convert(Triple sourceObject) } @BeforeEach - public void setUp() throws Exception { + public void setUp() { // prepare data triples.clear(); triples.add(vf.createTriple(vf.createIRI("urn:a"), vf.createIRI("urn:p"), vf.createIRI("urn:b"))); @@ -171,14 +171,14 @@ public ValueFactory getValueFactory() { } @Override - public CloseableIteration getStatements(Resource subj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { return baseSource.getStatements(subj, pred, obj, contexts); } @Override - public CloseableIteration getRdfStarTriples(Resource subj, + public CloseableIteration getRdfStarTriples(Resource subj, IRI pred, Value obj) throws QueryEvaluationException { return baseSource.getRdfStarTriples(subj, pred, obj); @@ -192,7 +192,7 @@ public ValueFactory getValueFactory() { } @Override - public CloseableIteration getStatements(Resource subj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { return baseSource.getStatements(subj, pred, obj, contexts); @@ -206,8 +206,9 @@ public CloseableIteration getStat public void testMatchAllUnbound(boolean bRDFStarData) { EvaluationStrategy strategy = new StrictEvaluationStrategy(createSource(bRDFStarData), null); // case check all unbound - try (CloseableIteration iter = strategy.evaluate(tripleRefNode, - new EmptyBindingSet())) { + try (CloseableIteration iter = strategy.precompile(tripleRefNode) + .evaluate( + new EmptyBindingSet())) { ArrayList expected = new ArrayList<>(); triples.forEach(t -> { expected.add(fromTriple(t)); @@ -225,8 +226,9 @@ public void testMatchAllUnbound(boolean bRDFStarData) { @ValueSource(booleans = { false, true }) public void testSubjVarBound(boolean bRDFStarData) { EvaluationStrategy strategy = new StrictEvaluationStrategy(createSource(bRDFStarData), null); - try (CloseableIteration iter = strategy.evaluate(tripleRefNode, - createWithVarValue(tripleRefNode.getSubjectVar(), vf.createIRI("urn:a")))) { + try (CloseableIteration iter = strategy.precompile(tripleRefNode) + .evaluate( + createWithVarValue(tripleRefNode.getSubjectVar(), vf.createIRI("urn:a")))) { ArrayList expected = new ArrayList<>(); triples.forEach(t -> { if (t.getSubject().equals(vf.createIRI("urn:a"))) { @@ -246,8 +248,9 @@ public void testSubjVarBound(boolean bRDFStarData) { @ValueSource(booleans = { false, true }) public void testPredVarBound(boolean bRDFStarData) { EvaluationStrategy strategy = new StrictEvaluationStrategy(createSource(bRDFStarData), null); - try (CloseableIteration iter = strategy.evaluate(tripleRefNode, - createWithVarValue(tripleRefNode.getPredicateVar(), vf.createIRI("urn:p")))) { + try (CloseableIteration iter = strategy.precompile(tripleRefNode) + .evaluate( + createWithVarValue(tripleRefNode.getPredicateVar(), vf.createIRI("urn:p")))) { ArrayList expected = new ArrayList<>(); triples.forEach(t -> { @@ -268,8 +271,9 @@ public void testPredVarBound(boolean bRDFStarData) { @ValueSource(booleans = { false, true }) public void testObjVarBound(boolean bRDFStarData) { EvaluationStrategy strategy = new StrictEvaluationStrategy(createSource(bRDFStarData), null); - try (CloseableIteration iter = strategy.evaluate(tripleRefNode, - createWithVarValue(tripleRefNode.getObjectVar(), vf.createIRI("urn:b")))) { + try (CloseableIteration iter = strategy.precompile(tripleRefNode) + .evaluate( + createWithVarValue(tripleRefNode.getObjectVar(), vf.createIRI("urn:b")))) { ArrayList expected = new ArrayList<>(); triples.forEach(t -> { @@ -293,7 +297,7 @@ public void testSubjAndObjVarBound(boolean bRDFStarData) { set.addBinding(tripleRefNode.getSubjectVar().getName(), vf.createIRI("urn:a:2")); EvaluationStrategy strategy = new StrictEvaluationStrategy(createSource(bRDFStarData), null); - try (CloseableIteration iter = strategy.evaluate(tripleRefNode, set)) { + try (CloseableIteration iter = strategy.precompile(tripleRefNode).evaluate(set)) { ArrayList expected = new ArrayList<>(); triples.forEach(t -> { @@ -317,7 +321,7 @@ public void testExtVarBound(boolean bRDFStarData) { QueryBindingSet set = (QueryBindingSet) createWithVarValue(tripleRefNode.getExprVar(), triple); EvaluationStrategy strategy = new StrictEvaluationStrategy(createSource(bRDFStarData), null); - try (CloseableIteration iter = strategy.evaluate(tripleRefNode, set)) { + try (CloseableIteration iter = strategy.precompile(tripleRefNode).evaluate(set)) { ArrayList expected = new ArrayList<>(); expected.add(fromTriple(triple)); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryJoinOptimizerTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryJoinOptimizerTest.java index 92c0ea69678..11a47b1fc58 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryJoinOptimizerTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryJoinOptimizerTest.java @@ -94,7 +94,7 @@ protected void meetUnaryTupleOperator(UnaryTupleOperator node) throws Exception } @Test - public void testSES2116JoinBind() throws Exception { + public void testSES2116JoinBind() { StringBuilder qb = new StringBuilder(); qb.append("SELECT ?subject ?name ?row {\n" + " ?subject ?uri .\n" @@ -112,7 +112,7 @@ public void testSES2116JoinBind() throws Exception { } @Test - public void bindSubselectJoinOrder() throws Exception { + public void bindSubselectJoinOrder() { String query = "SELECT * WHERE {\n" + " BIND (bnode() as ?ct01) \n" + " { SELECT ?s WHERE {\n" + " ?s ?p ?o .\n" + " }\n" + " LIMIT 10\n" + " }\n" + "}"; diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelNormalizerTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelNormalizerTest.java index 72f123fd1fe..c3339c6ed1f 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelNormalizerTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/QueryModelNormalizerTest.java @@ -26,7 +26,7 @@ public class QueryModelNormalizerTest extends QueryOptimizerTest { private QueryModelNormalizerOptimizer subject; @BeforeEach - public void setup() throws Exception { + public void setup() { subject = getOptimizer(); } diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/StrictEvaluationStrategyTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/StrictEvaluationStrategyTest.java index 53c4a5061af..868e2dc2336 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/StrictEvaluationStrategyTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/StrictEvaluationStrategyTest.java @@ -51,7 +51,7 @@ public class StrictEvaluationStrategyTest { private EvaluationStrategy strategy; @BeforeEach - public void setUp() throws Exception { + public void setUp() { strategy = new StrictEvaluationStrategy(new EmptyTripleSource(), null); } @@ -59,7 +59,7 @@ public void setUp() throws Exception { * Verifies if only those input bindings that actually occur in the query are returned in the result. See SES-2373. */ @Test - public void testBindings() throws Exception { + public void testBindings() { String query = "SELECT ?a ?b WHERE {}"; ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); @@ -70,8 +70,9 @@ public void testBindings() throws Exception { constants.addBinding("x", vf.createLiteral("X")); constants.addBinding("y", vf.createLiteral("Y")); - CloseableIteration result = strategy.evaluate(pq.getTupleExpr(), - constants); + CloseableIteration result = strategy.precompile(pq.getTupleExpr()) + .evaluate( + constants); assertNotNull(result); assertTrue(result.hasNext()); BindingSet bs = result.next(); @@ -82,7 +83,7 @@ public void testBindings() throws Exception { } @Test - public void testOptimize() throws Exception { + public void testOptimize() { QueryOptimizer optimizer1 = mock(QueryOptimizer.class); QueryOptimizer optimizer2 = mock(QueryOptimizer.class); @@ -99,7 +100,7 @@ public void testOptimize() throws Exception { } @Test - public void testEvaluateRegexFlags() throws Exception { + public void testEvaluateRegexFlags() { String query = "SELECT ?a WHERE { " + "VALUES ?a { \"foo.bar\" \"foo bar\" } \n" @@ -107,8 +108,8 @@ public void testEvaluateRegexFlags() throws Exception { ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); - CloseableIteration result = strategy.evaluate(pq.getTupleExpr(), - new EmptyBindingSet()); + CloseableIteration result = strategy.precompile(pq.getTupleExpr()) + .evaluate(EmptyBindingSet.getInstance()); List bindingSets = QueryResults.asList(result); assertThat(bindingSets).hasSize(2); @@ -120,8 +121,7 @@ public void testEvaluateRegexFlags() throws Exception { pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); - result = strategy.evaluate(pq.getTupleExpr(), - new EmptyBindingSet()); + result = strategy.precompile(pq.getTupleExpr()).evaluate(EmptyBindingSet.getInstance()); bindingSets = QueryResults.asList(result); assertThat(bindingSets).hasSize(1); @@ -134,8 +134,9 @@ public void testEvaluateRegexFlags() throws Exception { pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); - result = strategy.evaluate(pq.getTupleExpr(), - new EmptyBindingSet()); + result = strategy.precompile(pq.getTupleExpr()) + .evaluate( + new EmptyBindingSet()); bindingSets = QueryResults.asList(result); assertThat(bindingSets).hasSize(2); @@ -170,7 +171,7 @@ public void testNow() { ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); QueryEvaluationStep prepared = strategy.precompile(pq.getTupleExpr()); assertNotNull(prepared); - try (CloseableIteration evaluate = prepared + try (CloseableIteration evaluate = prepared .evaluate(EmptyBindingSet.getInstance())) { assertTrue(evaluate.hasNext()); BindingSet next = evaluate.next(); @@ -191,7 +192,7 @@ public void testDatetimeCast() { ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); QueryEvaluationStep prepared = strategy.precompile(pq.getTupleExpr()); assertNotNull(prepared); - try (CloseableIteration result = prepared + try (CloseableIteration result = prepared .evaluate(EmptyBindingSet.getInstance())) { assertNotNull(result); assertTrue(result.hasNext()); @@ -203,12 +204,12 @@ public void testDatetimeCast() { } @Test - public void testSES1991NOWEvaluation() throws Exception { + public void testSES1991NOWEvaluation() { String query = "PREFIX ex: SELECT ?d WHERE {VALUES(?s ?p ?o) {(ex:type rdf:type ex:type)(ex:type ex:type ex:type)} . BIND(NOW() as ?d) } LIMIT 2"; ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); QueryEvaluationStep prepared = strategy.precompile(pq.getTupleExpr()); - try (CloseableIteration result = prepared + try (CloseableIteration result = prepared .evaluate(EmptyBindingSet.getInstance())) { assertNotNull(result); assertTrue(result.hasNext()); @@ -233,7 +234,7 @@ public void testSES869ValueOfNow() { "SELECT ?p ( NOW() as ?n ) { BIND (NOW() as ?p ) }", null); QueryEvaluationStep prepared = strategy.precompile(pq.getTupleExpr()); - try (CloseableIteration result = prepared + try (CloseableIteration result = prepared .evaluate(EmptyBindingSet.getInstance())) { assertNotNull(result); assertTrue(result.hasNext()); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/UnionScopeChangeOptimizerTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/UnionScopeChangeOptimizerTest.java index c839d6ab8b6..82918a5a70d 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/UnionScopeChangeOptimizerTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/impl/UnionScopeChangeOptimizerTest.java @@ -28,7 +28,7 @@ public class UnionScopeChangeOptimizerTest extends QueryOptimizerTest { private Union union; @BeforeEach - public void setup() throws Exception { + public void setup() { subject = getOptimizer(); union = new Union(); union.setVariableScopeChange(true); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/BindingSetSize.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/BindingSetSize.java deleted file mode 100644 index e6a44710451..00000000000 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/BindingSetSize.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.iterator; - -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.query.Binding; -import org.eclipse.rdf4j.query.BindingSet; - -class BindingSetSize implements BindingSet { - - private static final long serialVersionUID = -7968068342865378845L; - - private final int size; - - public BindingSetSize(int size) { - super(); - this.size = size; - } - - @Override - public Binding getBinding(String bindingName) { - throw new UnsupportedOperationException(); - } - - @Override - public Set getBindingNames() { - throw new UnsupportedOperationException(); - } - - @Override - public Value getValue(String bindingName) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean hasBinding(String bindingName) { - throw new UnsupportedOperationException(); - } - - @Override - public Iterator iterator() { - throw new UnsupportedOperationException(); - } - - @Override - public int size() { - return size; - } - - @Override - public String toString() { - return getClass().getSimpleName() + "#" + size; - } -} diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/HashJoinIterationTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/HashJoinIterationTest.java index 4d42951b1e8..6ef82e99c30 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/HashJoinIterationTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/HashJoinIterationTest.java @@ -47,7 +47,7 @@ public ValueFactory getValueFactory() { } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { // TODO Auto-generated method stub return null; @@ -70,7 +70,9 @@ public void testCartesianJoin() throws QueryEvaluationException { right.setBindingSets(List.of(rightb)); } - HashJoinIteration iter = new HashJoinIteration(evaluator, left, right, EmptyBindingSet.getInstance(), false); + HashJoinIteration iter = new HashJoinIteration(evaluator.evaluate(left, EmptyBindingSet.getInstance()), + left.getBindingNames(), evaluator.evaluate(right, EmptyBindingSet.getInstance()), + right.getBindingNames(), false); BindingSet actual = iter.next(); assertEquals("1", actual.getValue("a").stringValue()); @@ -95,7 +97,9 @@ public void testInnerJoin() throws QueryEvaluationException { right.setBindingSets(List.of(rightb)); } - HashJoinIteration iter = new HashJoinIteration(evaluator, left, right, EmptyBindingSet.getInstance(), false); + HashJoinIteration iter = new HashJoinIteration(evaluator.evaluate(left, EmptyBindingSet.getInstance()), + left.getBindingNames(), evaluator.evaluate(right, EmptyBindingSet.getInstance()), + right.getBindingNames(), false); BindingSet actual = iter.next(); assertEquals("1", actual.getValue("a").stringValue()); @@ -121,7 +125,9 @@ public void testLeftJoin() throws QueryEvaluationException { right.setBindingSets(List.of(rightb)); } - HashJoinIteration iter = new HashJoinIteration(evaluator, left, right, EmptyBindingSet.getInstance(), true); + HashJoinIteration iter = new HashJoinIteration(evaluator.evaluate(left, EmptyBindingSet.getInstance()), + left.getBindingNames(), evaluator.evaluate(right, EmptyBindingSet.getInstance()), + right.getBindingNames(), true); BindingSet actual = iter.next(); assertEquals("1", actual.getValue("a").stringValue()); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/IterationStub.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/IterationStub.java deleted file mode 100644 index 07e4c9affb1..00000000000 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/IterationStub.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.iterator; - -import java.io.Serializable; - -import org.eclipse.rdf4j.common.iteration.CloseableIteratorIteration; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; - -class IterationStub extends CloseableIteratorIteration implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - int hasNextCount = 0; - - int nextCount = 0; - - int removeCount = 0; - - @Override - public boolean hasNext() throws QueryEvaluationException { - hasNextCount++; - return super.hasNext(); - } - - @Override - public BindingSet next() throws QueryEvaluationException { - nextCount++; - return super.next(); - } - - @Override - public void remove() { - removeCount++; - } -} diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/JoinIteratorTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/JoinIteratorTest.java index d28e4f609ec..33d910457e9 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/JoinIteratorTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/JoinIteratorTest.java @@ -53,7 +53,7 @@ public ValueFactory getValueFactory() { } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { // TODO Auto-generated method stub return null; @@ -106,11 +106,11 @@ private void testBindingSetAssignmentJoin(int expectedSize, int n, BindingSet bi right.setBindingSets(rightb); } - JoinIterator lrIter = new JoinIterator(evaluator, new Join(left, right), bindings, context); + JoinIterator lrIter = new JoinIterator(evaluator.precompile(left), evaluator.precompile(right), bindings); Set lr = Iterations.asSet(lrIter); assertEquals(expectedSize, lr.size()); - JoinIterator rlIter = new JoinIterator(evaluator, new Join(right, left), bindings, context); + JoinIterator rlIter = new JoinIterator(evaluator.precompile(right), evaluator.precompile(left), bindings); Set rl = Iterations.asSet(rlIter); assertEquals(expectedSize, rl.size()); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/OrderIteratorTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/OrderIteratorTest.java index 8b7cbd5bd17..a327098a548 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/OrderIteratorTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/OrderIteratorTest.java @@ -35,7 +35,7 @@ */ public class OrderIteratorTest { - class IterationStub extends CloseableIteratorIteration { + class IterationStub extends CloseableIteratorIteration { int hasNextCount = 0; @@ -139,7 +139,7 @@ public String toString() { private SizeComparator cmp; @Test - public void testFirstHasNext() throws Exception { + public void testFirstHasNext() { order.hasNext(); assertEquals(list.size() + 1, iteration.hasNextCount); assertEquals(list.size(), iteration.nextCount); @@ -147,7 +147,7 @@ public void testFirstHasNext() throws Exception { } @Test - public void testHasNext() throws Exception { + public void testHasNext() { order.hasNext(); order.next(); order.hasNext(); @@ -157,7 +157,7 @@ public void testHasNext() throws Exception { } @Test - public void testFirstNext() throws Exception { + public void testFirstNext() { order.next(); assertEquals(list.size() + 1, iteration.hasNextCount); assertEquals(list.size(), iteration.nextCount); @@ -165,7 +165,7 @@ public void testFirstNext() throws Exception { } @Test - public void testNext() throws Exception { + public void testNext() { order.next(); order.next(); assertEquals(list.size() + 1, iteration.hasNextCount); @@ -174,7 +174,7 @@ public void testNext() throws Exception { } @Test - public void testRemove() throws Exception { + public void testRemove() { try { order.remove(); fail(); @@ -184,7 +184,7 @@ public void testRemove() throws Exception { } @Test - public void testSorting() throws Exception { + public void testSorting() { List sorted = new ArrayList<>(list); Collections.sort(sorted, cmp); for (BindingSet b : sorted) { @@ -194,7 +194,7 @@ public void testSorting() throws Exception { } @BeforeEach - protected void setUp() throws Exception { + protected void setUp() { list = Arrays.asList(b3, b5, b2, b1, b4, b2); cmp = new SizeComparator(); iteration = new IterationStub(list.iterator()); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/PathIterationTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/PathIterationTest.java index c57f8249145..b6d038e15dd 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/PathIterationTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/PathIterationTest.java @@ -55,7 +55,7 @@ public void setUp() { TripleSource ts = new TripleSource() { @Override - public CloseableIteration getStatements(Resource subj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { return new CloseableIteratorIteration<>(m.getStatements(subj, pred, obj, contexts).iterator()); } diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SizeComparator.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SizeComparator.java deleted file mode 100644 index 641d2b9f830..00000000000 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/SizeComparator.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.evaluation.iterator; - -import java.io.Serializable; -import java.util.Comparator; - -import org.eclipse.rdf4j.query.BindingSet; - -class SizeComparator implements Comparator, Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public int compare(BindingSet o1, BindingSet o2) { - return Integer.valueOf(o1.size()).compareTo(o2.size()); - } -} diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ZeroLengthPathIterationTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ZeroLengthPathIterationTest.java index 082a1c5edec..eecfb6149fc 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ZeroLengthPathIterationTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/iterator/ZeroLengthPathIterationTest.java @@ -53,7 +53,7 @@ public void setUp() { TripleSource ts = new TripleSource() { @Override - public CloseableIteration getStatements(Resource subj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { return new CloseableIteratorIteration<>(m.getStatements(subj, pred, obj, contexts).iterator()); } diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/LiteralComparatorTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/LiteralComparatorTest.java index 97dc0063dc5..994e3528845 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/LiteralComparatorTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/LiteralComparatorTest.java @@ -64,7 +64,7 @@ public class LiteralComparatorTest { private final ValueComparator cmp = new ValueComparator(); @Test - public void testNumeric() throws Exception { + public void testNumeric() { assertTrue(cmp.compare(one, one) == 0); assertTrue(cmp.compare(one, ten) < 0); assertTrue(cmp.compare(ten, one) > 0); @@ -72,7 +72,7 @@ public void testNumeric() throws Exception { } @Test - public void testString() throws Exception { + public void testString() { assertTrue(cmp.compare(a, a) == 0); assertTrue(cmp.compare(a, b) < 0); assertTrue(cmp.compare(b, a) > 0); @@ -80,7 +80,7 @@ public void testString() throws Exception { } @Test - public void testSameLanguage() throws Exception { + public void testSameLanguage() { assertTrue(cmp.compare(la, la) == 0); assertTrue(cmp.compare(la, lb) < 0); assertTrue(cmp.compare(lb, la) > 0); @@ -88,12 +88,12 @@ public void testSameLanguage() throws Exception { } @Test - public void testDifferentLanguage() throws Exception { + public void testDifferentLanguage() { cmp.compare(la, lf); } @Test - public void testBoolean() throws Exception { + public void testBoolean() { assertTrue(cmp.compare(f, f) == 0); assertTrue(cmp.compare(f, t) < 0); assertTrue(cmp.compare(t, f) > 0); @@ -101,7 +101,7 @@ public void testBoolean() throws Exception { } @Test - public void testDateTime() throws Exception { + public void testDateTime() { assertTrue(cmp.compare(date1, date1) == 0); assertTrue(cmp.compare(date1, date2) < 0); assertTrue(cmp.compare(date2, date1) > 0); @@ -109,7 +109,7 @@ public void testDateTime() throws Exception { } @Test - public void testBothSimple() throws Exception { + public void testBothSimple() { assertTrue(cmp.compare(simple1, simple1) == 0); assertTrue(cmp.compare(simple1, simple2) < 0); assertTrue(cmp.compare(simple2, simple1) > 0); @@ -117,17 +117,17 @@ public void testBothSimple() throws Exception { } @Test - public void testLeftSimple() throws Exception { + public void testLeftSimple() { assertTrue(cmp.compare(simple1, typed1) == 0); } @Test - public void testRightSimple() throws Exception { + public void testRightSimple() { assertTrue(cmp.compare(typed1, simple1) == 0); } @Test - public void testOrder() throws Exception { + public void testOrder() { Literal en4 = vf.createLiteral("4", "en"); Literal nine = vf.createLiteral(9); List list = new ArrayList<>(); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/OrderComparatorTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/OrderComparatorTest.java index 53b1999234e..c54b855c155 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/OrderComparatorTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/OrderComparatorTest.java @@ -32,6 +32,7 @@ import org.eclipse.rdf4j.query.algebra.ValueExpr; import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; +import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizerPipeline; import org.eclipse.rdf4j.query.algebra.evaluation.QueryValueEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; @@ -52,15 +53,19 @@ public class OrderComparatorTest { class EvaluationStrategyStub implements EvaluationStrategy { @Override - public CloseableIteration evaluate(Service expr, String serviceUri, - CloseableIteration bindings) throws QueryEvaluationException { + public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) + throws QueryEvaluationException { throw new UnsupportedOperationException(); } @Override - public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) - throws QueryEvaluationException { - throw new UnsupportedOperationException(); + public QueryEvaluationStep precompile(TupleExpr expr) { + return QueryEvaluationStep.minimal(this, expr); + } + + @Override + public QueryEvaluationStep precompile(TupleExpr expr, QueryEvaluationContext context) { + return QueryEvaluationStep.minimal(this, expr); } @Override @@ -140,7 +145,7 @@ public int compare(Value o1, Value o2) { private final int NEG = -7349; @Test - public void testEquals() throws Exception { + public void testEquals() { order.addElement(asc); cmp.setIterator(List.of(ZERO).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp, context); @@ -148,7 +153,7 @@ public void testEquals() throws Exception { } @Test - public void testZero() throws Exception { + public void testZero() { order.addElement(asc); order.addElement(asc); cmp.setIterator(Arrays.asList(ZERO, POS).iterator()); @@ -157,7 +162,7 @@ public void testZero() throws Exception { } @Test - public void testTerm() throws Exception { + public void testTerm() { order.addElement(asc); order.addElement(asc); cmp.setIterator(Arrays.asList(POS, NEG).iterator()); @@ -166,7 +171,7 @@ public void testTerm() throws Exception { } @Test - public void testAscLessThan() throws Exception { + public void testAscLessThan() { order.addElement(asc); cmp.setIterator(List.of(NEG).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp, context); @@ -174,7 +179,7 @@ public void testAscLessThan() throws Exception { } @Test - public void testAscGreaterThan() throws Exception { + public void testAscGreaterThan() { order.addElement(asc); cmp.setIterator(List.of(POS).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp, context); @@ -182,7 +187,7 @@ public void testAscGreaterThan() throws Exception { } @Test - public void testDescLessThan() throws Exception { + public void testDescLessThan() { order.addElement(desc); cmp.setIterator(List.of(NEG).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp, context); @@ -190,7 +195,7 @@ public void testDescLessThan() throws Exception { } @Test - public void testDescGreaterThan() throws Exception { + public void testDescGreaterThan() { order.addElement(desc); cmp.setIterator(List.of(POS).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp, context); @@ -198,7 +203,7 @@ public void testDescGreaterThan() throws Exception { } @Test - public void testDisjunctBindingNames() throws Exception { + public void testDisjunctBindingNames() { OrderComparator sud = new OrderComparator(strategy, order, cmp, context); QueryBindingSet a = new QueryBindingSet(); QueryBindingSet b = new QueryBindingSet(); @@ -222,7 +227,7 @@ public void testEqualBindingNamesUnequalValues() { } @BeforeEach - public void setUp() throws Exception { + public void setUp() { asc.setAscending(true); desc.setAscending(false); } diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/ValueComparatorTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/ValueComparatorTest.java index 0beacdf15c8..f460369e772 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/ValueComparatorTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/ValueComparatorTest.java @@ -46,22 +46,22 @@ public class ValueComparatorTest { private final ValueComparator cmp = new ValueComparator(); @Test - public void testBothNull() throws Exception { + public void testBothNull() { assertTrue(cmp.compare(null, null) == 0); } @Test - public void testLeftNull() throws Exception { + public void testLeftNull() { assertTrue(cmp.compare(null, typed1) < 0); } @Test - public void testRightNull() throws Exception { + public void testRightNull() { assertTrue(cmp.compare(typed1, null) > 0); } @Test - public void testBothBnode() throws Exception { + public void testBothBnode() { assertTrue(cmp.compare(bnode1, bnode1) == 0); assertTrue(cmp.compare(bnode2, bnode2) == 0); assertTrue(cmp.compare(bnode1, bnode2) != cmp.compare(bnode2, bnode1)); @@ -69,17 +69,17 @@ public void testBothBnode() throws Exception { } @Test - public void testLeftBnode() throws Exception { + public void testLeftBnode() { assertTrue(cmp.compare(bnode1, typed1) < 0); } @Test - public void testRightBnode() throws Exception { + public void testRightBnode() { assertTrue(cmp.compare(typed1, bnode1) > 0); } @Test - public void testBothURI() throws Exception { + public void testBothURI() { assertTrue(cmp.compare(uri1, uri1) == 0); assertTrue(cmp.compare(uri1, uri2) < 0); assertTrue(cmp.compare(uri1, uri3) < 0); @@ -92,12 +92,12 @@ public void testBothURI() throws Exception { } @Test - public void testLeftURI() throws Exception { + public void testLeftURI() { assertTrue(cmp.compare(uri1, typed1) < 0); } @Test - public void testRightURI() throws Exception { + public void testRightURI() { assertTrue(cmp.compare(typed1, uri1) > 0); } @@ -105,7 +105,7 @@ public void testRightURI() throws Exception { * Tests whether xsd:int's are properly sorted in a list with mixed value types. */ @Test - public void testOrder1() throws Exception { + public void testOrder1() { Literal en4 = vf.createLiteral("4", "en"); Literal int10 = vf.createLiteral(10); Literal int9 = vf.createLiteral(9); @@ -120,7 +120,7 @@ public void testOrder1() throws Exception { * Tests whether various numerics are properly sorted in a list with mixed value types. */ @Test - public void testOrder2() throws Exception { + public void testOrder2() { Literal en4 = vf.createLiteral("4", "en"); Literal int10 = vf.createLiteral(10); Literal int9 = vf.createLiteral(9); @@ -146,7 +146,7 @@ public void testOrder2() throws Exception { * sorted between the numerics if the datatypes were to be sorted alphabetically. */ @Test - public void testOrder3() throws Exception { + public void testOrder3() { Literal year1234 = vf.createLiteral("1234", XSD.GYEAR); Literal float2000 = vf.createLiteral(2000f); Literal int1000 = vf.createLiteral(1000); @@ -157,7 +157,7 @@ public void testOrder3() throws Exception { } @Test - public void testNonStrictComparisons() throws Exception { + public void testNonStrictComparisons() { cmp.setStrict(false); assertTrue(cmp.isStrict() == false); Literal date1 = vf.createLiteral("2019-09-02", XSD.DATE); @@ -166,7 +166,7 @@ public void testNonStrictComparisons() throws Exception { } @Test - public void testStrictComparisons() throws Exception { + public void testStrictComparisons() { cmp.setStrict(true); assertTrue(cmp.isStrict() == true); Literal date1 = vf.createLiteral("2019-09-02", XSD.DATE); diff --git a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/XMLDatatypeMathUtilTest.java b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/XMLDatatypeMathUtilTest.java index 04942e7ab6d..1ab69e8775f 100644 --- a/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/XMLDatatypeMathUtilTest.java +++ b/core/queryalgebra/evaluation/src/test/java/org/eclipse/rdf4j/query/algebra/evaluation/util/XMLDatatypeMathUtilTest.java @@ -28,7 +28,7 @@ public class XMLDatatypeMathUtilTest { private final ValueFactory vf = SimpleValueFactory.getInstance(); @Test - public void testCompute() throws Exception { + public void testCompute() { Literal float1 = vf.createLiteral("12", XSD.INTEGER); Literal float2 = vf.createLiteral("2", CoreDatatype.XSD.INTEGER); Literal duration1 = vf.createLiteral("P1Y1M", XSD.YEARMONTHDURATION); @@ -54,7 +54,7 @@ public void testCompute() throws Exception { assertComputeEquals(vf.createLiteral("2013-11", XSD.GYEARMONTH), duration1, yearMonth1, MathOp.PLUS); } - private void assertComputeEquals(Literal result, Literal lit1, Literal lit2, MathOp op) throws Exception { + private void assertComputeEquals(Literal result, Literal lit1, Literal lit2, MathOp op) { assertEquals(result, XMLDatatypeMathUtil.compute(lit1, lit2, op)); } } diff --git a/core/queryalgebra/geosparql/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/geosparql/FunctionArguments.java b/core/queryalgebra/geosparql/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/geosparql/FunctionArguments.java index 7c142444952..70851efbbbf 100644 --- a/core/queryalgebra/geosparql/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/geosparql/FunctionArguments.java +++ b/core/queryalgebra/geosparql/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/geosparql/FunctionArguments.java @@ -16,9 +16,8 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.vocabulary.GEO; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.GEOF; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.locationtech.spatial4j.context.SpatialContext; @@ -66,7 +65,7 @@ public static double getDouble(Function func, Value v) throws ValueExprEvaluatio * @throws ValueExprEvaluationException */ public static String getString(Function func, Value v) throws ValueExprEvaluationException { - Literal l = getLiteral(func, v, XSD.STRING); + Literal l = getLiteral(func, v, CoreDatatype.XSD.STRING); return l.stringValue(); } @@ -80,7 +79,7 @@ public static String getString(Function func, Value v) throws ValueExprEvaluatio * @throws ValueExprEvaluationException */ public static Shape getShape(Function func, Value v, SpatialContext context) throws ValueExprEvaluationException { - Literal wktLiteral = getLiteral(func, v, GEO.WKT_LITERAL); + Literal wktLiteral = getLiteral(func, v, CoreDatatype.GEO.WKT_LITERAL); try { ShapeReader reader = context.getFormats().getWktReader(); return reader.read(wktLiteral.getLabel()); @@ -128,6 +127,19 @@ public static Literal getLiteral(Function func, Value v, IRI expectedDatatype) t return lit; } + public static Literal getLiteral(Function func, Value v, CoreDatatype expectedDatatype) + throws ValueExprEvaluationException { + if (!(v instanceof Literal)) { + throw new ValueExprEvaluationException("Invalid argument for " + func.getURI() + ": " + v); + } + Literal lit = (Literal) v; + if (expectedDatatype != lit.getCoreDatatype()) { + throw new ValueExprEvaluationException( + "Invalid datatype " + lit.getDatatype() + " for " + func.getURI() + ": " + v); + } + return lit; + } + /** * Get the UoM IRI of the unit * diff --git a/core/queryalgebra/geosparql/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/geosparql/SRID.java b/core/queryalgebra/geosparql/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/geosparql/SRID.java index 44cab01e8c0..2b64e7762ad 100644 --- a/core/queryalgebra/geosparql/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/geosparql/SRID.java +++ b/core/queryalgebra/geosparql/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/geosparql/SRID.java @@ -13,9 +13,9 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.vocabulary.GEO; import org.eclipse.rdf4j.model.vocabulary.GEOF; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; @@ -37,7 +37,7 @@ public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExpr throw new ValueExprEvaluationException(getURI() + " requires exactly 1 argument, got " + args.length); } - Literal geom = FunctionArguments.getLiteral(this, args[0], GEO.WKT_LITERAL); + Literal geom = FunctionArguments.getLiteral(this, args[0], CoreDatatype.GEO.WKT_LITERAL); String wkt = geom.getLabel(); String srid; int sep = wkt.indexOf(' '); @@ -47,6 +47,6 @@ public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExpr srid = GEO.DEFAULT_SRID; } - return valueFactory.createLiteral(srid, XSD.ANYURI); + return valueFactory.createLiteral(srid, CoreDatatype.XSD.ANYURI); } } diff --git a/core/queryalgebra/model/pom.xml b/core/queryalgebra/model/pom.xml index a356536aaa7..ce8d3ac617f 100644 --- a/core/queryalgebra/model/pom.xml +++ b/core/queryalgebra/model/pom.xml @@ -21,12 +21,4 @@ ${project.version} - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/AbstractQueryModelNode.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/AbstractQueryModelNode.java index 7be6789f4bd..62a2b1d94cc 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/AbstractQueryModelNode.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/AbstractQueryModelNode.java @@ -22,7 +22,7 @@ /** * Base implementation of {@link QueryModelNode}. */ -public abstract class AbstractQueryModelNode implements QueryModelNode, VariableScopeChange, GraphPatternGroupable { +public abstract class AbstractQueryModelNode implements QueryModelNode, VariableScopeChange { private static final double CARDINALITY_NOT_SET = Double.MIN_VALUE; @@ -68,35 +68,6 @@ public void setVariableScopeChange(boolean isVariableScopeChange) { this.isVariableScopeChange = isVariableScopeChange; } - @Override - @Deprecated - public boolean isGraphPatternGroup() { - return isVariableScopeChange(); - } - - @Override - @Deprecated - public void setGraphPatternGroup(boolean isGraphPatternGroup) { - setVariableScopeChange(isGraphPatternGroup); - } - - /** - * Dummy implementation of {@link QueryModelNode#visitChildren} that does nothing. Subclasses should override this - * method when they have child nodes. - */ - @Override - public void visitChildren(QueryModelVisitor visitor) throws X { - } - - /** - * Default implementation of {@link QueryModelNode#replaceChildNode(QueryModelNode, QueryModelNode)} that throws an - * {@link IllegalArgumentException} indicating that current is not a child node of this node. - */ - @Override - public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { - throw new IllegalArgumentException("Node is not a child node: " + current); - } - /** * Default implementation of {@link QueryModelNode#replaceWith(QueryModelNode)} that throws an * {@link IllegalArgumentException} indicating that current is not a child node of this node. diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/AggregateOperatorBase.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/AggregateOperatorBase.java deleted file mode 100644 index 6a5e3931880..00000000000 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/AggregateOperatorBase.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra; - -/** - * @author Jeen Broekstra - * @deprecated Use {@link AbstractAggregateOperator} instead. - */ -@Deprecated(since = "2.0") -public abstract class AggregateOperatorBase extends AbstractAggregateOperator { - - private static final long serialVersionUID = 1L; - - protected AggregateOperatorBase(ValueExpr arg) { - super(arg); - } - -} diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BNodeGenerator.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BNodeGenerator.java index 8d42f418c10..3b92e1141e1 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BNodeGenerator.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BNodeGenerator.java @@ -51,6 +51,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + @Override public boolean equals(Object other) { return other instanceof BNodeGenerator; diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BinaryTupleOperator.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BinaryTupleOperator.java index 74cddbd2ae1..9a6a7fbade4 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BinaryTupleOperator.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BinaryTupleOperator.java @@ -145,7 +145,7 @@ public BinaryTupleOperator clone() { } @Experimental - public void setAlgorithm(CloseableIteration iteration) { + public void setAlgorithm(CloseableIteration iteration) { this.algorithmName = iteration.getClass().getSimpleName(); } diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BindingSetAssignment.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BindingSetAssignment.java index 3fac373e1de..fb0518c829c 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BindingSetAssignment.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/BindingSetAssignment.java @@ -58,6 +58,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + @Override public boolean equals(Object obj) { if (this == obj) { diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/DeleteData.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/DeleteData.java index bfadc0224e3..24251c839eb 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/DeleteData.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/DeleteData.java @@ -32,6 +32,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + public String getDataBlock() { return dataBlock; } diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/EmptySet.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/EmptySet.java index 972ada20f9f..a6e467e33ae 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/EmptySet.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/EmptySet.java @@ -38,6 +38,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + @Override public boolean equals(Object other) { return other instanceof EmptySet; diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/GraphPatternGroupable.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/GraphPatternGroupable.java deleted file mode 100644 index 25aabf41f44..00000000000 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/GraphPatternGroupable.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra; - -/** - * @author jeen - * @deprecated Use {@link VariableScopeChange} instead. - */ -@Deprecated(since = "3.2") -public interface GraphPatternGroupable { - - /** - * indicates if the node represents the root of a graph pattern group. - * - * @return true iff the node represents the node of a graph pattern group. - */ - @Deprecated - boolean isGraphPatternGroup(); - - /** - * Set the value of {@link #isGraphPatternGroup()} to true or false. - */ - @Deprecated - void setGraphPatternGroup(boolean isGraphPatternGroup); - -} diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/InsertData.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/InsertData.java index 0a4baca36bf..49785a3f53b 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/InsertData.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/InsertData.java @@ -33,6 +33,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + public String getDataBlock() { return dataBlock; } diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/Like.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/Like.java deleted file mode 100644 index 980716e3017..00000000000 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/Like.java +++ /dev/null @@ -1,106 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra; - -/** - * Compares the string representation of a value expression to a pattern. - */ -@Deprecated(forRemoval = true) -public class Like extends UnaryValueOperator { - - /*-----------* - * Variables * - *-----------*/ - - private String pattern; - - private boolean caseSensitive; - - /** - * Operational pattern, equal to pattern but converted to lower case when not case sensitive. - */ - private String opPattern; - - /*--------------* - * Constructors * - *--------------*/ - - public Like() { - } - - public Like(ValueExpr expr, String pattern, boolean caseSensitive) { - super(expr); - setPattern(pattern, caseSensitive); - } - - /*---------* - * Methods * - *---------*/ - - public void setPattern(String pattern, boolean caseSensitive) { - assert pattern != null : "pattern must not be null"; - this.pattern = pattern; - this.caseSensitive = caseSensitive; - opPattern = caseSensitive ? pattern : pattern.toLowerCase(); - } - - public String getPattern() { - return pattern; - } - - public boolean isCaseSensitive() { - return caseSensitive; - } - - public String getOpPattern() { - return opPattern; - } - - @Override - public void visit(QueryModelVisitor visitor) throws X { - visitor.meet(this); - } - - @Override - public String getSignature() { - StringBuilder sb = new StringBuilder(128); - - sb.append(super.getSignature()); - sb.append(" \""); - sb.append(pattern); - sb.append("\""); - - if (caseSensitive) { - sb.append(" IGNORE CASE"); - } - - return sb.toString(); - } - - @Override - public boolean equals(Object other) { - if (other instanceof Like && super.equals(other)) { - Like o = (Like) other; - return caseSensitive == o.isCaseSensitive() && opPattern.equals(o.getOpPattern()); - } - return false; - } - - @Override - public int hashCode() { - return super.hashCode() ^ opPattern.hashCode(); - } - - @Override - public Like clone() { - return (Like) super.clone(); - } -} diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ProjectionElem.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ProjectionElem.java index d18c8124908..ea46c0b969f 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ProjectionElem.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ProjectionElem.java @@ -79,22 +79,6 @@ public String getName() { return name; } - /** - * @deprecated since 4.1.1. Use {@link #getName()} instead. - */ - @Deprecated(since = "4.1.1", forRemoval = true) - public String getSourceName() { - return getName(); - } - - /** - * @deprecated since 4.1.1. Use {@link #setName(String)} instead. - */ - @Deprecated(since = "4.1.1", forRemoval = true) - public void setSourceName(String sourceName) { - setName(sourceName); - } - /** * Set the name of the projection element (typically the name of the variable in the select expressions) * @@ -124,22 +108,6 @@ public void setProjectionAlias(String alias) { this.projectionAlias = alias; } - /** - * @deprecated since 4.1.1. Use {@link #setProjectionAlias(String)} instead. - */ - @Deprecated(since = "4.1.1", forRemoval = true) - public void setTargetName(String targetName) { - setProjectionAlias(targetName); - } - - /** - * @deprecated since 4.1.1. Use {@link #getProjectionAlias()} instead. - */ - @Deprecated(since = "4.1.1", forRemoval = true) - public String getTargetName() { - return getProjectionAlias().orElse(null); - } - @Override public void visit(QueryModelVisitor visitor) throws X { visitor.meet(this); @@ -150,6 +118,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + @Override public String getSignature() { StringBuilder sb = new StringBuilder(32); diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ProjectionElemList.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ProjectionElemList.java index 838b9bffb8a..53a4394f813 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ProjectionElemList.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ProjectionElemList.java @@ -81,14 +81,6 @@ public void addElement(ProjectionElem pe) { pe.setParentNode(this); } - /** - * @deprecated since 4.1.1. Use {@link #getProjectedNames()} instead. - */ - @Deprecated(since = "4.1.1", forRemoval = true) - public Set getTargetNames() { - return getProjectedNames(); - } - public Set getProjectedNames() { Set projectedNames = new LinkedHashSet<>(elementsList.size()); @@ -99,14 +91,6 @@ public Set getProjectedNames() { return projectedNames; } - /** - * @deprecated since 4.1.1. Use {@link #getProjectedNamesFor(Collection)} instead. - */ - @Deprecated(since = "4.1.1", forRemoval = true) - public Set getTargetNamesFor(Collection sourceNames) { - return getProjectedNamesFor(sourceNames); - } - public Set getProjectedNamesFor(Collection sourceNames) { Set projectedNames = new LinkedHashSet<>(elementsList.size()); diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/QueryModelVisitor.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/QueryModelVisitor.java index bebbeba0b74..3625f99b123 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/QueryModelVisitor.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/QueryModelVisitor.java @@ -109,9 +109,6 @@ public interface QueryModelVisitor { void meet(LeftJoin node) throws X; - @Deprecated(forRemoval = true) - void meet(Like node) throws X; - void meet(Load load) throws X; void meet(LocalName node) throws X; diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/SingletonSet.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/SingletonSet.java index 72ab10a007b..45fabeb5c34 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/SingletonSet.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/SingletonSet.java @@ -38,6 +38,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + @Override public boolean equals(Object other) { return other instanceof SingletonSet; diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/StatementPattern.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/StatementPattern.java index e6160849c14..a653205eb17 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/StatementPattern.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/StatementPattern.java @@ -25,9 +25,6 @@ */ public class StatementPattern extends AbstractQueryModelNode implements TupleExpr { - @Deprecated - public static final double CARDINALITY_NOT_SET = Double.MIN_VALUE; - /** * Indicates the scope of the statement pattern. */ @@ -60,14 +57,6 @@ public enum Scope { private Set assuredBindingNames; private List varList; - /*--------------* - * Constructors * - *--------------*/ - - @Deprecated(since = "4.0.0", forRemoval = true) - public StatementPattern() { - } - /** * Creates a statement pattern that matches a subject-, predicate- and object variable against statements from all * contexts. @@ -122,56 +111,18 @@ public Scope getScope() { return scope; } - /** - * Sets the context scope for the statement pattern. - */ - @Deprecated(since = "4.0.0", forRemoval = true) - public void setScope(Scope scope) { - this.scope = Objects.requireNonNull(scope); - assuredBindingNames = null; - varList = null; - resetCardinality(); - } - public Var getSubjectVar() { return subjectVar; } - @Deprecated(since = "4.0.0", forRemoval = true) - public void setSubjectVar(Var subject) { - Objects.requireNonNull(subject).setParentNode(this); - subjectVar = subject; - assuredBindingNames = null; - varList = null; - resetCardinality(); - } - public Var getPredicateVar() { return predicateVar; } - @Deprecated(since = "4.0.0", forRemoval = true) - public void setPredicateVar(Var predicate) { - Objects.requireNonNull(predicate).setParentNode(this); - predicateVar = predicate; - assuredBindingNames = null; - varList = null; - resetCardinality(); - } - public Var getObjectVar() { return objectVar; } - @Deprecated(since = "4.0.0", forRemoval = true) - public void setObjectVar(Var object) { - Objects.requireNonNull(object).setParentNode(this); - objectVar = object; - assuredBindingNames = null; - varList = null; - resetCardinality(); - } - /** * Returns the context variable, if available. */ @@ -179,17 +130,6 @@ public Var getContextVar() { return contextVar; } - @Deprecated(since = "4.0.0", forRemoval = true) - public void setContextVar(Var context) { - if (context != null) { - context.setParentNode(this); - } - contextVar = context; - assuredBindingNames = null; - varList = null; - resetCardinality(); - } - @Override public Set getBindingNames() { return getAssuredBindingNames(); @@ -356,14 +296,26 @@ public void visitChildren(QueryModelVisitor visitor) th @Override public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { if (subjectVar == current) { - setSubjectVar((Var) replacement); + Objects.requireNonNull((Var) replacement).setParentNode(this); + subjectVar = (Var) replacement; } else if (predicateVar == current) { - setPredicateVar((Var) replacement); + Objects.requireNonNull((Var) replacement).setParentNode(this); + predicateVar = (Var) replacement; } else if (objectVar == current) { - setObjectVar((Var) replacement); + Objects.requireNonNull((Var) replacement).setParentNode(this); + objectVar = (Var) replacement; } else if (contextVar == current) { - setContextVar((Var) replacement); + if (replacement != null) { + replacement.setParentNode(this); + } + contextVar = (Var) replacement; + } else { + throw new IllegalArgumentException("Not a child " + current); } + + assuredBindingNames = null; + varList = null; + resetCardinality(); } @Override diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ValueConstant.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ValueConstant.java index 0bf57f43905..5dfcc1889c5 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ValueConstant.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ValueConstant.java @@ -57,6 +57,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + @Override public String getSignature() { StringBuilder sb = new StringBuilder(64); diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ValueExprTripleRef.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ValueExprTripleRef.java index 147e8a57f97..12b5c6eca70 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ValueExprTripleRef.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/ValueExprTripleRef.java @@ -96,7 +96,7 @@ public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) } else if (objectVar == current) { objectVar = (Var) replacement; } else { - super.replaceChildNode(current, replacement); + throw new IllegalArgumentException("Node is not a child node: " + current); } } } diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/Var.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/Var.java index cabf88ff605..7d72405946a 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/Var.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/Var.java @@ -22,20 +22,16 @@ */ public class Var extends AbstractQueryModelNode implements ValueExpr { - private String name; + private final String name; private Value value; - private boolean anonymous = false; + private final boolean anonymous; private boolean constant = false; private int cachedHashCode = 0; - @Deprecated(forRemoval = true, since = "4.1.0") - public Var() { - } - public Var(String name, Value value, boolean anonymous, boolean constant) { this.name = name; this.value = value; @@ -56,10 +52,8 @@ public Var(String name, Value value) { this(name, value, false, false); } - @Deprecated(forRemoval = true, since = "4.1.0") - public void setAnonymous(boolean anonymous) { - this.cachedHashCode = 0; - this.anonymous = anonymous; + public Var(String name, Value value, boolean anonymous) { + this(name, value, anonymous, false); } public boolean isAnonymous() { @@ -70,18 +64,6 @@ public String getName() { return name; } - @Deprecated(forRemoval = true, since = "4.1.0") - public void setName(String name) { - this.cachedHashCode = 0; - this.name = name; - } - - @Deprecated(forRemoval = true, since = "4.1.0") - public void setValue(Value value) { - this.cachedHashCode = 0; - this.value = value; - } - public boolean hasValue() { return value != null; } @@ -111,15 +93,6 @@ public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) } - @Override - public void replaceWith(QueryModelNode replacement) { - if (getParentNode() == null) { - throw new IllegalStateException("Node has no parent"); - } - - getParentNode().replaceChildNode(this, replacement); - } - @Override public String getSignature() { StringBuilder sb = new StringBuilder(64); @@ -183,11 +156,4 @@ public boolean isConstant() { return constant; } - /** - * @param constant The constant to set. - */ - @Deprecated(forRemoval = true, since = "4.1.0") - public void setConstant(boolean constant) { - this.constant = constant; - } } diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/FederatedService.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/FederatedService.java index b35cd14c193..175456e0ff1 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/FederatedService.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/federation/FederatedService.java @@ -63,7 +63,7 @@ public interface FederatedService { * @return an iteration over the results of the query * @throws QueryEvaluationException If there was an exception generated while evaluating the query. */ - CloseableIteration select(Service service, Set projectionVars, + CloseableIteration select(Service service, Set projectionVars, BindingSet bindings, String baseUri) throws QueryEvaluationException; /** @@ -86,8 +86,8 @@ CloseableIteration select(Service service, * inserted into the results! * @throws QueryEvaluationException If there was an exception generated while evaluating the query. */ - CloseableIteration evaluate(Service service, - CloseableIteration bindings, String baseUri) + CloseableIteration evaluate(Service service, + CloseableIteration bindings, String baseUri) throws QueryEvaluationException; /** diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/AbstractQueryModelVisitor.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/AbstractQueryModelVisitor.java index 62696a603ce..ca154b48265 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/AbstractQueryModelVisitor.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/AbstractQueryModelVisitor.java @@ -58,7 +58,6 @@ import org.eclipse.rdf4j.query.algebra.Lang; import org.eclipse.rdf4j.query.algebra.LangMatches; import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.Like; import org.eclipse.rdf4j.query.algebra.ListMemberOperator; import org.eclipse.rdf4j.query.algebra.Load; import org.eclipse.rdf4j.query.algebra.LocalName; @@ -334,12 +333,6 @@ public void meet(LeftJoin node) throws X { meetBinaryTupleOperator(node); } - @Override - @Deprecated(forRemoval = true) - public void meet(Like node) throws X { - // From SERQL should not be seen - } - @Override public void meet(Load node) throws X { meetUpdateExpr(node); diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/AbstractSimpleQueryModelVisitor.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/AbstractSimpleQueryModelVisitor.java index d39102e9091..f2948a6d0a9 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/AbstractSimpleQueryModelVisitor.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/AbstractSimpleQueryModelVisitor.java @@ -58,7 +58,6 @@ import org.eclipse.rdf4j.query.algebra.Lang; import org.eclipse.rdf4j.query.algebra.LangMatches; import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.Like; import org.eclipse.rdf4j.query.algebra.ListMemberOperator; import org.eclipse.rdf4j.query.algebra.Load; import org.eclipse.rdf4j.query.algebra.LocalName; @@ -345,12 +344,6 @@ public void meet(LeftJoin node) throws X { meetBinaryTupleOperator(node); } - @Override - @Deprecated(forRemoval = true) - public void meet(Like node) throws X { - // From SERQL should not be seen - } - @Override public void meet(Load node) throws X { meetUpdateExpr(node); diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/BGPCollector.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/BGPCollector.java deleted file mode 100644 index 395ada6c08b..00000000000 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/BGPCollector.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.helpers; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.eclipse.rdf4j.query.algebra.Join; -import org.eclipse.rdf4j.query.algebra.QueryModelNode; -import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; -import org.eclipse.rdf4j.query.algebra.StatementPattern; - -/** - * Basic graph pattern collector. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class BGPCollector extends QueryModelVisitorBase { - - private final QueryModelVisitor visitor; - - private List statementPatterns; - - public BGPCollector(QueryModelVisitor visitor) { - this.visitor = visitor; - } - - public List getStatementPatterns() { - return (statementPatterns != null) ? statementPatterns : Collections.emptyList(); - } - - @Override - public void meet(Join node) throws X { - // by-pass meetNode() - node.visitChildren(this); - } - - @Override - public void meet(StatementPattern sp) throws X { - if (statementPatterns == null) { - statementPatterns = new ArrayList<>(); - } - statementPatterns.add(sp); - } - - @Override - protected void meetNode(QueryModelNode node) throws X { - // resume previous visitor - node.visit(visitor); - } -} diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/QueryModelNodeReplacer.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/QueryModelNodeReplacer.java deleted file mode 100644 index e8017f03d34..00000000000 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/QueryModelNodeReplacer.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.helpers; - -import org.eclipse.rdf4j.query.algebra.BinaryTupleOperator; -import org.eclipse.rdf4j.query.algebra.BinaryValueOperator; -import org.eclipse.rdf4j.query.algebra.Filter; -import org.eclipse.rdf4j.query.algebra.QueryModelNode; -import org.eclipse.rdf4j.query.algebra.TupleExpr; -import org.eclipse.rdf4j.query.algebra.UnaryTupleOperator; -import org.eclipse.rdf4j.query.algebra.UnaryValueOperator; -import org.eclipse.rdf4j.query.algebra.ValueExpr; - -@Deprecated -public class QueryModelNodeReplacer extends AbstractQueryModelVisitor { - - private QueryModelNode former; - - private QueryModelNode replacement; - - public void replaceChildNode(QueryModelNode parent, QueryModelNode former, QueryModelNode replacement) { - this.former = former; - this.replacement = replacement; - parent.visit(this); - } - - public void replaceNode(QueryModelNode former, QueryModelNode replacement) { - replaceChildNode(former.getParentNode(), former, replacement); - } - - public void removeChildNode(QueryModelNode parent, QueryModelNode former) { - replaceChildNode(parent, former, null); - } - - public void removeNode(QueryModelNode former) { - replaceChildNode(former.getParentNode(), former, null); - } - - @Override - public void meet(Filter node) { - if (replacement == null) { - replaceNode(node, node.getArg()); - } else if (replacement instanceof ValueExpr) { - assert former == node.getCondition(); - node.setCondition((ValueExpr) replacement); - } else { - assert former == node.getArg(); - node.setArg((TupleExpr) replacement); - } - } - - @Override - protected void meetBinaryTupleOperator(BinaryTupleOperator node) { - if (node.getLeftArg() == former) { - if (replacement == null) { - replaceNode(node, node.getRightArg()); - } else { - node.setLeftArg((TupleExpr) replacement); - } - } else { - assert former == node.getRightArg(); - if (replacement == null) { - replaceNode(node, node.getLeftArg()); - } else { - node.setRightArg((TupleExpr) replacement); - } - } - } - - @Override - protected void meetBinaryValueOperator(BinaryValueOperator node) { - if (former == node.getLeftArg()) { - if (replacement == null) { - replaceNode(node, node.getRightArg()); - } else { - node.setLeftArg((ValueExpr) replacement); - } - } else { - assert former == node.getRightArg(); - if (replacement == null) { - replaceNode(node, node.getLeftArg()); - } else { - node.setRightArg((ValueExpr) replacement); - } - } - } - - @Override - protected void meetUnaryTupleOperator(UnaryTupleOperator node) { - assert former == node.getArg(); - if (replacement == null) { - removeNode(node); - } else { - node.setArg((TupleExpr) replacement); - } - } - - @Override - protected void meetUnaryValueOperator(UnaryValueOperator node) { - assert former == node.getArg(); - if (replacement == null) { - removeNode(node); - } else { - node.setArg((ValueExpr) replacement); - } - } - - @Override - protected void meetNode(QueryModelNode node) { - throw new IllegalArgumentException("Unhandled Node: " + node); - } -} diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/QueryModelVisitorBase.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/QueryModelVisitorBase.java deleted file mode 100644 index d81775aba84..00000000000 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/QueryModelVisitorBase.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.helpers; - -/** - * @author Jeen Broekstra - * @deprecated since 2.0. Use {@link AbstractQueryModelVisitor} instead. - */ -@Deprecated(since = "2.0") -public abstract class QueryModelVisitorBase extends AbstractQueryModelVisitor { - -} diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/StatementPatternCollector.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/StatementPatternCollector.java deleted file mode 100644 index 2945713dd8b..00000000000 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/StatementPatternCollector.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.helpers; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.rdf4j.query.algebra.Filter; -import org.eclipse.rdf4j.query.algebra.QueryModelNode; -import org.eclipse.rdf4j.query.algebra.StatementPattern; - -/** - * A QueryModelVisitor that collects StatementPattern's from a query model. StatementPatterns thet are part of - * filters/constraints are not included in the result. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class StatementPatternCollector extends AbstractQueryModelVisitor { - - public static List process(QueryModelNode node) { - StatementPatternCollector collector = new StatementPatternCollector(); - node.visit(collector); - return collector.getStatementPatterns(); - } - - private final List stPatterns = new ArrayList<>(); - - public List getStatementPatterns() { - return stPatterns; - } - - @Override - public void meet(Filter node) { - // Skip boolean constraints - node.getArg().visit(this); - } - - @Override - public void meet(StatementPattern node) { - stPatterns.add(node); - } -} diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/StatementPatternVisitor.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/StatementPatternVisitor.java index 3bfc26a1dac..271099f5862 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/StatementPatternVisitor.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/StatementPatternVisitor.java @@ -60,7 +60,6 @@ import org.eclipse.rdf4j.query.algebra.Lang; import org.eclipse.rdf4j.query.algebra.LangMatches; import org.eclipse.rdf4j.query.algebra.LeftJoin; -import org.eclipse.rdf4j.query.algebra.Like; import org.eclipse.rdf4j.query.algebra.ListMemberOperator; import org.eclipse.rdf4j.query.algebra.Load; import org.eclipse.rdf4j.query.algebra.LocalName; @@ -330,12 +329,6 @@ public void meet(LeftJoin node) throws Exception { ((BinaryTupleOperator) node).visitChildren(this); } - @Override - @Deprecated(forRemoval = true) - public void meet(Like node) throws Exception { - // From SERQL should not be seen - } - @Override public void meet(Load node) throws Exception { diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/TupleExprs.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/TupleExprs.java index dba21171e55..9bd90d23da9 100644 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/TupleExprs.java +++ b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/TupleExprs.java @@ -22,7 +22,6 @@ import org.eclipse.rdf4j.query.algebra.Exists; import org.eclipse.rdf4j.query.algebra.Extension; import org.eclipse.rdf4j.query.algebra.Filter; -import org.eclipse.rdf4j.query.algebra.GraphPatternGroupable; import org.eclipse.rdf4j.query.algebra.Join; import org.eclipse.rdf4j.query.algebra.Not; import org.eclipse.rdf4j.query.algebra.Projection; @@ -128,22 +127,6 @@ public static boolean isVariableScopeChange(TupleExpr expr) { return false; } - /** - * Verifies if the supplied {@link TupleExpr} represents a group graph pattern. - * - * @param expr a {@link TupleExpr} - * @return true if the {@link TupleExpr} is {@link GraphPatternGroupable} and has its graph pattern - * group flag set to true, false otherwise. - * @deprecated Use {@link #isVariableScopeChange(TupleExpr)} instead. - */ - @Deprecated(since = "3.2") - public static boolean isGraphPatternGroup(TupleExpr expr) { - if (expr instanceof GraphPatternGroupable) { - return ((GraphPatternGroupable) expr).isGraphPatternGroup(); - } - return false; - } - /** * Verifies if the supplied {@link TupleExpr} contains a {@link Projection}. If the supplied TupleExpr is a * {@link Join} or contains a {@link Join}, projections inside that Join's arguments will not be taken into account. diff --git a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/VarNameCollector.java b/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/VarNameCollector.java deleted file mode 100644 index 431fb44e863..00000000000 --- a/core/queryalgebra/model/src/main/java/org/eclipse/rdf4j/query/algebra/helpers/VarNameCollector.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.algebra.helpers; - -import java.util.LinkedHashSet; -import java.util.Set; - -import org.eclipse.rdf4j.query.algebra.QueryModelNode; -import org.eclipse.rdf4j.query.algebra.Var; - -/** - * A QueryModelVisitor that collects the names of (non-constant) variables that are used in a query model. - */ -@Deprecated(forRemoval = true, since = "4.1.0") -public class VarNameCollector extends AbstractQueryModelVisitor { - - public static Set process(QueryModelNode node) { - VarNameCollector collector = new VarNameCollector(); - node.visit(collector); - return collector.getVarNames(); - } - - private final Set varNames = new LinkedHashSet<>(); - - public Set getVarNames() { - return varNames; - } - - @Override - public void meet(Var var) { - if (!var.hasValue()) { - varNames.add(var.getName()); - } - } -} diff --git a/core/queryalgebra/model/src/test/java/org/eclipse/rdf4j/query/algebra/AbstractQueryModelNodeTest.java b/core/queryalgebra/model/src/test/java/org/eclipse/rdf4j/query/algebra/AbstractQueryModelNodeTest.java index c3b08b851f6..d259494fd67 100644 --- a/core/queryalgebra/model/src/test/java/org/eclipse/rdf4j/query/algebra/AbstractQueryModelNodeTest.java +++ b/core/queryalgebra/model/src/test/java/org/eclipse/rdf4j/query/algebra/AbstractQueryModelNodeTest.java @@ -12,6 +12,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import org.eclipse.rdf4j.model.vocabulary.RDF; import org.junit.jupiter.api.Test; public class AbstractQueryModelNodeTest { @@ -20,34 +21,34 @@ public class AbstractQueryModelNodeTest { public void getCardinalityString() { { - StatementPattern statementPattern = new StatementPattern(); + StatementPattern statementPattern = new StatementPattern(new Var("s"), new Var("p"), new Var("o")); String cardinalityString = statementPattern.toHumanReadbleNumber(statementPattern.getResultSizeEstimate()); assertEquals("UNKNOWN", cardinalityString); } { - StatementPattern statementPattern = new StatementPattern(); + StatementPattern statementPattern = new StatementPattern(new Var("s"), new Var("p"), new Var("o")); statementPattern.setResultSizeEstimate(1234); String cardinalityString = statementPattern.toHumanReadbleNumber(statementPattern.getResultSizeEstimate()); assertEquals("1.2K", cardinalityString); } { - StatementPattern statementPattern = new StatementPattern(); + StatementPattern statementPattern = new StatementPattern(new Var("s"), new Var("p"), new Var("o")); statementPattern.setResultSizeEstimate(1910000); String cardinalityString = statementPattern.toHumanReadbleNumber(statementPattern.getResultSizeEstimate()); assertEquals("1.9M", cardinalityString); } { - StatementPattern statementPattern = new StatementPattern(); + StatementPattern statementPattern = new StatementPattern(new Var("s"), new Var("p"), new Var("o")); statementPattern.setResultSizeEstimate(1990000); String cardinalityString = statementPattern.toHumanReadbleNumber(statementPattern.getResultSizeEstimate()); assertEquals("2.0M", cardinalityString); } { - StatementPattern statementPattern = new StatementPattern(); + StatementPattern statementPattern = new StatementPattern(new Var("s"), new Var("p"), new Var("o")); statementPattern.setResultSizeEstimate(912000); String cardinalityString = statementPattern.toHumanReadbleNumber(statementPattern.getResultSizeEstimate()); assertEquals("912.0K", cardinalityString); diff --git a/core/queryalgebra/model/src/test/java/org/eclipse/rdf4j/query/algebra/helpers/TupleExprsTest.java b/core/queryalgebra/model/src/test/java/org/eclipse/rdf4j/query/algebra/helpers/TupleExprsTest.java index d2c3f59d1e0..9a2d1a72332 100644 --- a/core/queryalgebra/model/src/test/java/org/eclipse/rdf4j/query/algebra/helpers/TupleExprsTest.java +++ b/core/queryalgebra/model/src/test/java/org/eclipse/rdf4j/query/algebra/helpers/TupleExprsTest.java @@ -38,7 +38,7 @@ public void isFilterExistsFunctionOnEmptyFilter() { @Test public void isFilterExistsFunctionOnNormalFilter() { Filter expr = new Filter(); - expr.setArg(new StatementPattern()); + expr.setArg(new StatementPattern(new Var("s"), new Var("p"), new Var("o"))); expr.setCondition(new Compare(new Var("x", f.createBNode()), new Var("y", f.createBNode()))); assertThat(isFilterExistsFunction(expr)).isFalse(); @@ -47,7 +47,7 @@ public void isFilterExistsFunctionOnNormalFilter() { @Test public void isFilterExistsFunctionOnNormalNot() { Filter expr = new Filter(); - expr.setArg(new StatementPattern()); + expr.setArg(new StatementPattern(new Var("s"), new Var("p"), new Var("o"))); expr.setCondition(new Not(new Compare(new Var("x", f.createBNode()), new Var("y", f.createBNode())))); assertThat(isFilterExistsFunction(expr)).isFalse(); @@ -56,8 +56,8 @@ public void isFilterExistsFunctionOnNormalNot() { @Test public void isFilterExistsFunctionOnExists() { Filter expr = new Filter(); - expr.setArg(new StatementPattern()); - expr.setCondition(new Exists(new StatementPattern())); + expr.setArg(new StatementPattern(new Var("s"), new Var("p"), new Var("o"))); + expr.setCondition(new Exists(new StatementPattern(new Var("s"), new Var("p"), new Var("o")))); assertThat(isFilterExistsFunction(expr)).isTrue(); @@ -66,8 +66,8 @@ public void isFilterExistsFunctionOnExists() { @Test public void isFilterExistsFunctionOnNotExist() { Filter expr = new Filter(); - expr.setArg(new StatementPattern()); - expr.setCondition(new Not(new Exists(new StatementPattern()))); + expr.setArg(new StatementPattern(new Var("s"), new Var("p"), new Var("o"))); + expr.setCondition(new Not(new Exists(new StatementPattern(new Var("s"), new Var("p"), new Var("o"))))); assertThat(isFilterExistsFunction(expr)).isTrue(); } diff --git a/core/queryparser/api/pom.xml b/core/queryparser/api/pom.xml index 640be54a6e4..4b9a1cbacb9 100644 --- a/core/queryparser/api/pom.xml +++ b/core/queryparser/api/pom.xml @@ -21,12 +21,4 @@ ${project.version} - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/queryparser/api/src/main/java/org/eclipse/rdf4j/query/impl/AbstractParserQuery.java b/core/queryparser/api/src/main/java/org/eclipse/rdf4j/query/impl/AbstractParserQuery.java index 1f59fa2cf59..2bdaf1cecee 100644 --- a/core/queryparser/api/src/main/java/org/eclipse/rdf4j/query/impl/AbstractParserQuery.java +++ b/core/queryparser/api/src/main/java/org/eclipse/rdf4j/query/impl/AbstractParserQuery.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.query.impl; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.TimeLimitIteration; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; @@ -36,8 +35,8 @@ public ParsedQuery getParsedQuery() { return parsedQuery; } - protected CloseableIteration enforceMaxQueryTime( - CloseableIteration bindingsIter) { + protected CloseableIteration enforceMaxQueryTime( + CloseableIteration bindingsIter) { if (getMaxExecutionTime() > 0) { bindingsIter = new QueryInterruptIteration(bindingsIter, 1000L * getMaxExecutionTime()); } @@ -67,9 +66,9 @@ public String toString() { } @Deprecated(since = "4.1.0") - protected class QueryInterruptIteration extends TimeLimitIteration { + protected class QueryInterruptIteration extends TimeLimitIteration { - public QueryInterruptIteration(Iteration iter, + public QueryInterruptIteration(CloseableIteration iter, long timeLimit) { super(iter, timeLimit); } diff --git a/core/queryparser/api/src/main/java/org/eclipse/rdf4j/query/parser/impl/AbstractParserQuery.java b/core/queryparser/api/src/main/java/org/eclipse/rdf4j/query/parser/impl/AbstractParserQuery.java index 88bcb297b44..d895c0d193d 100644 --- a/core/queryparser/api/src/main/java/org/eclipse/rdf4j/query/parser/impl/AbstractParserQuery.java +++ b/core/queryparser/api/src/main/java/org/eclipse/rdf4j/query/parser/impl/AbstractParserQuery.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.query.parser.impl; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.TimeLimitIteration; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; @@ -36,8 +35,8 @@ public ParsedQuery getParsedQuery() { return parsedQuery; } - protected CloseableIteration enforceMaxQueryTime( - CloseableIteration bindingsIter) { + protected CloseableIteration enforceMaxQueryTime( + CloseableIteration bindingsIter) { if (getMaxExecutionTime() > 0) { bindingsIter = new QueryInterruptIteration(bindingsIter, 1000L * getMaxExecutionTime()); } @@ -67,9 +66,9 @@ public String toString() { } @Deprecated(since = "4.1.0") - protected class QueryInterruptIteration extends TimeLimitIteration { + protected class QueryInterruptIteration extends TimeLimitIteration { - public QueryInterruptIteration(Iteration iter, + public QueryInterruptIteration(CloseableIteration iter, long timeLimit) { super(iter, timeLimit); } diff --git a/core/queryparser/api/src/test/java/org/eclipse/rdf4j/query/parser/QueryParserUtilTest.java b/core/queryparser/api/src/test/java/org/eclipse/rdf4j/query/parser/QueryParserUtilTest.java index d910e6db148..d15a4ba92d4 100644 --- a/core/queryparser/api/src/test/java/org/eclipse/rdf4j/query/parser/QueryParserUtilTest.java +++ b/core/queryparser/api/src/test/java/org/eclipse/rdf4j/query/parser/QueryParserUtilTest.java @@ -20,7 +20,7 @@ public class QueryParserUtilTest { @Test - public void testGetRestOfQueryString() throws Exception { + public void testGetRestOfQueryString() { String queryString = "# this is a comment\n" + "PREFIX : \n" + "# one more comment\r\n" + "SELECT * WHERE { ?s ?p ?o }"; diff --git a/core/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/TupleExprBuilder.java b/core/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/TupleExprBuilder.java index 77e5ede5b6c..6ab57a6c64c 100644 --- a/core/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/TupleExprBuilder.java +++ b/core/queryparser/sparql/src/main/java/org/eclipse/rdf4j/query/parser/sparql/TupleExprBuilder.java @@ -102,8 +102,8 @@ import org.eclipse.rdf4j.query.algebra.ZeroLengthPath; import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; import org.eclipse.rdf4j.query.algebra.helpers.TupleExprs; -import org.eclipse.rdf4j.query.algebra.helpers.VarNameCollector; import org.eclipse.rdf4j.query.algebra.helpers.collectors.StatementPatternCollector; +import org.eclipse.rdf4j.query.algebra.helpers.collectors.VarNameCollector; import org.eclipse.rdf4j.query.impl.ListBindingSet; import org.eclipse.rdf4j.query.parser.sparql.aggregate.CustomAggregateFunctionRegistry; import org.eclipse.rdf4j.query.parser.sparql.ast.ASTAbs; @@ -938,7 +938,7 @@ private List replaceSameTermVars(List statem if (subj.equals(left) || subj.equals(right)) { if (obj.equals(left) || obj.equals(right)) { - sp.setObjectVar(subj.clone()); + sp.replaceChildNode(sp.getObjectVar(), subj.clone()); } } } @@ -2334,9 +2334,7 @@ public ValueExpr visit(ASTNotIn node, Object data) throws VisitorException { @Override public Var visit(ASTVar node, Object data) throws VisitorException { - Var var = new Var(node.getName()); - var.setAnonymous(node.isAnonymous()); - return var; + return new Var(node.getName(), node.isAnonymous()); } @Override diff --git a/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/SPARQLParserTest.java b/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/SPARQLParserTest.java index 3b50f6d25e9..81912e2b320 100644 --- a/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/SPARQLParserTest.java +++ b/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/SPARQLParserTest.java @@ -88,12 +88,12 @@ public class SPARQLParserTest { private SPARQLParser parser; @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = new SPARQLParser(); } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { parser = null; } @@ -102,7 +102,7 @@ public void tearDown() throws Exception { * {@link org.eclipse.rdf4j.query.parser.sparql.SPARQLParser#parseQuery(java.lang.String, java.lang.String)} . */ @Test - public void testSourceStringAssignment() throws Exception { + public void testSourceStringAssignment() { String simpleSparqlQuery = "SELECT * WHERE {?X ?P ?Y }"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -111,7 +111,7 @@ public void testSourceStringAssignment() throws Exception { } @Test - public void testInsertDataLineNumberReporting() throws Exception { + public void testInsertDataLineNumberReporting() { String insertDataString = "INSERT DATA {\n incorrect reference }"; try { @@ -124,7 +124,7 @@ public void testInsertDataLineNumberReporting() throws Exception { } @Test - public void testDeleteDataLineNumberReporting() throws Exception { + public void testDeleteDataLineNumberReporting() { String deleteDataString = "DELETE DATA {\n incorrect reference }"; try { @@ -136,7 +136,7 @@ public void testDeleteDataLineNumberReporting() throws Exception { } @Test - public void testSES1922PathSequenceWithValueConstant() throws Exception { + public void testSES1922PathSequenceWithValueConstant() { StringBuilder qb = new StringBuilder(); qb.append("ASK {?A ()/ } "); @@ -162,7 +162,7 @@ public void testSES1922PathSequenceWithValueConstant() throws Exception { } @Test - public void testParsedBooleanQueryRootNode() throws Exception { + public void testParsedBooleanQueryRootNode() { StringBuilder qb = new StringBuilder(); qb.append("ASK {?a \"test\"}"); @@ -181,7 +181,7 @@ public void testParsedBooleanQueryRootNode() throws Exception { * @see #686 */ @Test - public void testParseWildcardSubselectInUpdate() throws Exception { + public void testParseWildcardSubselectInUpdate() { StringBuilder update = new StringBuilder(); update.append("INSERT { . } WHERE { SELECT * {?s ?p ?o } }"); @@ -205,7 +205,7 @@ public void testParseWildcardSubselectInUpdate() throws Exception { } @Test - public void testParseIntegerObjectValue() throws Exception { + public void testParseIntegerObjectValue() { // test that the parser correctly parses the object value as an integer, instead of as a decimal. String query = "select ?Concept where { ?Concept a 1. ?Concept2 a 1. } "; ParsedTupleQuery q = (ParsedTupleQuery) parser.parseQuery(query, null); @@ -218,7 +218,7 @@ public void testParseIntegerObjectValue() throws Exception { } @Test - public void testParsedTupleQueryRootNode() throws Exception { + public void testParsedTupleQueryRootNode() { StringBuilder qb = new StringBuilder(); qb.append("SELECT * {?a \"test\"}"); @@ -233,7 +233,7 @@ public void testParsedTupleQueryRootNode() throws Exception { } @Test - public void testParsedGraphQueryRootNode() throws Exception { + public void testParsedGraphQueryRootNode() { StringBuilder qb = new StringBuilder(); qb.append("CONSTRUCT WHERE {?a \"test\"}"); @@ -249,7 +249,7 @@ public void testParsedGraphQueryRootNode() throws Exception { } @Test - public void testOrderByWithAliases1() throws Exception { + public void testOrderByWithAliases1() { String queryString = " SELECT ?x (SUM(?v1)/COUNT(?v1) as ?r) WHERE { ?x ?v1 } GROUP BY ?x ORDER BY ?r"; ParsedQuery query = parser.parseQuery(queryString, null); @@ -271,7 +271,7 @@ public void testOrderByWithAliases1() throws Exception { } @Test - public void testOrderByWithAliases2() throws Exception { + public void testOrderByWithAliases2() { String queryString = "SELECT (?l AS ?v)\n" + "WHERE { ?s rdfs:label ?l. }\n" + "ORDER BY ?v"; @@ -293,7 +293,7 @@ public void testOrderByWithAliases2() throws Exception { } @Test - public void testSES1927UnequalLiteralValueConstants1() throws Exception { + public void testSES1927UnequalLiteralValueConstants1() { StringBuilder qb = new StringBuilder(); qb.append("ASK {?a \"test\". ?a \"test\"@en .} "); @@ -320,7 +320,7 @@ public void testSES1927UnequalLiteralValueConstants1() throws Exception { } @Test - public void testSES1927UnequalLiteralValueConstants2() throws Exception { + public void testSES1927UnequalLiteralValueConstants2() { StringBuilder qb = new StringBuilder(); qb.append("ASK {?a \"test\". ?a \"test\"^^ .} "); @@ -347,7 +347,7 @@ public void testSES1927UnequalLiteralValueConstants2() throws Exception { } @Test - public void testLongUnicode() throws Exception { + public void testLongUnicode() { ParsedUpdate ru = parser.parseUpdate("insert data { \"\\U0001F61F\" .}", "urn:test"); InsertData insertData = (InsertData) ru.getUpdateExprs().get(0); @@ -356,7 +356,7 @@ public void testLongUnicode() throws Exception { } @Test - public void testAdditionalWhitespace_Not_In() throws Exception { + public void testAdditionalWhitespace_Not_In() { String query = "SELECT * WHERE { ?s ?p ?o. FILTER(?o NOT IN (1, 2, 3)) }"; ParsedQuery parsedQuery = parser.parseQuery(query, null); @@ -368,7 +368,7 @@ public void testAdditionalWhitespace_Not_In() throws Exception { } @Test - public void testAdditionalWhitespace_Not_Exists() throws Exception { + public void testAdditionalWhitespace_Not_Exists() { String query = "SELECT * WHERE { ?s ?p ?o. FILTER NOT EXISTS { ?s ?p ?o } }"; ParsedQuery parsedQuery = parser.parseQuery(query, null); diff --git a/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TestPropPathMisbehaviour.java b/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TestPropPathMisbehaviour.java index bcd8f708814..f208983655b 100644 --- a/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TestPropPathMisbehaviour.java +++ b/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TestPropPathMisbehaviour.java @@ -31,18 +31,16 @@ public class TestPropPathMisbehaviour { private SPARQLParser parser; /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = new SPARQLParser(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { parser = null; } diff --git a/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TestSparqlStarParser.java b/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TestSparqlStarParser.java index 43d2a5b0bfe..383fc2de568 100644 --- a/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TestSparqlStarParser.java +++ b/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TestSparqlStarParser.java @@ -58,18 +58,16 @@ public class TestSparqlStarParser { private SPARQLParser parser; /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = new SPARQLParser(); } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { parser = null; } @@ -89,7 +87,7 @@ public void tearDown() throws Exception { * @throws Exception */ @Test - public void testUseInProjection() throws Exception { + public void testUseInProjection() { String simpleSparqlQuery = "SELECT (<< 1>> as ?ref) WHERE {}"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -134,7 +132,7 @@ public void testUseInProjection() throws Exception { * @throws Exception */ @Test - public void testUseInValues() throws Exception { + public void testUseInValues() { String simpleSparqlQuery = "SELECT ?ref WHERE { values ?ref {<< 1>>} }"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -185,7 +183,7 @@ public void testUseInValues() throws Exception { * @throws Exception */ @Test - public void testUseInBind() throws Exception { + public void testUseInBind() { String simpleSparqlQuery = "SELECT ?ref WHERE { bind(<< 1>> as ?ref)}"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -236,7 +234,7 @@ public void testUseInBind() throws Exception { * @throws Exception */ @Test - public void testUseInBindWithVars() throws Exception { + public void testUseInBindWithVars() { String simpleSparqlQuery = "SELECT * WHERE { bind(<> as ?ref)}"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -298,7 +296,7 @@ public void testUseInBindWithVars() throws Exception { * @throws Exception */ @Test - public void testUseInStatementPatternWithVars() throws Exception { + public void testUseInStatementPatternWithVars() { String simpleSparqlQuery = "SELECT * WHERE { <> ?val}"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -367,7 +365,7 @@ public void testUseInStatementPatternWithVars() throws Exception { * @throws Exception */ @Test - public void testUseNestedInStatementPatternWithVars() throws Exception { + public void testUseNestedInStatementPatternWithVars() { String simpleSparqlQuery = "SELECT * WHERE { <<<> ?q ?r>> ?val}"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -443,7 +441,7 @@ public void testUseNestedInStatementPatternWithVars() throws Exception { * @throws Exception */ @Test - public void testUseInConstructFromStatementPattern() throws Exception { + public void testUseInConstructFromStatementPattern() { String simpleSparqlQuery = "CONSTRUCT {<> } WHERE {?s ?p ?o}"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -526,7 +524,7 @@ public void testUseInConstructFromStatementPattern() throws Exception { * @throws Exception */ @Test - public void testUseInInsertFromStatementPattern() throws Exception { + public void testUseInInsertFromStatementPattern() { String simpleSparqlQuery = "Insert {<> } WHERE {?s ?p ?o}"; ParsedUpdate q = parser.parseUpdate(simpleSparqlQuery, null); @@ -596,7 +594,7 @@ public void testUseInInsertFromStatementPattern() throws Exception { * @throws Exception */ @Test - public void testUseInDeleteFromStatementPattern() throws Exception { + public void testUseInDeleteFromStatementPattern() { String simpleSparqlQuery = "DELETE {<> } WHERE {?s ?p ?o}"; ParsedUpdate q = parser.parseUpdate(simpleSparqlQuery, null); @@ -666,7 +664,7 @@ public void testUseInDeleteFromStatementPattern() throws Exception { * @throws Exception */ @Test - public void testUseInGroupByFromBindWithVars() throws Exception { + public void testUseInGroupByFromBindWithVars() { String simpleSparqlQuery = "SELECT ?ref (count( distinct ?p) as ?count) WHERE { bind(<> as ?ref)} group by ?ref"; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -750,7 +748,7 @@ public void testUseInGroupByFromBindWithVars() throws Exception { * @throws Exception */ @Test - public void testUseInExists() throws Exception { + public void testUseInExists() { String simpleSparqlQuery = "SELECT * WHERE { ?s ?p ?o . filter exists {<>> ?q}} "; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -816,7 +814,7 @@ public void testUseInExists() throws Exception { * @throws Exception */ @Test - public void testUseInSTR() throws Exception { + public void testUseInSTR() { String simpleSparqlQuery = "SELECT (str(<< >>) as ?str) WHERE { } "; ParsedQuery q = parser.parseQuery(simpleSparqlQuery, null); @@ -871,7 +869,7 @@ public void testUseInSTR() throws Exception { * @throws Exception */ @Test - public void testUpdateWithTripleRefEmptyHead() throws Exception { + public void testUpdateWithTripleRefEmptyHead() { String simpleSparqlUpdate = "insert {} where {<< >> 1}"; ParsedUpdate q = parser.parseUpdate(simpleSparqlUpdate, null); @@ -923,7 +921,7 @@ public void testUpdateWithTripleRefEmptyHead() throws Exception { * @throws Exception */ @Test - public void testUpdateWithTripleRefNonEmptyHead() throws Exception { + public void testUpdateWithTripleRefNonEmptyHead() { String simpleSparqlUpdate = "insert {<< >> 1} where {<< >> 1}"; ParsedUpdate q = parser.parseUpdate(simpleSparqlUpdate, null); diff --git a/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TupleExprBuilderTest.java b/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TupleExprBuilderTest.java index afaca7d955e..b1d24aa3ac5 100644 --- a/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TupleExprBuilderTest.java +++ b/core/queryparser/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/TupleExprBuilderTest.java @@ -253,7 +253,7 @@ public void testServiceGraphPatternStringDetection4() throws TokenMgrError, Pars } @Test - public void testServiceGraphPatternChopping() throws Exception { + public void testServiceGraphPatternChopping() { // just for construction Service service = new Service(new Var(null, null, false, false), new SingletonSet(), "", null, null, false); diff --git a/core/queryrender/src/main/java/org/eclipse/rdf4j/queryrender/BaseTupleExprRenderer.java b/core/queryrender/src/main/java/org/eclipse/rdf4j/queryrender/BaseTupleExprRenderer.java index 14c1089e59b..4e5f4edeed8 100644 --- a/core/queryrender/src/main/java/org/eclipse/rdf4j/queryrender/BaseTupleExprRenderer.java +++ b/core/queryrender/src/main/java/org/eclipse/rdf4j/queryrender/BaseTupleExprRenderer.java @@ -184,9 +184,8 @@ public static String scrubVarName(String theName) { * * @param theValue the ValueExpr to convert * @return the expression as a Value, or null if it cannot be converted - * @throws Exception if there is an error converting to a Value */ - private Value asValue(ValueExpr theValue) throws Exception { + private Value asValue(ValueExpr theValue) { if (theValue instanceof ValueConstant) { return ((ValueConstant) theValue).getValue(); } else if (theValue instanceof Var) { diff --git a/core/queryrender/src/main/java/org/eclipse/rdf4j/queryrender/sparql/experimental/SparqlQueryRenderer.java b/core/queryrender/src/main/java/org/eclipse/rdf4j/queryrender/sparql/experimental/SparqlQueryRenderer.java index a47e9364c8e..e07445934b8 100644 --- a/core/queryrender/src/main/java/org/eclipse/rdf4j/queryrender/sparql/experimental/SparqlQueryRenderer.java +++ b/core/queryrender/src/main/java/org/eclipse/rdf4j/queryrender/sparql/experimental/SparqlQueryRenderer.java @@ -47,7 +47,7 @@ public QueryLanguage getLanguage() { } @Override - public String render(ParsedQuery theQuery) throws Exception { + public String render(ParsedQuery theQuery) { if (theQuery instanceof ParsedTupleQuery) { ParsedQueryPreprocessor parserVisitor = new ParsedQueryPreprocessor(); PreprocessedQuerySerializer serializerVisitor = new PreprocessedQuerySerializer(); @@ -71,7 +71,7 @@ public String render(ParsedQuery theQuery) throws Exception { } } - public String render(ParsedOperation theOperation) throws Exception { + public String render(ParsedOperation theOperation) { if (theOperation instanceof ParsedQuery) { return render((ParsedQuery) theOperation); } else if (theOperation instanceof ParsedUpdate) { @@ -81,7 +81,7 @@ public String render(ParsedOperation theOperation) throws Exception { throw new UnsupportedOperationException("Only ParsedQuery and ParsedUpdate operations are supported"); } - private String renderUpdate(ParsedUpdate theUpdate) throws Exception { + private String renderUpdate(ParsedUpdate theUpdate) { StringBuilder exprBuilder = new StringBuilder(); boolean multipleExpressions = (theUpdate.getUpdateExprs().size() > 1); @@ -99,7 +99,7 @@ private String renderUpdate(ParsedUpdate theUpdate) throws Exception { } @Override - public String render(TupleExpr theExpr) throws Exception { + public String render(TupleExpr theExpr) { ParsedQueryPreprocessor parserVisitor = new ParsedQueryPreprocessor(); PreprocessedQuerySerializer serializerVisitor = new PreprocessedQuerySerializer(); SerializableParsedTupleQuery toSerialize = parserVisitor.transformToSerialize(theExpr); @@ -107,7 +107,7 @@ public String render(TupleExpr theExpr) throws Exception { } @Override - public String renderValueExpr(ValueExpr theExpr) throws Exception { + public String renderValueExpr(ValueExpr theExpr) { PreprocessedQuerySerializer serializerVisitor = new PreprocessedQuerySerializer(); theExpr.visit(serializerVisitor); return serializerVisitor.builder.toString(); diff --git a/core/queryresultio/api/pom.xml b/core/queryresultio/api/pom.xml index 5e297ef1e5b..523f4037078 100644 --- a/core/queryresultio/api/pom.xml +++ b/core/queryresultio/api/pom.xml @@ -31,12 +31,4 @@ ${project.version} - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/queryresultio/api/src/main/java/org/eclipse/rdf4j/query/resultio/helpers/BackgroundTupleResult.java b/core/queryresultio/api/src/main/java/org/eclipse/rdf4j/query/resultio/helpers/BackgroundTupleResult.java index af42626fa4e..d7bb190a2ba 100644 --- a/core/queryresultio/api/src/main/java/org/eclipse/rdf4j/query/resultio/helpers/BackgroundTupleResult.java +++ b/core/queryresultio/api/src/main/java/org/eclipse/rdf4j/query/resultio/helpers/BackgroundTupleResult.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.query.resultio.helpers; import java.io.InputStream; -import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -46,8 +45,8 @@ public class BackgroundTupleResult extends IteratingTupleQueryResult implements private final CountDownLatch finishedParsing = new CountDownLatch(1); - public BackgroundTupleResult(TupleQueryResultParser parser, InputStream in, WeakReference callerRef) { - this(new QueueCursor<>(10, callerRef), parser, in); + public BackgroundTupleResult(TupleQueryResultParser parser, InputStream in) { + this(new QueueCursor<>(10), parser, in); } public BackgroundTupleResult(QueueCursor queue, TupleQueryResultParser parser, InputStream in) { diff --git a/core/queryresultio/sparqljson/src/main/java/org/eclipse/rdf4j/query/resultio/sparqljson/AbstractSPARQLJSONParser.java b/core/queryresultio/sparqljson/src/main/java/org/eclipse/rdf4j/query/resultio/sparqljson/AbstractSPARQLJSONParser.java index 9a9c60c90ea..76b36c1a057 100644 --- a/core/queryresultio/sparqljson/src/main/java/org/eclipse/rdf4j/query/resultio/sparqljson/AbstractSPARQLJSONParser.java +++ b/core/queryresultio/sparqljson/src/main/java/org/eclipse/rdf4j/query/resultio/sparqljson/AbstractSPARQLJSONParser.java @@ -471,7 +471,7 @@ private Value parseValue(String type, String value, String language, String data // For broken SPARQL endpoints which return LANGSTRING without a language, fall back // to using STRING as the datatype - if (RDF.LANGSTRING.equals(datatypeIri) && language == null) { + if (RDF.LANGSTRING.equals(datatypeIri)) { logger.debug( "rdf:langString typed literal missing language tag: '{}'. Falling back to xsd:string.", StringUtils.abbreviate(value, 10) diff --git a/core/queryresultio/sparqljson/src/test/java/org/eclipse/rdf4j/query/resultio/sparqljson/SPARQLJSONParserCustomTest.java b/core/queryresultio/sparqljson/src/test/java/org/eclipse/rdf4j/query/resultio/sparqljson/SPARQLJSONParserCustomTest.java index 89c972f9dc0..67d70aa5813 100644 --- a/core/queryresultio/sparqljson/src/test/java/org/eclipse/rdf4j/query/resultio/sparqljson/SPARQLJSONParserCustomTest.java +++ b/core/queryresultio/sparqljson/src/test/java/org/eclipse/rdf4j/query/resultio/sparqljson/SPARQLJSONParserCustomTest.java @@ -118,7 +118,7 @@ public class SPARQLJSONParserCustomTest { .createLiteral("42\u0009", XSD.STRING); @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = QueryResultIO.createTupleParser(TupleQueryResultFormat.JSON); errors = new ParseErrorCollector(); results = new QueryResultCollector(); @@ -126,7 +126,7 @@ public void setUp() throws Exception { parser.setQueryResultHandler(results); } - private void verifyParseResults(String bindingName, Value nextObject) throws Exception { + private void verifyParseResults(String bindingName, Value nextObject) { assertEquals(0, errors.getWarnings().size()); assertEquals(0, errors.getErrors().size()); assertEquals(0, errors.getFatalErrors().size()); @@ -142,13 +142,13 @@ private InputStream stringToInputStream(String input) { } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { // 11 supported in AbstractSPARQLJSONParser + 0 from AbstractQueryResultParser assertEquals(11, parser.getSupportedSettings().size()); } @Test - public void testAllowBackslashEscapingAnyCharacterDefault() throws Exception { + public void testAllowBackslashEscapingAnyCharacterDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(BACKSLASH_ESCAPED_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -162,7 +162,7 @@ public void testAllowBackslashEscapingAnyCharacterEnabled() throws Exception { } @Test - public void testAllowBackslashEscapingAnyCharacterDisabled() throws Exception { + public void testAllowBackslashEscapingAnyCharacterDisabled() { parser.set(JSONSettings.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(BACKSLASH_ESCAPED_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -170,7 +170,7 @@ public void testAllowBackslashEscapingAnyCharacterDisabled() throws Exception { } @Test - public void testAllowCommentsDefault() throws Exception { + public void testAllowCommentsDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(COMMENTS_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -184,7 +184,7 @@ public void testAllowCommentsEnabled() throws Exception { } @Test - public void testAllowCommentsDisabled() throws Exception { + public void testAllowCommentsDisabled() { parser.set(JSONSettings.ALLOW_COMMENTS, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(COMMENTS_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -192,7 +192,7 @@ public void testAllowCommentsDisabled() throws Exception { } @Test - public void testAllowNonNumericNumbersDefault() throws Exception { + public void testAllowNonNumericNumbersDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(NON_NUMERIC_NUMBERS_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -206,7 +206,7 @@ public void testAllowNonNumericNumbersEnabled() throws Exception { } @Test - public void testAllowNonNumericNumbersDisabled() throws Exception { + public void testAllowNonNumericNumbersDisabled() { parser.set(JSONSettings.ALLOW_NON_NUMERIC_NUMBERS, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(NON_NUMERIC_NUMBERS_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -214,7 +214,7 @@ public void testAllowNonNumericNumbersDisabled() throws Exception { } @Test - public void testAllowNumericLeadingZeroesDefault() throws Exception { + public void testAllowNumericLeadingZeroesDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(NUMERIC_LEADING_ZEROES_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -228,7 +228,7 @@ public void testAllowNumericLeadingZeroesEnabled() throws Exception { } @Test - public void testAllowNumericLeadingZeroesDisabled() throws Exception { + public void testAllowNumericLeadingZeroesDisabled() { parser.set(JSONSettings.ALLOW_NUMERIC_LEADING_ZEROS, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(NUMERIC_LEADING_ZEROES_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -236,7 +236,7 @@ public void testAllowNumericLeadingZeroesDisabled() throws Exception { } @Test - public void testAllowSingleQuotesDefault() throws Exception { + public void testAllowSingleQuotesDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(SINGLE_QUOTES_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -250,7 +250,7 @@ public void testAllowSingleQuotesEnabled() throws Exception { } @Test - public void testAllowSingleQuotesDisabled() throws Exception { + public void testAllowSingleQuotesDisabled() { parser.set(JSONSettings.ALLOW_SINGLE_QUOTES, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(SINGLE_QUOTES_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -258,7 +258,7 @@ public void testAllowSingleQuotesDisabled() throws Exception { } @Test - public void testAllowUnquotedControlCharactersDefault() throws Exception { + public void testAllowUnquotedControlCharactersDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(UNQUOTED_CONTROL_CHARS_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -272,7 +272,7 @@ public void testAllowUnquotedControlCharactersEnabled() throws Exception { } @Test - public void testAllowUnquotedControlCharactersDisabled() throws Exception { + public void testAllowUnquotedControlCharactersDisabled() { parser.set(JSONSettings.ALLOW_UNQUOTED_CONTROL_CHARS, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(UNQUOTED_CONTROL_CHARS_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -280,7 +280,7 @@ public void testAllowUnquotedControlCharactersDisabled() throws Exception { } @Test - public void testAllowUnquotedFieldNamesDefault() throws Exception { + public void testAllowUnquotedFieldNamesDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(UNQUOTED_FIELD_NAMES_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -294,7 +294,7 @@ public void testAllowUnquotedFieldNamesEnabled() throws Exception { } @Test - public void testAllowUnquotedFieldNamesDisabled() throws Exception { + public void testAllowUnquotedFieldNamesDisabled() { parser.set(JSONSettings.ALLOW_UNQUOTED_FIELD_NAMES, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(UNQUOTED_FIELD_NAMES_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -302,7 +302,7 @@ public void testAllowUnquotedFieldNamesDisabled() throws Exception { } @Test - public void testAllowYamlCommentsDefault() throws Exception { + public void testAllowYamlCommentsDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(YAML_COMMENTS_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -316,7 +316,7 @@ public void testAllowYamlCommentsEnabled() throws Exception { } @Test - public void testAllowYamlCommentsDisabled() throws Exception { + public void testAllowYamlCommentsDisabled() { parser.set(JSONSettings.ALLOW_YAML_COMMENTS, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(YAML_COMMENTS_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -324,7 +324,7 @@ public void testAllowYamlCommentsDisabled() throws Exception { } @Test - public void testAllowTrailingCommaDefault() throws Exception { + public void testAllowTrailingCommaDefault() { assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(TRAILING_COMMA_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) .hasMessage("Could not parse SPARQL/JSON"); @@ -338,7 +338,7 @@ public void testAllowTrailingCommaEnabled() throws Exception { } @Test - public void testAllowTrailingCommaDisabled() throws Exception { + public void testAllowTrailingCommaDisabled() { parser.set(JSONSettings.ALLOW_TRAILING_COMMA, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(TRAILING_COMMA_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -397,7 +397,7 @@ public void testIncludeSourceLocationDisabled() throws Exception { } @Test - public void testStrictDuplicateDetectionDefault() throws Exception { + public void testStrictDuplicateDetectionDefault() { parser.set(JSONSettings.STRICT_DUPLICATE_DETECTION, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(STRICT_DUPLICATE_DETECTION_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -405,7 +405,7 @@ public void testStrictDuplicateDetectionDefault() throws Exception { } @Test - public void testStrictDuplicateDetectionEnabled() throws Exception { + public void testStrictDuplicateDetectionEnabled() { parser.set(JSONSettings.STRICT_DUPLICATE_DETECTION, true); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(STRICT_DUPLICATE_DETECTION_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) @@ -413,7 +413,7 @@ public void testStrictDuplicateDetectionEnabled() throws Exception { } @Test - public void testStrictDuplicateDetectionDisabled() throws Exception { + public void testStrictDuplicateDetectionDisabled() { parser.set(JSONSettings.STRICT_DUPLICATE_DETECTION, false); assertThatThrownBy(() -> parser.parseQueryResult(stringToInputStream(STRICT_DUPLICATE_DETECTION_TEST_STRING))) .isInstanceOf(QueryResultParseException.class) diff --git a/core/queryresultio/sparqljson/src/test/java/org/eclipse/rdf4j/query/resultio/sparqljson/SPARQLJSONTupleTest.java b/core/queryresultio/sparqljson/src/test/java/org/eclipse/rdf4j/query/resultio/sparqljson/SPARQLJSONTupleTest.java index 03926b7c2c4..050f0237250 100644 --- a/core/queryresultio/sparqljson/src/test/java/org/eclipse/rdf4j/query/resultio/sparqljson/SPARQLJSONTupleTest.java +++ b/core/queryresultio/sparqljson/src/test/java/org/eclipse/rdf4j/query/resultio/sparqljson/SPARQLJSONTupleTest.java @@ -309,7 +309,7 @@ public void testRDFStar_extendedFormatRDF4J() throws Exception { } @Test - public void testRDFStar_extendedFormatRDF4J_incompleteTriple() throws Exception { + public void testRDFStar_extendedFormatRDF4J_incompleteTriple() { SPARQLResultsJSONParser parser = new SPARQLResultsJSONParser(SimpleValueFactory.getInstance()); QueryResultCollector handler = new QueryResultCollector(); parser.setQueryResultHandler(handler); @@ -322,7 +322,7 @@ public void testRDFStar_extendedFormatRDF4J_incompleteTriple() throws Exception } @Test - public void testRDFStar_extendedFormatRDF4J_doubleSubject() throws Exception { + public void testRDFStar_extendedFormatRDF4J_doubleSubject() { SPARQLResultsJSONParser parser = new SPARQLResultsJSONParser(SimpleValueFactory.getInstance()); QueryResultCollector handler = new QueryResultCollector(); parser.setQueryResultHandler(handler); diff --git a/core/queryresultio/sparqlxml/src/test/java/org/eclipse/rdf4j/query/resultio/sparqlxml/SPARQLXMLParserCustomTest.java b/core/queryresultio/sparqlxml/src/test/java/org/eclipse/rdf4j/query/resultio/sparqlxml/SPARQLXMLParserCustomTest.java index 277be3b33ca..8bd9997a60d 100644 --- a/core/queryresultio/sparqlxml/src/test/java/org/eclipse/rdf4j/query/resultio/sparqlxml/SPARQLXMLParserCustomTest.java +++ b/core/queryresultio/sparqlxml/src/test/java/org/eclipse/rdf4j/query/resultio/sparqlxml/SPARQLXMLParserCustomTest.java @@ -181,7 +181,7 @@ public void testEntityExpansionNoSecureProcessing() throws Exception { } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { assertTrue(QueryResultIO.createTupleParser(TupleQueryResultFormat.SPARQL).getSupportedSettings().size() > 0); } } diff --git a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleBackgroundTest.java b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleBackgroundTest.java index ec8e0f2a8d8..3e43c729d38 100644 --- a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleBackgroundTest.java +++ b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleBackgroundTest.java @@ -59,7 +59,7 @@ protected BooleanQueryResultFormat getMatchingBooleanFormatOrNull() { } @Test - public void testEndOfLine() throws Exception { + public void testEndOfLine() { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); @@ -72,7 +72,7 @@ public void testEndOfLine() throws Exception { } @Test - public void testEmptyResults() throws Exception { + public void testEmptyResults() { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); @@ -85,7 +85,7 @@ public void testEmptyResults() throws Exception { } @Test - public void testSingleVarResults() throws Exception { + public void testSingleVarResults() { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); @@ -104,7 +104,7 @@ public void testSingleVarResults() throws Exception { } @Test - public void testmultipleVarResults() throws Exception { + public void testmultipleVarResults() { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); diff --git a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleQueryResultWriterTest.java b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleQueryResultWriterTest.java index 3cb1ba73870..5a9f3d2761f 100644 --- a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleQueryResultWriterTest.java +++ b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleQueryResultWriterTest.java @@ -36,13 +36,13 @@ protected TupleQueryResultWriterFactory getWriterFactory() { @Override @Disabled("pending implementation of RDF-star extensions for the csv format") @Test - public void testRDFStarHandling_NoEncoding() throws Exception { + public void testRDFStarHandling_NoEncoding() { } @Override @Disabled("pending implementation of RDF-star extensions for the csv format") @Test - public void testRDFStarHandling_DeepNesting() throws Exception { + public void testRDFStarHandling_DeepNesting() { } @Override diff --git a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleTest.java b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleTest.java index fa9db139c7b..2280c3800f1 100644 --- a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleTest.java +++ b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/csv/SPARQLCSVTupleTest.java @@ -59,7 +59,7 @@ protected BooleanQueryResultFormat getMatchingBooleanFormatOrNull() { } @Test - public void testEndOfLine() throws Exception { + public void testEndOfLine() { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); @@ -72,7 +72,7 @@ public void testEndOfLine() throws Exception { } @Test - public void testEmptyResults() throws Exception { + public void testEmptyResults() { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); @@ -85,7 +85,7 @@ public void testEmptyResults() throws Exception { } @Test - public void testSingleVarResults() throws Exception { + public void testSingleVarResults() { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); @@ -104,7 +104,7 @@ public void testSingleVarResults() throws Exception { } @Test - public void testmultipleVarResults() throws Exception { + public void testmultipleVarResults() { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); diff --git a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVTupleBackgroundTest.java b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVTupleBackgroundTest.java index ad737292c76..858ce74271b 100644 --- a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVTupleBackgroundTest.java +++ b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVTupleBackgroundTest.java @@ -16,7 +16,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.regex.Pattern; @@ -64,17 +63,17 @@ protected TupleQueryResult parseTupleInternal(TupleQueryResultFormat format, Inp } @Test - public void testEndOfLine() throws Exception { + public void testEndOfLine() { assertEquals("\n", toString(createTupleNoBindingSets()).replaceAll("\\S+|\t", "")); } @Test - public void testEmptyResults() throws Exception { + public void testEmptyResults() { assertRegex("\\?a\t\\?b\t\\?c\n?", toString(createTupleNoBindingSets())); } @Test - public void testSingleVarResults() throws Exception { + public void testSingleVarResults() { assertRegex("\\?a\n" + "\n" + "(2.0(E0)?|\"2.0\"\\^\\^)\n" + "_:bnode3\n" + "\"?''single-quoted string(\"(\\^\\^)?)?\n" + "\"\\\\\"\\\\\"double-quoted string\"(\\^\\^)?\n" @@ -87,7 +86,7 @@ public void testSingleVarResults() throws Exception { } @Test - public void testmultipleVarResults() throws Exception { + public void testmultipleVarResults() { assertRegex("\\?a\t\\?b\t\\?c\n" + "\t_:bnode\t(baz|\"baz\"(\\^\\^)?)\n" + "(1|\"1\"\\^\\^)\t\t\"Hello World!\"@en\n" @@ -98,7 +97,7 @@ public void testmultipleVarResults() throws Exception { } private String toString(TupleQueryResult results) throws QueryResultHandlerException, - TupleQueryResultHandlerException, QueryEvaluationException, UnsupportedEncodingException { + TupleQueryResultHandlerException, QueryEvaluationException { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); @@ -118,8 +117,7 @@ private void assertRegex(String pattern, String actual) { @Override protected void assertQueryResultsEqual(TupleQueryResult expected, TupleQueryResult output) - throws QueryEvaluationException, TupleQueryResultHandlerException, QueryResultHandlerException, - UnsupportedEncodingException { + throws QueryEvaluationException, TupleQueryResultHandlerException, QueryResultHandlerException { MutableTupleQueryResult r1 = new MutableTupleQueryResult(expected); MutableTupleQueryResult r2 = new MutableTupleQueryResult(output); if (!QueryResults.equals(r1, r2)) { diff --git a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVTupleTest.java b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVTupleTest.java index ad857047503..90b74ceef1a 100644 --- a/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVTupleTest.java +++ b/core/queryresultio/text/src/test/java/org/eclipse/rdf4j/query/resultio/text/tsv/SPARQLTSVTupleTest.java @@ -14,7 +14,6 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.regex.Pattern; @@ -54,17 +53,17 @@ protected BooleanQueryResultFormat getMatchingBooleanFormatOrNull() { } @Test - public void testEndOfLine() throws Exception { + public void testEndOfLine() { assertEquals("\n", toString(createTupleNoBindingSets()).replaceAll("\\S+|\t", "")); } @Test - public void testEmptyResults() throws Exception { + public void testEmptyResults() { assertRegex("\\?a\t\\?b\t\\?c\n?", toString(createTupleNoBindingSets())); } @Test - public void testSingleVarResults() throws Exception { + public void testSingleVarResults() { assertRegex("\\?a\n" + "\n" + "(2.0(E0)?|\"2.0\"\\^\\^)\n" + "_:bnode3\n" + "\"?''single-quoted string(\"(\\^\\^)?)?\n" + "\"\\\\\"\\\\\"double-quoted string\"(\\^\\^)?\n" @@ -77,7 +76,7 @@ public void testSingleVarResults() throws Exception { } @Test - public void testmultipleVarResults() throws Exception { + public void testmultipleVarResults() { assertRegex("\\?a\t\\?b\t\\?c\n" + "\t_:bnode\t(baz|\"baz\"(\\^\\^)?)\n" + "(1|\"1\"\\^\\^)\t\t\"Hello World!\"@en\n" @@ -88,7 +87,7 @@ public void testmultipleVarResults() throws Exception { } private String toString(TupleQueryResult results) throws QueryResultHandlerException, - TupleQueryResultHandlerException, QueryEvaluationException, UnsupportedEncodingException { + TupleQueryResultHandlerException, QueryEvaluationException { TupleQueryResultFormat format = getTupleFormat(); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); @@ -108,8 +107,7 @@ private void assertRegex(String pattern, String actual) { @Override protected void assertQueryResultsEqual(TupleQueryResult expected, TupleQueryResult output) - throws QueryEvaluationException, TupleQueryResultHandlerException, QueryResultHandlerException, - UnsupportedEncodingException { + throws QueryEvaluationException, TupleQueryResultHandlerException, QueryResultHandlerException { MutableTupleQueryResult r1 = new MutableTupleQueryResult(expected); MutableTupleQueryResult r2 = new MutableTupleQueryResult(output); if (!QueryResults.equals(r1, r2)) { diff --git a/core/repository/api/pom.xml b/core/repository/api/pom.xml index f4947b35455..6f5e94a505f 100644 --- a/core/repository/api/pom.xml +++ b/core/repository/api/pom.xml @@ -68,12 +68,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/RepositoryConnection.java b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/RepositoryConnection.java index 06e924077cf..0f1107e2ba8 100644 --- a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/RepositoryConnection.java +++ b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/RepositoryConnection.java @@ -17,7 +17,6 @@ import java.net.URL; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.transaction.IsolationLevel; import org.eclipse.rdf4j.common.transaction.TransactionSetting; import org.eclipse.rdf4j.model.IRI; @@ -953,24 +952,6 @@ void add(File file, String baseURI, RDFFormat dataFormat, Resource... contexts) */ void add(Iterable statements, Resource... contexts) throws RepositoryException; - /** - * Adds the supplied statements to this repository, optionally to one or more named contexts. - * - * @param statements The statements to add. In case the iteration is a - * {@link org.eclipse.rdf4j.common.iteration.CloseableIteration}, it will be closed before this - * method returns. - * @param contexts The contexts to add the statements to. Note that this parameter is a vararg and as such is - * optional. If no contexts are specified, each statement is added to any context specified in the - * statement, or if the statement contains no context, it is added without context. If one or more - * contexts are specified each statement is added to these contexts, ignoring any context - * information in the statement itself. ignored. - * @throws RepositoryException If the statements could not be added to the repository, for example because the - * repository is not writable. - */ - @Deprecated(since = "4.1.0", forRemoval = true) - void add(Iteration statements, Resource... contexts) - throws RepositoryException, E; - /** * Adds the supplied statements to this repository, optionally to one or more named contexts. * @@ -983,10 +964,8 @@ void add(Iteration statements, Res * @throws RepositoryException If the statements could not be added to the repository, for example because the * repository is not writable. */ - default void add(CloseableIteration statements, Resource... contexts) - throws RepositoryException, E { - add(((Iteration) statements), contexts); - } + void add(CloseableIteration statements, Resource... contexts) + throws RepositoryException; /** * Adds the supplied statements to this repository, optionally to one or more named contexts. @@ -1002,7 +981,7 @@ default void add(CloseableIteration statements, Resource... contexts) throws RepositoryException { - add((CloseableIteration) statements, contexts); + add((CloseableIteration) statements, contexts); } /** @@ -1043,23 +1022,6 @@ default void add(RepositoryResult statements, Resource... contexts) */ void remove(Iterable statements, Resource... contexts) throws RepositoryException; - /** - * Removes the supplied statements from a specific context in this repository, ignoring any context information - * carried by the statements themselves. - * - * @param statements The statements to remove. In case the iteration is a - * {@link org.eclipse.rdf4j.common.iteration.CloseableIteration}, it will be closed before this - * method returns. - * @param contexts The context(s) to remove the data from. Note that this parameter is a vararg and as such is - * optional. If no contexts are supplied the method operates on the contexts associated with the - * statement itself, and if no context is associated with the statement, on the entire repository. - * @throws RepositoryException If the statements could not be removed from the repository, for example because the - * repository is not writable. - */ - @Deprecated(since = "4.1.0", forRemoval = true) - void remove(Iteration statements, Resource... contexts) - throws RepositoryException, E; - /** * Removes the supplied statements from a specific context in this repository, ignoring any context information * carried by the statements themselves. @@ -1071,11 +1033,9 @@ void remove(Iteration statements, * @throws RepositoryException If the statements could not be removed from the repository, for example because the * repository is not writable. */ - default void remove(CloseableIteration statements, + void remove(CloseableIteration statements, Resource... contexts) - throws RepositoryException, E { - remove((Iteration) statements, contexts); - } + throws RepositoryException; /** * Removes the supplied statements from a specific context in this repository, ignoring any context information @@ -1091,7 +1051,7 @@ default void remove(CloseableIteration statements, Resource... contexts) throws RepositoryException { - remove((CloseableIteration) statements, contexts); + remove((CloseableIteration) statements, contexts); } /** diff --git a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/RepositoryResult.java b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/RepositoryResult.java index 06deed3509d..6942a4c294f 100644 --- a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/RepositoryResult.java +++ b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/RepositoryResult.java @@ -18,7 +18,6 @@ import org.eclipse.rdf4j.common.iteration.AbstractCloseableIteration; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.DistinctIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.common.iterator.CloseableIterationIterator; import org.eclipse.rdf4j.model.IRI; @@ -44,11 +43,11 @@ * @see RepositoryConnection#getNamespaces() * @see RepositoryConnection#getContextIDs() */ -public class RepositoryResult extends AbstractCloseableIteration implements Iterable { +public class RepositoryResult extends AbstractCloseableIteration implements Iterable { - private CloseableIteration wrappedIter; + private CloseableIteration wrappedIter; - public RepositoryResult(CloseableIteration iter) { + public RepositoryResult(CloseableIteration iter) { assert iter != null; wrappedIter = iter; } @@ -73,7 +72,9 @@ protected void handleClose() throws RepositoryException { try { super.handleClose(); } finally { - Iterations.closeCloseable(wrappedIter); + if (wrappedIter != null) { + wrappedIter.close(); + } } } @@ -91,7 +92,7 @@ public void enableDuplicateFilter() throws RepositoryException { return; } - wrappedIter = new DistinctIteration(wrappedIter); + wrappedIter = new DistinctIteration(wrappedIter); } /** @@ -104,7 +105,7 @@ public void enableDuplicateFilter() throws RepositoryException { * @return a List containing all objects of this RepositoryResult. * @throws RepositoryException if a problem occurred during retrieval of the results. * @see #addTo(Collection) - * @deprecated Use {@link Iterations#asList(Iteration)} instead. + * @deprecated Use {@link Iterations#asList(CloseableIteration)} instead. */ @Deprecated public List asList() throws RepositoryException { @@ -117,7 +118,7 @@ public List asList() throws RepositoryException { * * @return A reference to the collection that was supplied. * @throws RepositoryException if a problem occurred during retrieval of the results. - * @deprecated Use {@link Iterations#addAll(Iteration, Collection)} instead. + * @deprecated Use {@link Iterations#addAll(CloseableIteration, Collection)} instead. */ @Deprecated public > C addTo(C collection) throws RepositoryException { diff --git a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/base/AbstractRepositoryConnection.java b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/base/AbstractRepositoryConnection.java index 89966168c90..5c5a7db35c0 100644 --- a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/base/AbstractRepositoryConnection.java +++ b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/base/AbstractRepositoryConnection.java @@ -18,8 +18,7 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; -import org.eclipse.rdf4j.common.iteration.Iteration; -import org.eclipse.rdf4j.common.iteration.Iterations; +import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.transaction.IsolationLevel; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Namespace; @@ -392,9 +391,9 @@ public void add(Iterable statements, Resource... contexts) } @Override - public void add(Iteration statements, Resource... contexts) - throws RepositoryException, E { - try { + public void add(CloseableIteration statements, Resource... contexts) + throws RepositoryException { + try (statements) { Objects.requireNonNull(contexts, "contexts argument may not be null; either the value should be cast to Resource or an empty array should be supplied"); @@ -410,8 +409,6 @@ public void add(Iteration statemen conditionalRollback(localTransaction); throw e; } - } finally { - Iterations.closeCloseable(statements); } } @@ -458,9 +455,9 @@ public void remove(Iterable statements, Resource... context } @Override - public void remove(Iteration statements, Resource... contexts) - throws RepositoryException, E { - try { + public void remove(CloseableIteration statements, Resource... contexts) + throws RepositoryException { + try (statements) { boolean localTransaction = startLocalTransaction(); try { @@ -473,8 +470,6 @@ public void remove(Iteration state conditionalRollback(localTransaction); throw e; } - } finally { - Iterations.closeCloseable(statements); } } diff --git a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/base/RepositoryConnectionWrapper.java b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/base/RepositoryConnectionWrapper.java index c736d76b04b..bb7560afcd9 100644 --- a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/base/RepositoryConnectionWrapper.java +++ b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/base/RepositoryConnectionWrapper.java @@ -16,7 +16,7 @@ import java.io.Reader; import java.net.URL; -import org.eclipse.rdf4j.common.iteration.Iteration; +import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.transaction.IsolationLevel; import org.eclipse.rdf4j.common.transaction.TransactionSetting; import org.eclipse.rdf4j.model.IRI; @@ -84,7 +84,7 @@ public void setDelegate(RepositoryConnection delegate) { * {@link #addWithoutCommit(Resource, IRI, Value, Resource[])} * @throws RepositoryException * @see #add(Iterable, Resource...) - * @see #add(Iteration, Resource...) + * @see #add(CloseableIteration, Resource...) * @see #add(Statement, Resource...) * @see #add(File, String, RDFFormat, Resource...) * @see #add(InputStream, String, RDFFormat, Resource...) @@ -121,7 +121,7 @@ protected boolean isDelegatingRead() throws RepositoryException { * @throws RepositoryException * @see #clear(Resource...) * @see #remove(Iterable, Resource...) - * @see #remove(Iteration, Resource...) + * @see #remove(CloseableIteration, Resource...) * @see #remove(Statement, Resource...) * @see #remove(Resource, IRI, Value, Resource...) */ @@ -167,8 +167,8 @@ public void add(Iterable statements, Resource... contexts) } @Override - public void add(Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void add(CloseableIteration statementIter, Resource... contexts) + throws RepositoryException { if (isDelegatingAdd()) { getDelegate().add(statementIter, contexts); } else { @@ -358,8 +358,9 @@ public void remove(Iterable statements, Resource... context } @Override - public void remove(Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void remove(CloseableIteration statementIter, + Resource... contexts) + throws RepositoryException { if (isDelegatingRemove()) { getDelegate().remove(statementIter, contexts); } else { diff --git a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/AbstractDelegatingRepositoryImplConfig.java b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/AbstractDelegatingRepositoryImplConfig.java index fab7dbfee57..097899e6f0f 100644 --- a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/AbstractDelegatingRepositoryImplConfig.java +++ b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/AbstractDelegatingRepositoryImplConfig.java @@ -21,9 +21,6 @@ public abstract class AbstractDelegatingRepositoryImplConfig extends AbstractRepositoryImplConfig implements DelegatingRepositoryImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private RepositoryImplConfig delegate; /** @@ -68,15 +65,27 @@ public void validate() throws RepositoryConfigException { @Override public Resource export(Model model) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(model); + } + + Resource resource = super.export(model); + + if (delegate != null) { + model.setNamespace(CONFIG.NS); + Resource delegateNode = delegate.export(model); + model.add(resource, CONFIG.delegate, delegateNode); + } + + return resource; + } + + private Resource exportLegacy(Model model) { Resource resource = super.export(model); if (delegate != null) { Resource delegateNode = delegate.export(model); - if (USE_CONFIG) { - model.add(resource, CONFIG.delegate, delegateNode); - } else { - model.add(resource, RepositoryConfigSchema.DELEGATE, delegateNode); - } + model.add(resource, RepositoryConfigSchema.DELEGATE, delegateNode); } return resource; diff --git a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/AbstractRepositoryImplConfig.java b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/AbstractRepositoryImplConfig.java index 00daa3a939c..a6f3c9dcce0 100644 --- a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/AbstractRepositoryImplConfig.java +++ b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/AbstractRepositoryImplConfig.java @@ -27,9 +27,6 @@ */ public class AbstractRepositoryImplConfig implements RepositoryImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private String type; /** @@ -66,15 +63,24 @@ public void validate() throws RepositoryConfigException { @Override public Resource export(Model model) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(model); + } + BNode implNode = bnode(); if (type != null) { - if (USE_CONFIG) { - model.add(implNode, CONFIG.Rep.type, literal(type)); - } else { - model.add(implNode, REPOSITORYTYPE, literal(type)); - } + model.add(implNode, CONFIG.Rep.type, literal(type)); + } + return implNode; + } + + private Resource exportLegacy(Model model) { + BNode implNode = bnode(); + + if (type != null) { + model.add(implNode, REPOSITORYTYPE, literal(type)); } return implNode; diff --git a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/RepositoryConfig.java b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/RepositoryConfig.java index 1f0df449294..42f5d33055b 100644 --- a/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/RepositoryConfig.java +++ b/core/repository/api/src/main/java/org/eclipse/rdf4j/repository/config/RepositoryConfig.java @@ -12,9 +12,6 @@ import static org.eclipse.rdf4j.model.util.Values.bnode; import static org.eclipse.rdf4j.model.util.Values.literal; -import static org.eclipse.rdf4j.repository.config.RepositoryConfigSchema.REPOSITORY; -import static org.eclipse.rdf4j.repository.config.RepositoryConfigSchema.REPOSITORYID; -import static org.eclipse.rdf4j.repository.config.RepositoryConfigSchema.REPOSITORYIMPL; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -31,9 +28,6 @@ */ public class RepositoryConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private String id; private String title; @@ -134,18 +128,37 @@ public void export(Model model) { * @since 2.3 */ public void export(Model model, Resource repositoryNode) { + if (Configurations.useLegacyConfig()) { + exportLegacy(model, repositoryNode); + return; + } + model.setNamespace(RDFS.NS); model.setNamespace(XSD.NS); model.setNamespace(CONFIG.NS); model.add(repositoryNode, RDF.TYPE, CONFIG.Rep.Repository); - model.add(repositoryNode, RDF.TYPE, REPOSITORY); if (id != null) { - if (USE_CONFIG) { - model.add(repositoryNode, CONFIG.Rep.id, literal(id)); - } else { - model.add(repositoryNode, REPOSITORYID, literal(id)); - } + model.add(repositoryNode, CONFIG.Rep.id, literal(id)); + + } + if (title != null) { + model.add(repositoryNode, RDFS.LABEL, literal(title)); + } + if (implConfig != null) { + Resource implNode = implConfig.export(model); + model.add(repositoryNode, CONFIG.Rep.impl, implNode); + + } + } + + private void exportLegacy(Model model, Resource repositoryNode) { + model.setNamespace(RDFS.NS); + model.setNamespace(XSD.NS); + model.setNamespace("rep", RepositoryConfigSchema.NAMESPACE); + + if (id != null) { + model.add(repositoryNode, RepositoryConfigSchema.REPOSITORYID, literal(id)); } if (title != null) { @@ -153,11 +166,7 @@ public void export(Model model, Resource repositoryNode) { } if (implConfig != null) { Resource implNode = implConfig.export(model); - if (USE_CONFIG) { - model.add(repositoryNode, CONFIG.Rep.impl, implNode); - } else { - model.add(repositoryNode, REPOSITORYIMPL, implNode); - } + model.add(repositoryNode, RepositoryConfigSchema.REPOSITORYIMPL, implNode); } } @@ -165,16 +174,14 @@ public void export(Model model, Resource repositoryNode) { public void parse(Model model, Resource repositoryNode) throws RepositoryConfigException { try { Configurations - .getLiteralValue(model, repositoryNode, CONFIG.Rep.id, - REPOSITORYID) + .getLiteralValue(model, repositoryNode, CONFIG.Rep.id, RepositoryConfigSchema.REPOSITORYID) .ifPresent(lit -> setID(lit.getLabel())); Models.objectLiteral(model.getStatements(repositoryNode, RDFS.LABEL, null)) .ifPresent(lit -> setTitle(lit.getLabel())); Configurations - .getResourceValue(model, repositoryNode, CONFIG.Rep.impl, - REPOSITORYIMPL) + .getResourceValue(model, repositoryNode, CONFIG.Rep.impl, RepositoryConfigSchema.REPOSITORYIMPL) .ifPresent(res -> setRepositoryImplConfig(AbstractRepositoryImplConfig.create(model, res))); } catch (ModelException e) { throw new RepositoryConfigException(e.getMessage(), e); diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/lmdb.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/lmdb.ttl index 947787e4e32..637c874b43e 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/lmdb.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/lmdb.ttl @@ -2,19 +2,15 @@ # Configuration template for an LmdbStore # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ns: . -@prefix sb: . +@prefix config: . -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|lmdb%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|lmdb%}" ; rdfs:label "{%Repository title|LMDB Store%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "rdf4j:LmdbStore" ; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "rdf4j:LmdbStore" ; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-customrule.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-customrule.ttl index 5190c2af707..7403da3df9d 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-customrule.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-customrule.ttl @@ -3,37 +3,31 @@ # a custom graph query inference rule. # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix cgqi: . -@prefix ms: . +@prefix config: . @prefix sp: . -@prefix sb: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|memory-customrule%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|memory-customrule%}" ; rdfs:label "{%Repository title|Memory store with custom graph query inferencing rule%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:CustomGraphQueryInferencer" ; - cgqi:queryLanguage "{%Query Language|SPARQL%}" ; - cgqi:ruleQuery [ + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:CustomGraphQueryInferencer" ; + config:cgqi.queryLanguage "{%Query Language|SPARQL%}" ; + config:cgqi.ruleQuery [ a sp:Construct ; sp:text '''{%Rule query|insert rule query here%}''' ]; - cgqi:matcherQuery [ + config:cgqi.matcherQuery [ a sp:Construct ; sp:text '''{%Matcher query (optional)|%}''' ]; - sail:delegate [ - sail:sailType "openrdf:MemoryStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; - ms:persist {%Persist|true|false%} ; - ms:syncDelay {%Sync delay|0%}; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:delegate [ + config:sail.type "openrdf:MemoryStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; + config:mem.persist {%Persist|true|false%} ; + config:mem.syncDelay {%Sync delay|0%}; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-lucene.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-lucene.ttl index 161c4e59a91..a5e5c667ba9 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-lucene.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-lucene.ttl @@ -1,29 +1,20 @@ @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix spin: . -@prefix sail-luc: . -@prefix cgqi: . -@prefix ms: . -@prefix sp: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|memory-lucene%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|memory-lucene%}" ; rdfs:label "{%Repository title|Native store with Lucene Support%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:LuceneSail"; - sail-luc:indexDir "index/" ; - sail:delegate [ - sail:sailType "openrdf:MemoryStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; - ms:persist {%Persist|true|false%} ; - ms:syncDelay {%Sync delay|0%}; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:LuceneSail"; + config:lucene.indexDir "index/" ; + config:delegate [ + config:sail.type "openrdf:MemoryStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; + config:mem.persist {%Persist|true|false%} ; + config:mem.syncDelay {%Sync delay|0%}; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-dt.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-dt.ttl index afe4544901f..36eb1dfae44 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-dt.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-dt.ttl @@ -3,28 +3,23 @@ # RDF Schema and direct type hierarchy inferencing # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ms: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|memory-rdfs-dt%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|memory-rdfs-dt%}" ; rdfs:label "{%Repository title|Memory store with RDF Schema and direct type inferencing%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:DirectTypeHierarchyInferencer" ; - sail:delegate [ - sail:sailType "rdf4j:SchemaCachingRDFSInferencer" ; - sail:delegate [ - sail:sailType "openrdf:MemoryStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ms:persist {%Persist|true|false%} ; - ms:syncDelay {%Sync delay|0%}; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:DirectTypeHierarchyInferencer" ; + config:delegate [ + config:sail.type "rdf4j:SchemaCachingRDFSInferencer" ; + config:delegate [ + config:sail.type "openrdf:MemoryStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:mem.persist {%Persist|true|false%} ; + config:mem.syncDelay {%Sync delay|0%}; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ] diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-legacy.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-legacy.ttl index 1d97b12a78e..423a45ae3aa 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-legacy.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-legacy.ttl @@ -3,26 +3,21 @@ # RDF Schema inferencing # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ms: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|memory-rdfs-new%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|memory-rdfs-new%}" ; rdfs:label "{%Repository title|Memory store with RDFS inferencing (legacy reasoner)%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:ForwardChainingRDFSInferencer" ; - sail:delegate [ - sail:sailType "openrdf:MemoryStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ms:persist {%Persist|true|false%} ; - ms:syncDelay {%Sync delay|0%}; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:ForwardChainingRDFSInferencer" ; + config:delegate [ + config:sail.type "openrdf:MemoryStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:mem.persist {%Persist|true|false%} ; + config:mem.syncDelay {%Sync delay|0%}; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-lucene.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-lucene.ttl index a1b1e07f4c1..f0c390e69e5 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-lucene.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs-lucene.ttl @@ -3,30 +3,24 @@ # RDF Schema inferencing and Lucene index # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix sail-luc: . -@prefix ms: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|memory-rdfs-lucene%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|memory-rdfs-lucene%}" ; rdfs:label "{%Repository title|Memory store with RDFS inferencing and Lucene index%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:LuceneSail"; - sail-luc:indexDir "index/" ; - sail:delegate [ - sail:sailType "rdf4j:SchemaCachingRDFSInferencer" ; - sail:delegate [ - sail:sailType "openrdf:MemoryStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ms:persist {%Persist|true|false%} ; - ms:syncDelay {%Sync delay|0%}; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:LuceneSail"; + config:lucene.indexDir "index/" ; + config:delegate [ + config:sail.type "rdf4j:SchemaCachingRDFSInferencer" ; + config:delegate [ + config:sail.type "openrdf:MemoryStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:mem.persist {%Persist|true|false%} ; + config:mem.syncDelay {%Sync delay|0%}; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ] diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs.ttl index a0180c07972..30e438823be 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-rdfs.ttl @@ -3,26 +3,21 @@ # RDF Schema inferencing # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ms: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|memory-rdfs%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|memory-rdfs%}" ; rdfs:label "{%Repository title|Memory store with RDFS inferencing%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "rdf4j:SchemaCachingRDFSInferencer" ; - sail:delegate [ - sail:sailType "openrdf:MemoryStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ms:persist {%Persist|true|false%} ; - ms:syncDelay {%Sync delay|0%}; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "rdf4j:SchemaCachingRDFSInferencer" ; + config:delegate [ + config:sail.type "openrdf:MemoryStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:mem.persist {%Persist|true|false%} ; + config:mem.syncDelay {%Sync delay|0%}; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-shacl.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-shacl.ttl index b18c24bbcee..30bc38c117e 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-shacl.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory-shacl.ttl @@ -2,26 +2,21 @@ # RDF4J configuration template for a main-memory repository with SHACL # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ms: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|memory-rdfs%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|memory-rdfs%}" ; rdfs:label "{%Repository title|Memory store with SHACL%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "rdf4j:ShaclSail" ; - sail:delegate [ - sail:sailType "openrdf:MemoryStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ms:persist {%Persist|true|false%} ; - ms:syncDelay {%Sync delay|0%}; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "rdf4j:ShaclSail" ; + config:delegate [ + config:sail.type "openrdf:MemoryStore" ; + config:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:mem.persist {%Persist|true|false%} ; + config:mem.syncDelay {%Sync delay|0%}; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory.ttl index b769da456d4..2804e1b7e48 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/memory.ttl @@ -2,22 +2,18 @@ # RDF4J configuration template for a main-memory repository # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ms: . -@prefix sb: . +@prefix config: . -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|memory%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|memory%}" ; rdfs:label "{%Repository title|Memory store%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:MemoryStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; - ms:persist {%Persist|true|false%} ; - ms:syncDelay {%Sync delay|0%} ; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:MemoryStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; + config:mem.persist {%Persist|true|false%} ; + config:mem.syncDelay {%Sync delay|0%} ; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-customrule.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-customrule.ttl index 4ea529d69c6..d51bc8e5b8b 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-customrule.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-customrule.ttl @@ -3,36 +3,30 @@ # a custom graph query inference rule. # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ns: . -@prefix cgqi: . +@prefix config: . @prefix sp: . -@prefix sb: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|native-customrule%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|native-customrule%}" ; rdfs:label "{%Repository title|Native store with custom graph query inferencing rule%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:CustomGraphQueryInferencer" ; - cgqi:queryLanguage "{%Query Language|SPARQL%}" ; - cgqi:ruleQuery [ + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:CustomGraphQueryInferencer" ; + config:cgqi.queryLanguage "{%Query Language|SPARQL%}" ; + config:cgqi.ruleQuery [ a sp:Construct ; sp:text '''{%Rule query|insert rule query here%}''' ]; - cgqi:matcherQuery [ + config:cgqi.matcherQuery [ a sp:Construct ; sp:text '''{%Matcher query (optional)|%}''' ]; - sail:delegate [ - sail:sailType "openrdf:NativeStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; - ns:tripleIndexes "{%Triple indexes|spoc,posc%}"; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:delegate [ + config:sail.type "openrdf:NativeStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; + config:native.tripleIndexes "{%Triple indexes|spoc,posc%}"; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-lucene.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-lucene.ttl index c98009c9927..99307a508f8 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-lucene.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-lucene.ttl @@ -3,30 +3,21 @@ # Lucene support # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix spin: . -@prefix sail-luc: . -@prefix cgqi: . -@prefix ns: . -@prefix sp: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|native-lucene%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|native-lucene%}" ; rdfs:label "{%Repository title|Native store with Lucene Support%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:LuceneSail"; - sail-luc:indexDir "index/" ; - sail:delegate [ - sail:sailType "openrdf:NativeStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; - ns:tripleIndexes "{%Triple indexes|spoc,posc%}"; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:LuceneSail"; + config:lucene.indexDir "index/" ; + config:delegate [ + config:sail.type "openrdf:NativeStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; + config:native.tripleIndexes "{%Triple indexes|spoc,posc%}"; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs-dt.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs-dt.ttl index 15f1556f9b1..3b4541605e8 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs-dt.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs-dt.ttl @@ -3,27 +3,22 @@ # RDF Schema and direct type hierarchy inferencing # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ns: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|native-rdfs-dt%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|native-rdfs-dt%}" ; rdfs:label "{%Repository title|Native store with RDF Schema and direct type inferencing%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:DirectTypeHierarchyInferencer" ; - sail:delegate [ - sail:sailType "rdf4j:SchemaCachingRDFSInferencer" ; - sail:delegate [ - sail:sailType "openrdf:NativeStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ns:tripleIndexes "{%Triple indexes|spoc,posc%}"; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:DirectTypeHierarchyInferencer" ; + config:delegate [ + config:sail.type "rdf4j:SchemaCachingRDFSInferencer" ; + config:delegate [ + config:sail.type "openrdf:NativeStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:native.tripleIndexes "{%Triple indexes|spoc,posc%}"; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ] diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs-lucene.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs-lucene.ttl index 20b7a743605..e3717bc5db3 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs-lucene.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs-lucene.ttl @@ -3,32 +3,23 @@ # RDFS support and a Lucene index # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix spin: . -@prefix sail-luc: . -@prefix cgqi: . -@prefix ns: . -@prefix sp: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|native-rdfs-lucene%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|native-rdfs-lucene%}" ; rdfs:label "{%Repository title|Native store with RDFS entailment and Lucene Support%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:LuceneSail"; - sail-luc:indexDir "index/" ; - sail:delegate [ - sail:sailType "rdf4j:SchemaCachingRDFSInferencer" ; - sail:delegate [ - sail:sailType "openrdf:NativeStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; - ns:tripleIndexes "{%Triple indexes|spoc,posc%}"; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:LuceneSail"; + config:lucene.indexDir "index/" ; + config:delegate [ + config:sail.type "rdf4j:SchemaCachingRDFSInferencer" ; + config:delegate [ + config:sail.type "openrdf:NativeStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache sync threshold|10000%}"; + config:native.tripleIndexes "{%Triple indexes|spoc,posc%}"; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ] diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs.ttl index 96d0ef4037b..5c5df705ba6 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-rdfs.ttl @@ -3,25 +3,20 @@ # RDF Schema inferencing # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ns: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|native-rdfs%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|native-rdfs%}" ; rdfs:label "{%Repository title|Native store with RDF Schema inferencing%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "rdf4j:SchemaCachingRDFSInferencer" ; - sail:delegate [ - sail:sailType "openrdf:NativeStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ns:tripleIndexes "{%Triple indexes|spoc,posc%}"; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "rdf4j:SchemaCachingRDFSInferencer" ; + config:delegate [ + config:sail.type "openrdf:NativeStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:native.tripleIndexes "{%Triple indexes|spoc,posc%}"; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-shacl.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-shacl.ttl index 3a84d5ea9e1..18a2d2c1dc7 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-shacl.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native-shacl.ttl @@ -3,25 +3,20 @@ # SHACL # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ns: . -@prefix sb: . +@prefix config: . - -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|native-shacl%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|native-shacl%}" ; rdfs:label "{%Repository title|Native store with SHACL support%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "rdf4j:ShaclSail" ; - sail:delegate [ - sail:sailType "openrdf:NativeStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ns:tripleIndexes "{%Triple indexes|spoc,posc%}"; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "rdf4j:ShaclSail" ; + config:delegate [ + config:sail.type "openrdf:NativeStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:native.tripleIndexes "{%Triple indexes|spoc,posc%}"; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native.ttl index 787c4629f55..550eae59c11 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/native.ttl @@ -2,21 +2,17 @@ # RDF4J configuration template for a native RDF repository # @prefix rdfs: . -@prefix rep: . -@prefix sr: . -@prefix sail: . -@prefix ns: . -@prefix sb: . +@prefix config: . -[] a rep:Repository ; - rep:repositoryID "{%Repository ID|native%}" ; +[] a config:Repository ; + config:rep.id "{%Repository ID|native%}" ; rdfs:label "{%Repository title|Native store%}" ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SailRepository" ; - sr:sailImpl [ - sail:sailType "openrdf:NativeStore" ; - sail:iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; - ns:tripleIndexes "{%Triple indexes|spoc,posc%}" ; - sb:defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:NativeStore" ; + config:sail.iterationCacheSyncThreshold "{%Query Iteration Cache size|10000%}"; + config:native.tripleIndexes "{%Triple indexes|spoc,posc%}" ; + config:sail.defaultQueryEvaluationMode "{%Query Evaluation Mode|STRICT|STANDARD%}" ] ]. diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/remote.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/remote.ttl index 40602d9122d..427250a8a45 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/remote.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/remote.ttl @@ -2,13 +2,12 @@ # RDF4J configuration template for a (proxy for a) remote repository # @prefix rdfs: . -@prefix rep: . -@prefix hr: . +@prefix config: . -[] a rep:Repository ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:HTTPRepository" ; - hr:repositoryURL <{%Sesame server location|http://localhost:8080/openrdf-sesame%}/repositories/{%Remote repository ID|SYSTEM%}> +[] a config:Repository ; + config:rep.impl [ + config:rep.type "openrdf:HTTPRepository" ; + config:http.url <{%RDF4J Server location|http://localhost:8080/rdf4j-server%}/repositories/{%Remote repository ID|SYSTEM%}> ]; - rep:repositoryID "{%Local repository ID|SYSTEM@localhost%}" ; + config:rep.id "{%Local repository ID|SYSTEM@localhost%}" ; rdfs:label "{%Repository title|SYSTEM repository @localhost%}" . diff --git a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/sparql.ttl b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/sparql.ttl index f65a7b890fa..4c478ca36e9 100644 --- a/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/sparql.ttl +++ b/core/repository/api/src/main/resources/org/eclipse/rdf4j/repository/config/sparql.ttl @@ -2,14 +2,13 @@ # RDF4J configuration template for a Repository proxy for a SPARQL endpoint # @prefix rdfs: . -@prefix rep: . -@prefix sparql: . +@prefix config: . -[] a rep:Repository ; - rep:repositoryImpl [ - rep:repositoryType "openrdf:SPARQLRepository" ; - sparql:query-endpoint <{%SPARQL query endpoint|%}> ; - sparql:update-endpoint <{%SPARQL update endpoint|%}> ; +[] a config:Repository ; + config:rep.impl [ + config:rep.type "openrdf:SPARQLRepository" ; + config:sparql.queryEndpoint <{%SPARQL query endpoint|%}> ; + config:sparql.updateEndpoint <{%SPARQL update endpoint|%}> ; ]; - rep:repositoryID "{%Local repository ID|endpoint@localhost%}" ; + config:rep.id "{%Local repository ID|endpoint@localhost%}" ; rdfs:label "{%Repository title|SPARQL endpoint repository @localhost%}" . diff --git a/core/repository/api/src/test/java/org/eclipse/rdf4j/repository/config/RepositoryConfigTest.java b/core/repository/api/src/test/java/org/eclipse/rdf4j/repository/config/RepositoryConfigTest.java index 5b2332a77da..42ad8acf7d8 100644 --- a/core/repository/api/src/test/java/org/eclipse/rdf4j/repository/config/RepositoryConfigTest.java +++ b/core/repository/api/src/test/java/org/eclipse/rdf4j/repository/config/RepositoryConfigTest.java @@ -12,8 +12,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.rdf4j.model.util.Values.iri; +import static org.eclipse.rdf4j.model.util.Values.literal; import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.impl.DynamicModelFactory; import org.eclipse.rdf4j.model.util.ModelBuilder; import org.eclipse.rdf4j.model.vocabulary.CONFIG; import org.junit.jupiter.api.Test; @@ -38,6 +40,23 @@ public void testParse_newVocabulary() { assertThat(config.getID()).isEqualTo(ID); } + @Test + public void testParse_useLegacy_newVocabulary() { + var repoNode = iri("urn:repo1"); + Model m = new ModelBuilder() + .subject(repoNode) + .add(CONFIG.Rep.id, ID) + .build(); + + RepositoryConfig config = new RepositoryConfig(); + + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + config.parse(m, repoNode); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + + assertThat(config.getID()).isEqualTo(ID); + } + @Test public void testParse_oldVocabulary() { var repoNode = iri("urn:repo1"); @@ -46,11 +65,72 @@ public void testParse_oldVocabulary() { .add(RepositoryConfigSchema.REPOSITORYID, ID) .build(); - RepositoryConfig config = new RepositoryConfig(ID); + RepositoryConfig config = new RepositoryConfig(); config.parse(m, repoNode); assertThat(config.getID()).isEqualTo(ID); } + @Test + public void testParse_mixedVocabulary() { + var repoNode = iri("urn:repo1"); + + var newId = "new_test"; + Model m = new ModelBuilder() + .subject(repoNode) + .add(RepositoryConfigSchema.REPOSITORYID, ID) + .add(CONFIG.Rep.id, newId) + .build(); + + RepositoryConfig config = new RepositoryConfig(); + + config.parse(m, repoNode); + + assertThat(config.getID()).isEqualTo(newId); + } + + @Test + public void testParse_useLegacy_mixedVocabulary() { + var repoNode = iri("urn:repo1"); + var newId = "new_test"; + Model m = new ModelBuilder() + .subject(repoNode) + .add(RepositoryConfigSchema.REPOSITORYID, ID) + .add(CONFIG.Rep.id, newId) + .build(); + + RepositoryConfig config = new RepositoryConfig(); + + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + config.parse(m, repoNode); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + + assertThat(config.getID()).isEqualTo(ID); + } + + @Test + public void testExport() { + var repoNode = iri("urn:repo1"); + var config = new RepositoryConfig(ID); + var m = new DynamicModelFactory().createEmptyModel(); + config.export(m, repoNode); + + assertThat(m.filter(repoNode, CONFIG.Rep.id, null).objects()).containsExactly(literal(ID)); + assertThat(m.filter(repoNode, RepositoryConfigSchema.REPOSITORYID, null).objects()).isEmpty(); + } + + @Test + public void testExport_useLegacy() { + var repoNode = iri("urn:repo1"); + var config = new RepositoryConfig(ID); + var m = new DynamicModelFactory().createEmptyModel(); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + config.export(m, repoNode); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + + assertThat(m.filter(repoNode, RepositoryConfigSchema.REPOSITORYID, null).objects()) + .containsExactly(literal(ID)); + assertThat(m.filter(repoNode, CONFIG.Rep.id, null).objects()).isEmpty(); + } } diff --git a/core/repository/contextaware/src/main/java/org/eclipse/rdf4j/repository/contextaware/ContextAwareConnection.java b/core/repository/contextaware/src/main/java/org/eclipse/rdf4j/repository/contextaware/ContextAwareConnection.java index e6344a78de5..0b4903c968d 100644 --- a/core/repository/contextaware/src/main/java/org/eclipse/rdf4j/repository/contextaware/ContextAwareConnection.java +++ b/core/repository/contextaware/src/main/java/org/eclipse/rdf4j/repository/contextaware/ContextAwareConnection.java @@ -19,7 +19,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.CloseableIteratorIteration; import org.eclipse.rdf4j.common.iteration.ConvertingIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; @@ -323,11 +322,11 @@ public void add(Iterable statements, Resource... contexts) } @Override - public void add(Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void add(CloseableIteration statementIter, Resource... contexts) + throws RepositoryException { final IRI insertContext = getInsertContext(); if (isNilContext(contexts)) { - super.add(new ConvertingIteration(statementIter) { + super.add(new ConvertingIteration(statementIter) { @Override protected Statement convert(Statement st) { @@ -655,11 +654,12 @@ public void remove(Iterable statements, Resource... context * @see #getRemoveContexts() */ @Override - public void remove(Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void remove(CloseableIteration statementIter, + Resource... contexts) + throws RepositoryException { final IRI[] removeContexts = getRemoveContexts(); if (isAllContext(contexts) && removeContexts.length == 1) { - super.remove(new ConvertingIteration(statementIter) { + super.remove(new ConvertingIteration(statementIter) { @Override protected Statement convert(Statement st) { diff --git a/core/repository/contextaware/src/main/java/org/eclipse/rdf4j/repository/contextaware/config/ContextAwareConfig.java b/core/repository/contextaware/src/main/java/org/eclipse/rdf4j/repository/contextaware/config/ContextAwareConfig.java index a6ea44d1ded..3b6c1a18064 100644 --- a/core/repository/contextaware/src/main/java/org/eclipse/rdf4j/repository/contextaware/config/ContextAwareConfig.java +++ b/core/repository/contextaware/src/main/java/org/eclipse/rdf4j/repository/contextaware/config/ContextAwareConfig.java @@ -29,6 +29,7 @@ import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.util.Configurations; +import org.eclipse.rdf4j.model.vocabulary.CONFIG; import org.eclipse.rdf4j.model.vocabulary.CONFIG.ContextAware; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.repository.config.AbstractDelegatingRepositoryImplConfig; @@ -190,40 +191,72 @@ public void setRemoveContexts(IRI... removeContexts) { @Override public Resource export(Model model) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(model); + } + Resource repImplNode = super.export(model); + model.setNamespace(CONFIG.NS); if (includeInferred != null) { model.add(repImplNode, ContextAware.includeInferred, literal(includeInferred)); - model.add(repImplNode, INCLUDE_INFERRED, literal(includeInferred)); } if (maxQueryTime > 0) { model.add(repImplNode, ContextAware.maxQueryTime, literal(maxQueryTime)); - model.add(repImplNode, MAX_QUERY_TIME, literal(maxQueryTime)); } if (queryLanguage != null) { model.add(repImplNode, ContextAware.queryLanguage, literal(queryLanguage.getName())); - model.add(repImplNode, QUERY_LANGUAGE, literal(queryLanguage.getName())); } if (baseURI != null) { model.add(repImplNode, ContextAware.base, iri(baseURI)); - model.add(repImplNode, BASE_URI, iri(baseURI)); } for (IRI uri : readContexts) { model.add(repImplNode, ContextAware.readContext, uri); - model.add(repImplNode, READ_CONTEXT, uri); } for (IRI resource : addContexts) { model.add(repImplNode, ADD_CONTEXT, resource); } for (IRI resource : removeContexts) { model.add(repImplNode, ContextAware.removeContext, resource); - model.add(repImplNode, REMOVE_CONTEXT, resource); } for (IRI resource : archiveContexts) { model.add(repImplNode, ARCHIVE_CONTEXT, resource); } if (insertContext != null) { model.add(repImplNode, ContextAware.insertContext, insertContext); + } + + return repImplNode; + } + + private Resource exportLegacy(Model model) { + Resource repImplNode = super.export(model); + + if (includeInferred != null) { + model.add(repImplNode, INCLUDE_INFERRED, literal(includeInferred)); + } + if (maxQueryTime > 0) { + model.add(repImplNode, MAX_QUERY_TIME, literal(maxQueryTime)); + } + if (queryLanguage != null) { + model.add(repImplNode, QUERY_LANGUAGE, literal(queryLanguage.getName())); + } + if (baseURI != null) { + model.add(repImplNode, BASE_URI, iri(baseURI)); + } + for (IRI uri : readContexts) { + model.add(repImplNode, READ_CONTEXT, uri); + } + for (IRI resource : addContexts) { + model.add(repImplNode, ADD_CONTEXT, resource); + } + for (IRI resource : removeContexts) { + model.add(repImplNode, REMOVE_CONTEXT, resource); + } + for (IRI resource : archiveContexts) { + model.add(repImplNode, ARCHIVE_CONTEXT, resource); + } + if (insertContext != null) { model.add(repImplNode, INSERT_CONTEXT, insertContext); } @@ -236,23 +269,19 @@ public void parse(Model model, Resource resource) throws RepositoryConfigExcepti try { Configurations - .getLiteralValue(model, resource, ContextAware.includeInferred, - INCLUDE_INFERRED) + .getLiteralValue(model, resource, ContextAware.includeInferred, INCLUDE_INFERRED) .ifPresent(lit -> setIncludeInferred(lit.booleanValue())); Configurations - .getLiteralValue(model, resource, ContextAware.maxQueryTime, - MAX_QUERY_TIME) + .getLiteralValue(model, resource, ContextAware.maxQueryTime, MAX_QUERY_TIME) .ifPresent(lit -> setMaxQueryTime(lit.intValue())); Configurations - .getLiteralValue(model, resource, ContextAware.queryLanguage, - QUERY_LANGUAGE) + .getLiteralValue(model, resource, ContextAware.queryLanguage, QUERY_LANGUAGE) .ifPresent(lit -> setQueryLanguage(QueryLanguage.valueOf(lit.getLabel()))); Configurations - .getIRIValue(model, resource, ContextAware.base, - BASE_URI) + .getIRIValue(model, resource, ContextAware.base, BASE_URI) .ifPresent(iri -> setBaseURI(iri.stringValue())); Set objects = Configurations.getPropertyValues(model, resource, ContextAware.readContext, @@ -262,16 +291,14 @@ public void parse(Model model, Resource resource) throws RepositoryConfigExcepti objects = model.filter(resource, ADD_CONTEXT, null).objects(); setAddContexts(objects.toArray(new IRI[objects.size()])); - objects = Configurations.getPropertyValues(model, resource, ContextAware.removeContext, - REMOVE_CONTEXT); + objects = Configurations.getPropertyValues(model, resource, ContextAware.removeContext, REMOVE_CONTEXT); setRemoveContexts(objects.toArray(new IRI[objects.size()])); objects = model.filter(resource, ARCHIVE_CONTEXT, null).objects(); setArchiveContexts(objects.toArray(new IRI[objects.size()])); Configurations - .getIRIValue(model, resource, ContextAware.insertContext, - INSERT_CONTEXT) + .getIRIValue(model, resource, ContextAware.insertContext, INSERT_CONTEXT) .ifPresent(iri -> setInsertContext(iri)); } catch (ArrayStoreException e) { throw new RepositoryConfigException(e); diff --git a/core/repository/contextaware/src/test/java/org/eclipse/rdf4j/repository/contextaware/ContextAwareConnectionTest.java b/core/repository/contextaware/src/test/java/org/eclipse/rdf4j/repository/contextaware/ContextAwareConnectionTest.java index 58e5019cc7e..e912dda8fb9 100644 --- a/core/repository/contextaware/src/test/java/org/eclipse/rdf4j/repository/contextaware/ContextAwareConnectionTest.java +++ b/core/repository/contextaware/src/test/java/org/eclipse/rdf4j/repository/contextaware/ContextAwareConnectionTest.java @@ -63,7 +63,7 @@ public Explanation explain(Explanation.Level level) { static class InvocationHandlerStub implements InvocationHandler { @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) { return null; } } @@ -116,7 +116,7 @@ public RepositoryConnectionStub() { String queryString = "SELECT ?o WHERE { ?s ?p ?o}"; @Test - public void testGraphQuery() throws Exception { + public void testGraphQuery() { RepositoryConnection stub = new RepositoryConnectionStub() { @Override @@ -142,7 +142,7 @@ public void setDataset(Dataset dataset) { } @Test - public void testQuery() throws Exception { + public void testQuery() { RepositoryConnection stub = new RepositoryConnectionStub() { @Override @@ -168,7 +168,7 @@ public void setDataset(Dataset dataset) { } @Test - public void testTupleQuery() throws Exception { + public void testTupleQuery() { RepositoryConnection stub = new RepositoryConnectionStub() { @Override @@ -194,7 +194,7 @@ public void setDataset(Dataset dataset) { } @Test - public void testIncludeInferred() throws Exception { + public void testIncludeInferred() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); @@ -205,7 +205,7 @@ public void testIncludeInferred() throws Exception { } @Test - public void testMaxQueryTime() throws Exception { + public void testMaxQueryTime() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); @@ -216,7 +216,7 @@ public void testMaxQueryTime() throws Exception { } @Test - public void testQueryLanguage() throws Exception { + public void testQueryLanguage() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); @@ -227,7 +227,7 @@ public void testQueryLanguage() throws Exception { } @Test - public void testBaseURI() throws Exception { + public void testBaseURI() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); @@ -238,7 +238,7 @@ public void testBaseURI() throws Exception { } @Test - public void testReadContexts() throws Exception { + public void testReadContexts() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); @@ -249,7 +249,7 @@ public void testReadContexts() throws Exception { } @Test - public void testRemoveContexts() throws Exception { + public void testRemoveContexts() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); @@ -260,7 +260,7 @@ public void testRemoveContexts() throws Exception { } @Test - public void testAddContexts() throws Exception { + public void testAddContexts() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); @@ -271,7 +271,7 @@ public void testAddContexts() throws Exception { } @Test - public void testArchiveContexts() throws Exception { + public void testArchiveContexts() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); @@ -282,7 +282,7 @@ public void testArchiveContexts() throws Exception { } @Test - public void testInsertContexts() throws Exception { + public void testInsertContexts() { RepositoryConnection stub = new RepositoryConnectionStub(); Repository repo = stub.getRepository(); ContextAwareConnection a = new ContextAwareConnection(repo, stub); diff --git a/core/repository/event/src/test/java/org/eclipse/rdf4j/repository/event/InterceptorTest.java b/core/repository/event/src/test/java/org/eclipse/rdf4j/repository/event/InterceptorTest.java index 9e5f72d828c..8cdeb549a48 100644 --- a/core/repository/event/src/test/java/org/eclipse/rdf4j/repository/event/InterceptorTest.java +++ b/core/repository/event/src/test/java/org/eclipse/rdf4j/repository/event/InterceptorTest.java @@ -45,7 +45,7 @@ public class InterceptorTest { static class InvocationHandlerStub implements InvocationHandler { @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) { if (Boolean.TYPE.equals(method.getReturnType())) { return false; } @@ -101,7 +101,7 @@ public void execute() throws UpdateExecutionException { } @Test - public void testUpdate() throws Exception { + public void testUpdate() { final Update updateStub = new UpdateStub() { @Override @@ -137,7 +137,7 @@ public boolean execute(RepositoryConnection conn, QueryLanguage ql, String updat } @Test - public void testRemove() throws Exception { + public void testRemove() { ValueFactory vf = SimpleValueFactory.getInstance(); final IRI uri = vf.createIRI("http://example.com/"); final RepositoryConnection stub = new RepositoryConnectionStub() { diff --git a/core/repository/event/src/test/java/org/eclipse/rdf4j/repository/event/NotifyingTest.java b/core/repository/event/src/test/java/org/eclipse/rdf4j/repository/event/NotifyingTest.java index 953f13dd312..610d85797fb 100644 --- a/core/repository/event/src/test/java/org/eclipse/rdf4j/repository/event/NotifyingTest.java +++ b/core/repository/event/src/test/java/org/eclipse/rdf4j/repository/event/NotifyingTest.java @@ -44,7 +44,7 @@ public class NotifyingTest { static class InvocationHandlerStub implements InvocationHandler { @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) { if (Boolean.TYPE.equals(method.getReturnType())) { return false; } @@ -100,7 +100,7 @@ public void execute() throws UpdateExecutionException { } @Test - public void testUpdate() throws Exception { + public void testUpdate() { final Update updateStub = new UpdateStub(); final RepositoryConnection stub = new RepositoryConnectionStub() { @@ -129,7 +129,7 @@ public void execute(RepositoryConnection conn, QueryLanguage ql, String update, } @Test - public void testRemove() throws Exception { + public void testRemove() { ValueFactory vf = SimpleValueFactory.getInstance(); final IRI uri = vf.createIRI("http://example.com/"); final RepositoryConnection stub = new RepositoryConnectionStub() { diff --git a/core/repository/http/pom.xml b/core/repository/http/pom.xml index b1d744ea437..526becc1b17 100644 --- a/core/repository/http/pom.xml +++ b/core/repository/http/pom.xml @@ -72,12 +72,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/repository/http/src/main/java/org/eclipse/rdf4j/repository/http/config/HTTPRepositoryConfig.java b/core/repository/http/src/main/java/org/eclipse/rdf4j/repository/http/config/HTTPRepositoryConfig.java index 8f0e76aabea..582bfc398dc 100644 --- a/core/repository/http/src/main/java/org/eclipse/rdf4j/repository/http/config/HTTPRepositoryConfig.java +++ b/core/repository/http/src/main/java/org/eclipse/rdf4j/repository/http/config/HTTPRepositoryConfig.java @@ -26,9 +26,6 @@ */ public class HTTPRepositoryConfig extends AbstractRepositoryImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private String url; private String username; @@ -78,18 +75,28 @@ public void validate() throws RepositoryConfigException { @Override public Resource export(Model graph) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(graph); + } + Resource implNode = super.export(graph); if (url != null) { - graph.setNamespace(CONFIG.PREFIX, CONFIG.NAMESPACE); - if (USE_CONFIG) { - graph.add(implNode, CONFIG.Http.url, SimpleValueFactory.getInstance().createIRI(url)); - } else { - graph.add(implNode, REPOSITORYURL, SimpleValueFactory.getInstance().createIRI(url)); - } + graph.setNamespace(CONFIG.NS); + graph.add(implNode, CONFIG.Http.url, SimpleValueFactory.getInstance().createIRI(url)); } + return implNode; + } + private Resource exportLegacy(Model graph) { + Resource implNode = super.export(graph); + + if (url != null) { + graph.setNamespace("http", HTTPRepositorySchema.NAMESPACE); + graph.add(implNode, REPOSITORYURL, SimpleValueFactory.getInstance().createIRI(url)); + + } return implNode; } diff --git a/core/repository/manager/src/main/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManager.java b/core/repository/manager/src/main/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManager.java index b6d72f63de9..7332d9a7f96 100644 --- a/core/repository/manager/src/main/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManager.java +++ b/core/repository/manager/src/main/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManager.java @@ -34,6 +34,7 @@ import org.eclipse.rdf4j.http.client.SharedHttpClientSessionManager; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.eclipse.rdf4j.model.util.Configurations; import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolver; import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolverClient; import org.eclipse.rdf4j.repository.DelegatingRepository; @@ -262,6 +263,7 @@ public synchronized RepositoryConfig getRepositoryConfig(String id) { File configFile = new File(dataDir, CFG_FILE); try (InputStream input = new FileInputStream(configFile)) { Model model = Rio.parse(input, configFile.toURI().toString(), CONFIG_FORMAT); + Set repositoryIDs = RepositoryConfigUtil.getRepositoryIDs(model); if (repositoryIDs.isEmpty()) { throw new RepositoryConfigException("No repository ID in configuration: " + configFile); @@ -273,7 +275,12 @@ public synchronized RepositoryConfig getRepositoryConfig(String id) { && !getRepositoryDir(repositoryID).getCanonicalFile().equals(dataDir.getCanonicalFile())) { throw new RepositoryConfigException("Wrong repository ID in configuration: " + configFile); } - return RepositoryConfigUtil.getRepositoryConfig(model, repositoryID); + var config = RepositoryConfigUtil.getRepositoryConfig(model, repositoryID); + if (Configurations.hasLegacyConfiguration(model) && !Configurations.useLegacyConfig()) { + logger.warn("configuration for {} uses legacy vocabulary, converting.", id); + addRepositoryConfig(config); + } + return config; } catch (IOException e) { throw new RepositoryConfigException(e); } diff --git a/core/repository/manager/src/main/java/org/eclipse/rdf4j/repository/manager/util/TypeFilteringRepositoryManager.java b/core/repository/manager/src/main/java/org/eclipse/rdf4j/repository/manager/util/TypeFilteringRepositoryManager.java index a38f32dc098..4548c3ec66b 100644 --- a/core/repository/manager/src/main/java/org/eclipse/rdf4j/repository/manager/util/TypeFilteringRepositoryManager.java +++ b/core/repository/manager/src/main/java/org/eclipse/rdf4j/repository/manager/util/TypeFilteringRepositoryManager.java @@ -113,7 +113,7 @@ public RepositoryConfig getRepositoryConfig(String repositoryID) if (!isCorrectType(result)) { logger.debug( "Surpressing retrieval of repository {}: repository type {} did not match expected type {}", - new Object[] { result.getID(), result.getRepositoryImplConfig().getType(), type }); + result.getID(), result.getRepositoryImplConfig().getType(), type); result = null; } diff --git a/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManagerTest.java b/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManagerTest.java index 1f585108af7..56f2b758afd 100644 --- a/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManagerTest.java +++ b/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/LocalRepositoryManagerTest.java @@ -15,7 +15,6 @@ import static org.mockito.Mockito.mock; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.config.RepositoryConfig; import org.eclipse.rdf4j.repository.config.RepositoryConfigException; @@ -36,19 +35,17 @@ public class LocalRepositoryManagerTest extends RepositoryManagerTest { /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp(@TempDir File datadir) throws Exception { + public void setUp(@TempDir File datadir) { subject = new LocalRepositoryManager(datadir); subject.init(); } /** - * @throws IOException if a problem occurs deleting temporary resources */ @AfterEach - public void tearDown() throws IOException { + public void tearDown() { subject.shutDown(); } @@ -59,4 +56,5 @@ public void testAddRepositoryConfig_validation() { assertThrows(RepositoryConfigException.class, () -> subject.addRepositoryConfig(config)); } + } diff --git a/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RemoteRepositoryManagerTest.java b/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RemoteRepositoryManagerTest.java index 997419d3927..e74a020bcc7 100644 --- a/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RemoteRepositoryManagerTest.java +++ b/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RemoteRepositoryManagerTest.java @@ -142,7 +142,7 @@ public void testAddRepositoryConfigExisting(MockServerClient client) throws Exce } @Test - public void testGetRepositoryConfig(MockServerClient client) throws Exception { + public void testGetRepositoryConfig(MockServerClient client) { client.when( request() .withMethod("GET") diff --git a/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RepositoryManagerTest.java b/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RepositoryManagerTest.java index 4d50b727794..c64976d24d6 100644 --- a/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RepositoryManagerTest.java +++ b/core/repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RepositoryManagerTest.java @@ -13,7 +13,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; @@ -37,7 +36,7 @@ public class RepositoryManagerTest { protected RepositoryManager subject; @BeforeEach - public void setUp() throws Exception { + public void setUp() { subject = new RepositoryManager() { @Override @@ -47,7 +46,7 @@ public void setHttpClient(HttpClient httpClient) { } @Override - public URL getLocation() throws MalformedURLException { + public URL getLocation() { return null; } diff --git a/core/repository/sail/pom.xml b/core/repository/sail/pom.xml index 2505c5ee12b..a5137e09479 100644 --- a/core/repository/sail/pom.xml +++ b/core/repository/sail/pom.xml @@ -68,12 +68,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/evaluation/RepositoryTripleSource.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/evaluation/RepositoryTripleSource.java index 5d25578f878..f6d57cf39c3 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/evaluation/RepositoryTripleSource.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/evaluation/RepositoryTripleSource.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.repository.evaluation; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.ExceptionConvertingIteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; @@ -38,21 +37,15 @@ public RepositoryTripleSource(RepositoryConnection repo, boolean includeInferred } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { - CloseableIteration iter = null; - CloseableIteration result = null; + CloseableIteration iter = null; + CloseableIteration result = null; boolean allGood = false; try { iter = repo.getStatements(subj, pred, obj, includeInferred, contexts); - result = new ExceptionConvertingIteration(iter) { - - @Override - protected QueryEvaluationException convert(Exception exception) { - return new QueryEvaluationException(exception); - } - }; + result = new QueryEvaluationCloseableIteration(iter); allGood = true; return result; } catch (RepositoryException e) { @@ -76,4 +69,58 @@ protected QueryEvaluationException convert(Exception exception) { public ValueFactory getValueFactory() { return repo.getValueFactory(); } + + static class QueryEvaluationCloseableIteration implements CloseableIteration { + + private final CloseableIteration iter; + + public QueryEvaluationCloseableIteration(CloseableIteration iter) { + this.iter = iter; + } + + @Override + public void close() { + try { + iter.close(); + } catch (Exception e) { + throw convert(e); + } + } + + @Override + public boolean hasNext() { + try { + return iter.hasNext(); + } catch (Exception e) { + throw convert(e); + } + } + + @Override + public E next() { + try { + return iter.next(); + } catch (Exception e) { + throw convert(e); + } + } + + @Override + public void remove() { + try { + iter.remove(); + } catch (Exception e) { + throw convert(e); + } + } + + protected QueryEvaluationException convert(Exception e) { + if (e instanceof QueryEvaluationException) { + return (QueryEvaluationException) e; + } else { + throw new QueryEvaluationException(e); + } + } + } + } diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailBooleanQuery.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailBooleanQuery.java index 1fe2f178388..1b8f06a6223 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailBooleanQuery.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailBooleanQuery.java @@ -44,8 +44,8 @@ public boolean evaluate() throws QueryEvaluationException { dataset = parsedBooleanQuery.getDataset(); } - CloseableIteration bindingsIter1 = null; - CloseableIteration bindingsIter2 = null; + CloseableIteration bindingsIter1 = null; + CloseableIteration bindingsIter2 = null; try { SailConnection sailCon = getConnection().getSailConnection(); diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailCloseableIteration.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailCloseableIteration.java index 550a95071ab..0b061b5fafb 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailCloseableIteration.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailCloseableIteration.java @@ -11,20 +11,56 @@ package org.eclipse.rdf4j.repository.sail; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.ExceptionConvertingIteration; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.sail.SailException; /** * @author Herko ter Horst */ -class SailCloseableIteration extends ExceptionConvertingIteration { +class SailCloseableIteration implements CloseableIteration { - public SailCloseableIteration(CloseableIteration iter) { - super(iter); + private final CloseableIteration iter; + + public SailCloseableIteration(CloseableIteration iter) { + this.iter = iter; + } + + @Override + public void close() { + try { + iter.close(); + } catch (Exception e) { + throw convert(e); + } + } + + @Override + public boolean hasNext() { + try { + return iter.hasNext(); + } catch (Exception e) { + throw convert(e); + } + } + + @Override + public E next() { + try { + return iter.next(); + } catch (Exception e) { + throw convert(e); + } } @Override + public void remove() { + try { + iter.remove(); + } catch (Exception e) { + throw convert(e); + } + } + protected RepositoryException convert(Exception e) { if (e instanceof SailException) { return new RepositoryException(e); diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailGraphQuery.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailGraphQuery.java index 22a7a7dc78f..6520b39ba4f 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailGraphQuery.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailGraphQuery.java @@ -49,10 +49,10 @@ public ParsedGraphQuery getParsedQuery() { public GraphQueryResult evaluate() throws QueryEvaluationException { TupleExpr tupleExpr = getParsedQuery().getTupleExpr(); - CloseableIteration bindingsIter1 = null; - CloseableIteration bindingsIter2 = null; - CloseableIteration bindingsIter3 = null; - CloseableIteration stIter = null; + CloseableIteration bindingsIter1 = null; + CloseableIteration bindingsIter2 = null; + CloseableIteration bindingsIter3 = null; + CloseableIteration stIter = null; IteratingGraphQueryResult result = null; boolean allGood = false; try { @@ -61,7 +61,7 @@ public GraphQueryResult evaluate() throws QueryEvaluationException { bindingsIter1 = sailCon.evaluate(tupleExpr, getActiveDataset(), getBindings(), getIncludeInferred()); // Filters out all partial and invalid matches - bindingsIter2 = new FilterIteration(bindingsIter1) { + bindingsIter2 = new FilterIteration(bindingsIter1) { @Override protected boolean accept(BindingSet bindingSet) { @@ -78,7 +78,7 @@ protected boolean accept(BindingSet bindingSet) { // Convert the BindingSet objects to actual RDF statements final ValueFactory vf = getConnection().getRepository().getValueFactory(); - stIter = new ConvertingIteration(bindingsIter3) { + stIter = new ConvertingIteration(bindingsIter3) { @Override protected Statement convert(BindingSet bindingSet) { diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailQueryPreparer.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailQueryPreparer.java deleted file mode 100644 index f8c5210726e..00000000000 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailQueryPreparer.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.repository.sail; - -import org.eclipse.rdf4j.query.BooleanQuery; -import org.eclipse.rdf4j.query.GraphQuery; -import org.eclipse.rdf4j.query.TupleQuery; -import org.eclipse.rdf4j.query.Update; -import org.eclipse.rdf4j.query.algebra.evaluation.QueryPreparer; -import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource; -import org.eclipse.rdf4j.query.parser.ParsedBooleanQuery; -import org.eclipse.rdf4j.query.parser.ParsedGraphQuery; -import org.eclipse.rdf4j.query.parser.ParsedTupleQuery; -import org.eclipse.rdf4j.query.parser.ParsedUpdate; -import org.eclipse.rdf4j.repository.evaluation.RepositoryTripleSource; - -/** - * QueryPreparer for use with SailRepository. - */ -public class SailQueryPreparer implements QueryPreparer { - - private final SailRepositoryConnection con; - - private final boolean includeInferred; - - private final TripleSource source; - - public SailQueryPreparer(SailRepositoryConnection con, boolean includeInferred) { - this.con = con; - this.includeInferred = includeInferred; - this.source = new RepositoryTripleSource(con, includeInferred); - } - - @Override - public BooleanQuery prepare(ParsedBooleanQuery askQuery) { - BooleanQuery query = new SailBooleanQuery(askQuery, con); - query.setIncludeInferred(includeInferred); - return query; - } - - @Override - public TupleQuery prepare(ParsedTupleQuery tupleQuery) { - TupleQuery query = new SailTupleQuery(tupleQuery, con); - query.setIncludeInferred(includeInferred); - return query; - } - - @Override - public GraphQuery prepare(ParsedGraphQuery graphQuery) { - GraphQuery query = new SailGraphQuery(graphQuery, con); - query.setIncludeInferred(includeInferred); - return query; - } - - @Override - public Update prepare(ParsedUpdate graphUpdate) { - Update update = new SailUpdate(graphUpdate, con); - update.setIncludeInferred(includeInferred); - return update; - } - - @Override - public TripleSource getTripleSource() { - return source; - } -} diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailRepositoryConnection.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailRepositoryConnection.java index b53930ff72a..350caee5270 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailRepositoryConnection.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailRepositoryConnection.java @@ -153,7 +153,7 @@ public void setHttpClient(HttpClient client) { public void begin() throws RepositoryException { try { // always call receiveTransactionSettings(...) before calling begin(); - sailConnection.setTransactionSettings(new TransactionSetting[0]); + sailConnection.setTransactionSettings(); if (getIsolationLevel() != null) { sailConnection.begin(getIsolationLevel()); @@ -169,7 +169,7 @@ public void begin() throws RepositoryException { public void begin(IsolationLevel level) throws RepositoryException { try { // always call receiveTransactionSettings(...) before calling begin(); - sailConnection.setTransactionSettings(new TransactionSetting[0]); + sailConnection.setTransactionSettings(); if (level != null) { sailConnection.begin(level); @@ -349,7 +349,7 @@ public RepositoryResult getStatements(Resource subj, IRI pred, Value Resource... contexts) throws RepositoryException { Objects.requireNonNull(contexts, "contexts argument may not be null; either the value should be cast to Resource or an empty array should be supplied"); - CloseableIteration statements = null; + CloseableIteration statements = null; try { statements = sailConnection.getStatements(subj, pred, obj, includeInferred, contexts); return createRepositoryResult(statements); @@ -507,7 +507,7 @@ public String getNamespace(String prefix) throws RepositoryException { /** * Wraps a CloseableIteration coming from a Sail in a RepositoryResult object, applying the required conversions */ - protected RepositoryResult createRepositoryResult(CloseableIteration sailIter) { + protected RepositoryResult createRepositoryResult(CloseableIteration sailIter) { return new RepositoryResult<>(new SailCloseableIteration(sailIter)); } diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailTupleQuery.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailTupleQuery.java index 6b88a3eb96f..bc85f134f07 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailTupleQuery.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/SailTupleQuery.java @@ -44,27 +44,23 @@ public ParsedTupleQuery getParsedQuery() { public TupleQueryResult evaluate() throws QueryEvaluationException { TupleExpr tupleExpr = getParsedQuery().getTupleExpr(); - CloseableIteration bindingsIter = null; + CloseableIteration bindingsIter = null; - boolean allGood = false; try { SailConnection sailCon = getConnection().getSailConnection(); bindingsIter = sailCon.evaluate(tupleExpr, getActiveDataset(), getBindings(), getIncludeInferred()); bindingsIter = enforceMaxQueryTime(bindingsIter); - IteratingTupleQueryResult result = new IteratingTupleQueryResult( - new ArrayList<>(tupleExpr.getBindingNames()), bindingsIter); - allGood = true; - return result; - } catch (SailException e) { - throw new QueryEvaluationException(e.getMessage(), e); - } finally { - if (!allGood) { - if (bindingsIter != null) { - bindingsIter.close(); - } + return new IteratingTupleQueryResult(new ArrayList<>(tupleExpr.getBindingNames()), bindingsIter); + } catch (Throwable e) { + if (bindingsIter != null) { + bindingsIter.close(); } + if (e instanceof SailException) { + throw new QueryEvaluationException(e.getMessage(), e); + } + throw e; } } diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/config/ProxyRepositoryConfig.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/config/ProxyRepositoryConfig.java index 54867bd5e17..ea3f62b8948 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/config/ProxyRepositoryConfig.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/config/ProxyRepositoryConfig.java @@ -23,9 +23,6 @@ public class ProxyRepositoryConfig extends AbstractRepositoryImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private String proxiedID; public ProxyRepositoryConfig() { @@ -55,13 +52,22 @@ public void validate() throws RepositoryConfigException { @Override public Resource export(Model model) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(model); + } + + Resource implNode = super.export(model); + if (null != this.proxiedID) { + model.setNamespace(CONFIG.NS); + model.add(implNode, CONFIG.Proxy.proxiedID, literal(this.proxiedID)); + } + return implNode; + } + + private Resource exportLegacy(Model model) { Resource implNode = super.export(model); if (null != this.proxiedID) { - if (USE_CONFIG) { - model.add(implNode, CONFIG.Proxy.proxiedID, literal(this.proxiedID)); - } else { - model.add(implNode, PROXIED_ID, literal(this.proxiedID)); - } + model.add(implNode, PROXIED_ID, literal(this.proxiedID)); } return implNode; } diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/config/SailRepositoryConfig.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/config/SailRepositoryConfig.java index 7abdca4cc38..a42365d8bd4 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/config/SailRepositoryConfig.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/config/SailRepositoryConfig.java @@ -32,9 +32,6 @@ */ public class SailRepositoryConfig extends AbstractRepositoryImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private SailImplConfig sailImplConfig; public SailRepositoryConfig() { @@ -70,16 +67,26 @@ public void validate() throws RepositoryConfigException { @Override public Resource export(Model model) { - Resource repImplNode = super.export(model); + if (Configurations.useLegacyConfig()) { + return exportLegacy(model); + } + Resource repImplNode = super.export(model); if (sailImplConfig != null) { model.setNamespace(CONFIG.NS); Resource sailImplNode = sailImplConfig.export(model); - if (USE_CONFIG) { - model.add(repImplNode, CONFIG.Sail.impl, sailImplNode); - } else { - model.add(repImplNode, SAILIMPL, sailImplNode); - } + model.add(repImplNode, CONFIG.Sail.impl, sailImplNode); + } + + return repImplNode; + } + + private Resource exportLegacy(Model model) { + Resource repImplNode = super.export(model); + if (sailImplConfig != null) { + model.setNamespace("sr", SailRepositorySchema.NAMESPACE); + Resource sailImplNode = sailImplConfig.export(model); + model.add(repImplNode, SAILIMPL, sailImplNode); } return repImplNode; diff --git a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/helpers/SailUpdateExecutor.java b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/helpers/SailUpdateExecutor.java index 95d33441114..608c6e0cd7b 100644 --- a/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/helpers/SailUpdateExecutor.java +++ b/core/repository/sail/src/main/java/org/eclipse/rdf4j/repository/sail/helpers/SailUpdateExecutor.java @@ -171,7 +171,7 @@ protected void executeCreate(Create create, UpdateContext uc) throws SailExcepti if (graphValue instanceof Resource) { Resource namedGraph = (Resource) graphValue; - try (CloseableIteration contextIDs = con.getContextIDs()) { + try (CloseableIteration contextIDs = con.getContextIDs()) { while (contextIDs.hasNext()) { Resource contextID = contextIDs.next(); @@ -212,12 +212,12 @@ protected void executeCopy(Copy copy, UpdateContext uc, int maxExecutionTime) th } // get all statements from source and add them to destination - CloseableIteration statements = null; + CloseableIteration statements = null; try { statements = con.getStatements(null, null, null, uc.isIncludeInferred(), (Resource) source); if (maxExecutionTime > 0) { - statements = new TimeLimitIteration(statements, + statements = new TimeLimitIteration(statements, 1000L * (maxExecutionTime - clearTime)) { @Override @@ -256,12 +256,12 @@ protected void executeAdd(Add add, UpdateContext uc, int maxExecTime) throws Sai } // get all statements from source and add them to destination - CloseableIteration statements = null; + CloseableIteration statements = null; try { statements = con.getStatements(null, null, null, uc.isIncludeInferred(), (Resource) source); if (maxExecTime > 0) { - statements = new TimeLimitIteration(statements, 1000L * maxExecTime) { + statements = new TimeLimitIteration(statements, 1000L * maxExecTime) { @Override protected void throwInterruptedException() throws SailException { @@ -308,12 +308,12 @@ protected void executeMove(Move move, UpdateContext uc, int maxExecutionTime) th } // remove all statements from source and add them to destination - CloseableIteration statements = null; + CloseableIteration statements = null; try { statements = con.getStatements(null, null, null, uc.isIncludeInferred(), (Resource) source); if (maxExecutionTime > 0) { - statements = new TimeLimitIteration(statements, + statements = new TimeLimitIteration(statements, 1000L * (maxExecutionTime - clearTime)) { @Override @@ -350,11 +350,11 @@ protected void executeClear(Clear clearExpr, UpdateContext uc, int maxExecutionT } else { Scope scope = clearExpr.getScope(); if (Scope.NAMED_CONTEXTS.equals(scope)) { - CloseableIteration contextIDs = null; + CloseableIteration contextIDs = null; try { contextIDs = con.getContextIDs(); if (maxExecutionTime > 0) { - contextIDs = new TimeLimitIteration(contextIDs, + contextIDs = new TimeLimitIteration(contextIDs, 1000L * maxExecutionTime) { @Override @@ -443,7 +443,7 @@ protected void executeModify(Modify modify, UpdateContext uc, int maxExecutionTi whereClause = new QueryRoot(whereClause); } - try (CloseableIteration sourceBindings = evaluateWhereClause( + try (CloseableIteration sourceBindings = evaluateWhereClause( whereClause, uc, maxExecutionTime)) { while (sourceBindings.hasNext()) { BindingSet sourceBinding = sourceBindings.next(); @@ -473,18 +473,18 @@ private IRI[] getDefaultRemoveGraphs(Dataset dataset) { return set.toArray(new IRI[set.size()]); } - private CloseableIteration evaluateWhereClause( + private CloseableIteration evaluateWhereClause( final TupleExpr whereClause, final UpdateContext uc, final int maxExecutionTime) throws SailException, QueryEvaluationException { - CloseableIteration sourceBindings1 = null; - CloseableIteration sourceBindings2 = null; - ConvertingIteration result = null; + CloseableIteration sourceBindings1 = null; + CloseableIteration sourceBindings2 = null; + ConvertingIteration result = null; boolean allGood = false; try { sourceBindings1 = con.evaluate(whereClause, uc.getDataset(), uc.getBindingSet(), uc.isIncludeInferred()); if (maxExecutionTime > 0) { - sourceBindings2 = new TimeLimitIteration(sourceBindings1, + sourceBindings2 = new TimeLimitIteration(sourceBindings1, 1000L * maxExecutionTime) { @Override @@ -496,7 +496,7 @@ protected void throwInterruptedException() throws QueryEvaluationException { sourceBindings2 = sourceBindings1; } - result = new ConvertingIteration(sourceBindings2) { + result = new ConvertingIteration(sourceBindings2) { @Override protected BindingSet convert(BindingSet sourceBinding) throws QueryEvaluationException { diff --git a/core/repository/sail/src/test/java/org/eclipse/rdf4j/repository/sail/SailRepositoryConnectionTest.java b/core/repository/sail/src/test/java/org/eclipse/rdf4j/repository/sail/SailRepositoryConnectionTest.java index d0af7a12dd2..94043deabe3 100644 --- a/core/repository/sail/src/test/java/org/eclipse/rdf4j/repository/sail/SailRepositoryConnectionTest.java +++ b/core/repository/sail/src/test/java/org/eclipse/rdf4j/repository/sail/SailRepositoryConnectionTest.java @@ -41,7 +41,7 @@ public class SailRepositoryConnectionTest { private SailRepository sailRepository; @BeforeEach - public void setUp() throws Exception { + public void setUp() { sailConnection = mock(SailConnection.class); sailRepository = mock(SailRepository.class); @@ -49,7 +49,7 @@ public void setUp() throws Exception { } @Test - public void testPrepareQuery_not_bypassed() throws Exception { + public void testPrepareQuery_not_bypassed() { Optional response = Optional.empty(); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.TUPLE), any(), any())).thenReturn(response); when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); @@ -61,7 +61,7 @@ public void testPrepareQuery_not_bypassed() throws Exception { } @Test - public void testPrepareQuery_bypassed() throws Exception { + public void testPrepareQuery_bypassed() { TupleExpr expr = mock(TupleExpr.class); Optional response = Optional.of(expr); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.GRAPH), any(), any())).thenReturn(response); @@ -74,7 +74,7 @@ public void testPrepareQuery_bypassed() throws Exception { } @Test - public void testPrepareTupleQuery_not_bypassed() throws Exception { + public void testPrepareTupleQuery_not_bypassed() { Optional response = Optional.empty(); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.TUPLE), any(), any())).thenReturn(response); when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); @@ -86,7 +86,7 @@ public void testPrepareTupleQuery_not_bypassed() throws Exception { } @Test - public void testPrepareTupleQuery_bypassed() throws Exception { + public void testPrepareTupleQuery_bypassed() { TupleExpr expr = mock(TupleExpr.class); Optional response = Optional.of(expr); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.TUPLE), any(), any())).thenReturn(response); @@ -99,7 +99,7 @@ public void testPrepareTupleQuery_bypassed() throws Exception { } @Test - public void testPrepareGraphQuery_not_bypassed() throws Exception { + public void testPrepareGraphQuery_not_bypassed() { Optional response = Optional.empty(); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.GRAPH), any(), any())).thenReturn(response); when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); @@ -111,7 +111,7 @@ public void testPrepareGraphQuery_not_bypassed() throws Exception { } @Test - public void testPrepareGraphQuery_bypassed() throws Exception { + public void testPrepareGraphQuery_bypassed() { TupleExpr expr = mock(TupleExpr.class); Optional response = Optional.of(expr); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.GRAPH), any(), any())).thenReturn(response); @@ -124,7 +124,7 @@ public void testPrepareGraphQuery_bypassed() throws Exception { } @Test - public void testPrepareBooleanQuery_not_bypassed() throws Exception { + public void testPrepareBooleanQuery_not_bypassed() { Optional response = Optional.empty(); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.BOOLEAN), any(), any())).thenReturn(response); when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); @@ -136,7 +136,7 @@ public void testPrepareBooleanQuery_not_bypassed() throws Exception { } @Test - public void testPrepareBooleanQuery_bypassed() throws Exception { + public void testPrepareBooleanQuery_bypassed() { TupleExpr expr = mock(TupleExpr.class); Optional response = Optional.of(expr); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.BOOLEAN), any(), any())).thenReturn(response); diff --git a/core/repository/sparql/pom.xml b/core/repository/sparql/pom.xml index 18d7d2990bb..47b218d83c2 100644 --- a/core/repository/sparql/pom.xml +++ b/core/repository/sparql/pom.xml @@ -38,12 +38,4 @@ ${project.version} - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/SPARQLConnection.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/SPARQLConnection.java index 0a17338e64d..a7073f0eef0 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/SPARQLConnection.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/SPARQLConnection.java @@ -24,7 +24,6 @@ import org.eclipse.rdf4j.common.iteration.ConvertingIteration; import org.eclipse.rdf4j.common.iteration.EmptyIteration; import org.eclipse.rdf4j.common.iteration.ExceptionConvertingIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.SingletonIteration; import org.eclipse.rdf4j.http.client.HttpClientDependent; import org.eclipse.rdf4j.http.client.SPARQLProtocolSession; @@ -145,7 +144,7 @@ public String toString() { * operation is modified to respond with a success message when removing a non-existent named graph. * * @param silent the value to set this to. - * @see https://www.w3.org/TR/sparql11-update/#clear + * @see https://www.w3.org/TR/sparql11-update/#clear */ public void setSilentClear(boolean silent) { this.silentClear = silent; @@ -157,7 +156,7 @@ public void setSilentClear(boolean silent) { *

* By default, the SPARQL connection executes the {@link #clear(Resource...)} API operation by converting it to a * SPARQL `CLEAR GRAPH` update operation. This operation has an optional SILENT modifier, which can be - * enabled by setting this flag to true. The behavior of this modifier is speficied as follows in the + * enabled by setting this flag to true. The behavior of this modifier is specified as follows in the * SPARQL 1.1 Recommendation: * *

If the store records the existence of empty graphs, then the SPARQL 1.1 Update service, by default, @@ -172,7 +171,7 @@ public void setSilentClear(boolean silent) { * operation is modified to respond with a success message when removing a non-existent named graph. * * @param flag the value to set this to. - * @see https://www.w3.org/TR/sparql11-update/#clear + * @see https://www.w3.org/TR/sparql11-update/#clear * @deprecated Use {@link #setSilentClear(boolean)} instead. */ @Deprecated(since = "3.6.0") @@ -227,7 +226,7 @@ public RepositoryResult getContextIDs() throws RepositoryException { TupleQuery query = prepareTupleQuery(SPARQL, NAMEDGRAPHS, ""); iter = query.evaluate(); result = new RepositoryResult<>(new ExceptionConvertingIteration( - new ConvertingIteration(iter) { + new ConvertingIteration(iter) { @Override protected Resource convert(BindingSet bindings) throws QueryEvaluationException { @@ -236,7 +235,7 @@ protected Resource convert(BindingSet bindings) throws QueryEvaluationException }) { @Override - protected RepositoryException convert(Exception e) { + protected RepositoryException convert(RuntimeException e) { return new RepositoryException(e); } }); @@ -248,14 +247,8 @@ protected RepositoryException convert(Exception e) { throw new RepositoryException(e); } finally { if (!allGood) { - try { - if (result != null) { - result.close(); - } - } finally { - if (iter != null) { - iter.close(); - } + if (iter != null) { + iter.close(); } } } @@ -326,11 +319,12 @@ private RepositoryResult getStatementsQuadMode(Resource subj, IRI pre setBindings(tupleQuery, subj, pred, obj, contexts); tupleQuery.setIncludeInferred(includeInferred); qRes = tupleQuery.evaluate(); + result = new RepositoryResult<>(new ExceptionConvertingIteration<>( - toStatementIteration(qRes, subj, pred, obj)) { + new BindingSetStatementConvertingIteration(qRes, subj, pred, obj)) { @Override - protected RepositoryException convert(Exception e) { + protected RepositoryException convert(RuntimeException e) { return new RepositoryException(e); } }); @@ -338,14 +332,8 @@ protected RepositoryException convert(Exception e) { return result; } finally { if (!allGood) { - try { - if (result != null) { - result.close(); - } - } finally { - if (qRes != null) { - qRes.close(); - } + if (qRes != null) { + qRes.close(); } } } @@ -355,7 +343,7 @@ private RepositoryResult getStatementsSingleTriple(Resource subj, IRI boolean includeInferred, Resource... contexts) throws RepositoryException { if (hasStatement(subj, pred, obj, includeInferred, contexts)) { Statement st = getValueFactory().createStatement(subj, pred, obj); - CloseableIteration cursor; + CloseableIteration cursor; cursor = new SingletonIteration<>(st); return new RepositoryResult<>(cursor); } else { @@ -377,7 +365,7 @@ private RepositoryResult getStatementGeneral(Resource subj, IRI pred, result = new RepositoryResult<>( new ExceptionConvertingIteration<>(gRes) { @Override - protected RepositoryException convert(Exception e) { + protected RepositoryException convert(RuntimeException e) { return new RepositoryException(e); } }); @@ -385,14 +373,8 @@ protected RepositoryException convert(Exception e) { return result; } finally { if (!allGood) { - try { - if (result != null) { - result.close(); - } - } finally { - if (gRes != null) { - gRes.close(); - } + if (gRes != null) { + gRes.close(); } } } @@ -540,9 +522,6 @@ public void add(File file, String baseURI, RDFFormat dataFormat, Resource... con // RDFInserter only throws wrapped RepositoryExceptions throw (RepositoryException) e.getCause(); - } catch (RDFParseException e) { - conditionalRollback(localTransaction); - throw e; } catch (IOException | RuntimeException e) { conditionalRollback(localTransaction); throw e; @@ -570,9 +549,6 @@ public void add(URL url, String baseURI, RDFFormat dataFormat, Resource... conte // RDFInserter only throws wrapped RepositoryExceptions throw (RepositoryException) e.getCause(); - } catch (RDFParseException e) { - conditionalRollback(localTransaction); - throw e; } catch (IOException | RuntimeException e) { conditionalRollback(localTransaction); throw e; @@ -601,9 +577,6 @@ public void add(InputStream in, String baseURI, RDFFormat dataFormat, Resource.. // RDFInserter only throws wrapped RepositoryExceptions throw (RepositoryException) e.getCause(); - } catch (RDFParseException e) { - conditionalRollback(localTransaction); - throw e; } catch (IOException | RuntimeException e) { conditionalRollback(localTransaction); throw e; @@ -633,9 +606,6 @@ public void add(Reader reader, String baseURI, RDFFormat dataFormat, Resource... // RDFInserter only throws wrapped RepositoryExceptions throw (RepositoryException) e.getCause(); - } catch (RDFParseException e) { - conditionalRollback(localTransaction); - throw e; } catch (IOException | RuntimeException e) { conditionalRollback(localTransaction); throw e; @@ -680,15 +650,15 @@ public void clear(Resource... contexts) throws RepositoryException { } if (contexts.length == 0) { - sparqlTransaction.append(clearMode + " ALL "); + sparqlTransaction.append(clearMode).append(" ALL "); sparqlTransaction.append("; "); } else { for (Resource context : contexts) { if (context == null) { - sparqlTransaction.append(clearMode + " DEFAULT "); + sparqlTransaction.append(clearMode).append(" DEFAULT "); sparqlTransaction.append("; "); } else if (context instanceof IRI) { - sparqlTransaction.append(clearMode + " GRAPH <" + context.stringValue() + "> "); + sparqlTransaction.append(clearMode).append(" GRAPH <").append(context.stringValue()).append("> "); sparqlTransaction.append("; "); } else { throw new RepositoryException("SPARQL does not support named graphs identified by blank nodes."); @@ -800,7 +770,7 @@ private String createInsertDataCommand(Iterable statements, // the blank node id. namedGraph = "urn:nodeid:" + context.stringValue(); } - qb.append(" GRAPH <" + namedGraph + "> { \n"); + qb.append(" GRAPH <").append(namedGraph).append("> { \n"); } createDataBody(qb, statements, true); if (context != null) { @@ -829,7 +799,7 @@ private String createDeleteDataCommand(Iterable statements, // the blank node id. namedGraph = "urn:nodeid:" + context.stringValue(); } - qb.append(" GRAPH <" + namedGraph + "> { \n"); + qb.append(" GRAPH <").append(namedGraph).append("> { \n"); } createDataBody(qb, statements, true); if (context != null) { @@ -856,16 +826,16 @@ private void createDataBody(StringBuilder qb, Iterable stat // the blank node id. namedGraph = "urn:nodeid:" + context.stringValue(); } - qb.append(" GRAPH <" + namedGraph + "> { \n"); + qb.append(" GRAPH <").append(namedGraph).append("> { \n"); } } if (st.getSubject() instanceof BNode) { - qb.append("_:" + st.getSubject().stringValue() + " "); + qb.append("_:").append(st.getSubject().stringValue()).append(" "); } else { - qb.append("<" + st.getSubject().stringValue() + "> "); + qb.append("<").append(st.getSubject().stringValue()).append("> "); } - qb.append("<" + st.getPredicate().stringValue() + "> "); + qb.append("<").append(st.getPredicate().stringValue()).append("> "); if (st.getObject() instanceof Literal) { Literal lit = (Literal) st.getObject(); @@ -877,13 +847,13 @@ private void createDataBody(StringBuilder qb, Iterable stat qb.append("@"); qb.append(lit.getLanguage().get()); } else { - qb.append("^^<" + lit.getDatatype().stringValue() + ">"); + qb.append("^^<").append(lit.getDatatype().stringValue()).append(">"); } qb.append(" "); } else if (st.getObject() instanceof BNode) { - qb.append("_:" + st.getObject().stringValue() + " "); + qb.append("_:").append(st.getObject().stringValue()).append(" "); } else { - qb.append("<" + st.getObject().stringValue() + "> "); + qb.append("<").append(st.getObject().stringValue()).append("> "); } qb.append(". \n"); @@ -994,10 +964,10 @@ private String createDeletePatternCommand(Resource subject, IRI predicate, Value // the blank node id. namedGraph = "urn:nodeid:" + context.stringValue(); } - qb.append(" GRAPH <" + namedGraph + "> { \n"); + qb.append(" GRAPH <").append(namedGraph).append("> { \n"); } createBGP(qb, subject, predicate, object); - if (context != null && context instanceof IRI) { + if (context instanceof IRI) { qb.append(" } \n"); } } @@ -1012,16 +982,16 @@ private String createDeletePatternCommand(Resource subject, IRI predicate, Value private void createBGP(StringBuilder qb, Resource subject, IRI predicate, Value object) { if (subject != null) { if (subject instanceof BNode) { - qb.append("_:" + subject.stringValue() + " "); + qb.append("_:").append(subject.stringValue()).append(" "); } else { - qb.append("<" + subject.stringValue() + "> "); + qb.append("<").append(subject.stringValue()).append("> "); } } else { qb.append("?subj"); } if (predicate != null) { - qb.append("<" + predicate.stringValue() + "> "); + qb.append("<").append(predicate.stringValue()).append("> "); } else { qb.append("?pred"); } @@ -1037,13 +1007,13 @@ private void createBGP(StringBuilder qb, Resource subject, IRI predicate, Value qb.append("@"); qb.append(lit.getLanguage().get()); } else { - qb.append("^^<" + lit.getDatatype().stringValue() + ">"); + qb.append("^^<").append(lit.getDatatype().stringValue()).append(">"); } qb.append(" "); } else if (object instanceof BNode) { - qb.append("_:" + object.stringValue() + " "); + qb.append("_:").append(object.stringValue()).append(" "); } else { - qb.append("<" + object.stringValue() + "> "); + qb.append("<").append(object.stringValue()).append("> "); } } else { qb.append("?obj"); @@ -1065,38 +1035,33 @@ protected boolean isSilentClear() { return silentClear; } - /** - * Converts a {@link TupleQueryResult} resulting from the {@link #EVERYTHING_WITH_GRAPH} to a statement by using the - * respective values from the {@link BindingSet} or (if provided) the ones from the arguments. - * - * @param iter the {@link TupleQueryResult} - * @param subj the subject {@link Resource} used as input or null if wildcard was used - * @param pred the predicate {@link IRI} used as input or null if wildcard was used - * @param obj the object {@link Value} used as input or null if wildcard was used - * @return the converted iteration - */ - @Deprecated(since = "4.1.0", forRemoval = true) - protected Iteration toStatementIteration(TupleQueryResult iter, - final Resource subj, final IRI pred, final Value obj) { + private ModelFactory getModelFactory() { + return modelFactory; + } - return new ConvertingIteration<>(iter) { + private static class BindingSetStatementConvertingIteration extends ConvertingIteration { - @Override - protected Statement convert(BindingSet b) throws QueryEvaluationException { + private final Resource subj; + private final IRI pred; + private final Value obj; - Resource s = subj == null ? (Resource) b.getValue("s") : subj; - IRI p = pred == null ? (IRI) b.getValue("p") : pred; - Value o = obj == null ? b.getValue("o") : obj; - Resource ctx = (Resource) b.getValue("ctx"); + public BindingSetStatementConvertingIteration(TupleQueryResult qRes, Resource subj, IRI pred, Value obj) { + super(qRes); + this.subj = subj; + this.pred = pred; + this.obj = obj; + } - return SimpleValueFactory.getInstance().createStatement(s, p, o, ctx); - } + @Override + protected Statement convert(BindingSet b) throws QueryEvaluationException { - }; - } + Resource s = subj == null ? (Resource) b.getValue("s") : subj; + IRI p = pred == null ? (IRI) b.getValue("p") : pred; + Value o = obj == null ? b.getValue("o") : obj; + Resource ctx = (Resource) b.getValue("ctx"); - private ModelFactory getModelFactory() { - return modelFactory; - } + return SimpleValueFactory.getInstance().createStatement(s, p, o, ctx); + } + } } diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/config/SPARQLRepositoryConfig.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/config/SPARQLRepositoryConfig.java index 1b055771adb..0e4dca2dacb 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/config/SPARQLRepositoryConfig.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/config/SPARQLRepositoryConfig.java @@ -30,9 +30,6 @@ */ public class SPARQLRepositoryConfig extends AbstractRepositoryImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private static final ValueFactory vf = SimpleValueFactory.getInstance(); public static final String NAMESPACE = "http://www.openrdf.org/config/repository/sparql#"; @@ -40,7 +37,7 @@ public class SPARQLRepositoryConfig extends AbstractRepositoryImplConfig { /** * Configuration setting for the SPARQL query endpoint. Required. * - * @deprecated use {@link CONFIG#queryEndpoint} instead. + * @deprecated use {@link CONFIG.Sparql#queryEndpoint} instead. */ public static final IRI QUERY_ENDPOINT = vf .createIRI("http://www.openrdf.org/config/repository/sparql#query-endpoint"); @@ -48,7 +45,7 @@ public class SPARQLRepositoryConfig extends AbstractRepositoryImplConfig { /** * Configuration setting for the SPARQL update endpoint. Optional. * - * @deprecated use {@link CONFIG#updateEndpoint} instead. + * @deprecated use {@link CONFIG.Sparql#updateEndpoint} instead. */ public static final IRI UPDATE_ENDPOINT = vf .createIRI("http://www.openrdf.org/config/repository/sparql#update-endpoint"); @@ -57,7 +54,7 @@ public class SPARQLRepositoryConfig extends AbstractRepositoryImplConfig { * Configuration setting for enabling/disabling direct result pass-through. Optional. * * @see SPARQLProtocolSession#isPassThroughEnabled() - * @deprecated use {@link CONFIG#passThroughEnabled} instead. + * @deprecated use {@link CONFIG.Sparql#passThroughEnabled} instead. */ public static final IRI PASS_THROUGH_ENABLED = vf .createIRI("http://www.openrdf.org/config/repository/sparql#pass-through-enabled"); @@ -108,29 +105,39 @@ public void validate() throws RepositoryConfigException { @Override public Resource export(Model m) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(m); + } + + Resource implNode = super.export(m); + + m.setNamespace(CONFIG.NS); + if (getQueryEndpointUrl() != null) { + m.add(implNode, CONFIG.Sparql.queryEndpoint, vf.createIRI(getQueryEndpointUrl())); + } + if (getUpdateEndpointUrl() != null) { + m.add(implNode, CONFIG.Sparql.updateEndpoint, vf.createIRI(getUpdateEndpointUrl())); + } + if (getPassThroughEnabled() != null) { + m.add(implNode, CONFIG.Sparql.passThroughEnabled, BooleanLiteral.valueOf(getPassThroughEnabled())); + } + + return implNode; + } + + private Resource exportLegacy(Model m) { + Resource implNode = super.export(m); m.setNamespace("sparql", NAMESPACE); if (getQueryEndpointUrl() != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Sparql.queryEndpoint, vf.createIRI(getQueryEndpointUrl())); - } else { - m.add(implNode, QUERY_ENDPOINT, vf.createIRI(getQueryEndpointUrl())); - } + m.add(implNode, QUERY_ENDPOINT, vf.createIRI(getQueryEndpointUrl())); } if (getUpdateEndpointUrl() != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Sparql.updateEndpoint, vf.createIRI(getUpdateEndpointUrl())); - } else { - m.add(implNode, UPDATE_ENDPOINT, vf.createIRI(getUpdateEndpointUrl())); - } + m.add(implNode, UPDATE_ENDPOINT, vf.createIRI(getUpdateEndpointUrl())); } if (getPassThroughEnabled() != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Sparql.passThroughEnabled, BooleanLiteral.valueOf(getPassThroughEnabled())); - } else { - m.add(implNode, PASS_THROUGH_ENABLED, BooleanLiteral.valueOf(getPassThroughEnabled())); - } + m.add(implNode, PASS_THROUGH_ENABLED, BooleanLiteral.valueOf(getPassThroughEnabled())); } return implNode; diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/CollectionIteration.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/CollectionIteration.java index f3363ca1842..bc285622cc9 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/CollectionIteration.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/CollectionIteration.java @@ -21,7 +21,7 @@ * * @author Andreas Schwarte */ -public class CollectionIteration extends AbstractCloseableIteration { +public class CollectionIteration extends AbstractCloseableIteration { protected final Collection collection; @@ -37,7 +37,7 @@ public CollectionIteration(Collection collection) { } @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (isClosed()) { return false; } @@ -45,7 +45,7 @@ public boolean hasNext() throws X { } @Override - public E next() throws X { + public E next() { if (isClosed()) { throw new NoSuchElementException("The iteration has been closed."); } @@ -53,7 +53,7 @@ public E next() throws X { } @Override - public void remove() throws X { + public void remove() { throw new UnsupportedOperationException("Remove not supported on CollectionIteration"); } diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/JoinExecutorBase.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/JoinExecutorBase.java index 72432b9871d..f3e59da63e1 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/JoinExecutorBase.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/JoinExecutorBase.java @@ -26,7 +26,7 @@ * * @author Andreas Schwarte */ -public abstract class JoinExecutorBase extends LookAheadIteration { +public abstract class JoinExecutorBase extends LookAheadIteration { /** * @deprecated No replacement, don't use static shared int variables. @@ -38,9 +38,9 @@ public abstract class JoinExecutorBase extends LookAheadIteration leftIter; + protected final CloseableIteration leftIter; - protected volatile CloseableIteration rightIter; + protected volatile CloseableIteration rightIter; /** * @deprecated Use {@link AbstractCloseableIteration#isClosed()} instead. @@ -52,9 +52,9 @@ public abstract class JoinExecutorBase extends LookAheadIteration> rightQueue = new QueueCursor<>(1024); + protected final QueueCursor> rightQueue = new QueueCursor<>(1024); - protected JoinExecutorBase(CloseableIteration leftIter, TupleExpr rightArg, + protected JoinExecutorBase(CloseableIteration leftIter, TupleExpr rightArg, BindingSet bindings) throws QueryEvaluationException { this.leftIter = leftIter; this.rightArg = rightArg; @@ -87,9 +87,9 @@ public final void run() { */ protected abstract void handleBindings() throws Exception; - public void addResult(CloseableIteration res) { + public void addResult(CloseableIteration res) { /* optimization: avoid adding empty results */ - if (res instanceof EmptyIteration) { + if (res instanceof EmptyIteration) { return; } @@ -116,7 +116,7 @@ public T getNextElement() throws QueryEvaluationException { // if we see any weird behavior check here !! while (rightIter != null || rightQueue.hasNext()) { - CloseableIteration nextRightIter = rightIter; + CloseableIteration nextRightIter = rightIter; if (nextRightIter == null) { nextRightIter = rightIter = rightQueue.next(); } @@ -143,13 +143,13 @@ public void handleClose() throws QueryEvaluationException { rightQueue.close(); } finally { try { - CloseableIteration toCloseRightIter = rightIter; + CloseableIteration toCloseRightIter = rightIter; rightIter = null; if (toCloseRightIter != null) { toCloseRightIter.close(); } } finally { - CloseableIteration toCloseLeftIter = leftIter; + CloseableIteration toCloseLeftIter = leftIter; if (toCloseLeftIter != null) { toCloseLeftIter.close(); } diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedService.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedService.java index 2da8252deb2..936733bfa58 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedService.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedService.java @@ -19,7 +19,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.EmptyIteration; -import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.common.iteration.SilentIteration; import org.eclipse.rdf4j.query.Binding; import org.eclipse.rdf4j.query.BindingSet; @@ -67,7 +66,7 @@ private class BatchingServiceIteration extends JoinExecutorBase { * @param inputBindings * @throws QueryEvaluationException */ - public BatchingServiceIteration(CloseableIteration inputBindings, + public BatchingServiceIteration(CloseableIteration inputBindings, int blockSize, Service service) throws QueryEvaluationException { super(inputBindings, null, EmptyBindingSet.getInstance()); this.blockSize = blockSize; @@ -86,7 +85,7 @@ protected void handleBindings() throws Exception { } blockBindings.add(leftIter.next()); } - CloseableIteration materializedIter = new CollectionIteration<>( + CloseableIteration materializedIter = new CollectionIteration<>( blockBindings); addResult(evaluateInternal(service, materializedIter, service.getBaseURI())); } @@ -128,12 +127,12 @@ protected void handleBindings() throws Exception { * * @author Andreas Schwarte */ - private static class CloseConnectionIteration implements CloseableIteration { + private static class CloseConnectionIteration implements CloseableIteration { - private final CloseableIteration delegate; + private final CloseableIteration delegate; private final RepositoryConnection connection; - private CloseConnectionIteration(CloseableIteration delegate, + private CloseConnectionIteration(CloseableIteration delegate, RepositoryConnection connection) { super(); this.delegate = delegate; @@ -207,7 +206,7 @@ public RepositoryFederatedService(Repository repo, boolean shutDown) { * Insert bindings into SELECT query and evaluate */ @Override - public CloseableIteration select(Service service, Set projectionVars, + public CloseableIteration select(Service service, Set projectionVars, BindingSet bindings, String baseUri) throws QueryEvaluationException { RepositoryConnection conn = null; @@ -228,7 +227,7 @@ public CloseableIteration select(Service s TupleQueryResult res = query.evaluate(); // insert original bindings again - CloseableIteration result = new InsertBindingSetCursor(res, bindings); + CloseableIteration result = new InsertBindingSetCursor(res, bindings); if (useFreshConnection) { result = new CloseConnectionIteration(result, conn); @@ -294,8 +293,8 @@ public boolean ask(Service service, BindingSet bindings, String baseUri) throws } @Override - public CloseableIteration evaluate(Service service, - CloseableIteration bindings, String baseUri) + public CloseableIteration evaluate(Service service, + CloseableIteration bindings, String baseUri) throws QueryEvaluationException { if (boundJoinBlockSize > 0) { @@ -313,8 +312,8 @@ public CloseableIteration evaluate(Service * clause, if this yields an exception fall back to the naive implementation. This method deals with SILENT * SERVICEs. */ - protected CloseableIteration evaluateInternal(Service service, - CloseableIteration bindings, String baseUri) + protected CloseableIteration evaluateInternal(Service service, + CloseableIteration bindings, String baseUri) throws QueryEvaluationException { // materialize all bindings (to allow for fallback in case of errors) @@ -334,7 +333,7 @@ protected CloseableIteration evaluateInter // below we need to take care for SILENT services RepositoryConnection conn = null; - CloseableIteration result = null; + CloseableIteration result = null; try { // fallback to simple evaluation (just a single binding) if (allBindings.size() == 1) { @@ -386,7 +385,9 @@ protected CloseableIteration evaluateInter if (useFreshConnection) { closeQuietly(conn); } - Iterations.closeCloseable(result); + if (result != null) { + result.close(); + } if (service.isSilent()) { return new CollectionIteration<>(allBindings); } @@ -405,7 +406,9 @@ protected CloseableIteration evaluateInter if (useFreshConnection) { closeQuietly(conn); } - Iterations.closeCloseable(result); + if (result != null) { + result.close(); + } if (service.isSilent()) { return new CollectionIteration<>(allBindings); } @@ -414,7 +417,9 @@ protected CloseableIteration evaluateInter if (useFreshConnection) { closeQuietly(conn); } - Iterations.closeCloseable(result); + if (result != null) { + result.close(); + } // suppress special exceptions (e.g. UndeclaredThrowable with wrapped // QueryEval) if silent if (service.isSilent()) { @@ -433,10 +438,10 @@ protected CloseableIteration evaluateInter * @param baseUri the base URI * @return resulting iteration */ - private CloseableIteration evaluateInternalFallback(Service service, + private CloseableIteration evaluateInternalFallback(Service service, List allBindings, String baseUri) { - CloseableIteration res = new FallbackServiceIteration(service, + CloseableIteration res = new FallbackServiceIteration(service, allBindings, baseUri); if (service.isSilent()) { diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/SPARQLCrossProductIteration.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/SPARQLCrossProductIteration.java index 2d36cdefdf8..8620703e8a7 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/SPARQLCrossProductIteration.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/SPARQLCrossProductIteration.java @@ -29,17 +29,17 @@ * * @author Andreas Schwarte */ -public class SPARQLCrossProductIteration extends LookAheadIteration { +public class SPARQLCrossProductIteration extends LookAheadIteration { protected final List inputBindings; - protected final CloseableIteration resultIteration; + protected final CloseableIteration resultIteration; protected Iterator inputBindingsIterator = null; protected BindingSet currentInputBinding = null; - public SPARQLCrossProductIteration(CloseableIteration resultIteration, + public SPARQLCrossProductIteration(CloseableIteration resultIteration, List inputBindings) { super(); this.resultIteration = resultIteration; diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/ServiceJoinConversionIteration.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/ServiceJoinConversionIteration.java index 20b9695b997..3617ab9ed0e 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/ServiceJoinConversionIteration.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/federation/ServiceJoinConversionIteration.java @@ -28,11 +28,11 @@ */ @Deprecated(since = "4.1.0") public class ServiceJoinConversionIteration - extends ConvertingIteration { + extends ConvertingIteration { protected final List bindings; - public ServiceJoinConversionIteration(CloseableIteration iter, + public ServiceJoinConversionIteration(CloseableIteration iter, List bindings) { super(iter); this.bindings = bindings; diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/query/InsertBindingSetCursor.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/query/InsertBindingSetCursor.java index 6546d31538e..2c02c25dc38 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/query/InsertBindingSetCursor.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/query/InsertBindingSetCursor.java @@ -21,11 +21,11 @@ * * @author James Leigh */ -public class InsertBindingSetCursor extends IterationWrapper { +public class InsertBindingSetCursor extends IterationWrapper { private final BindingSet bindings; - public InsertBindingSetCursor(CloseableIteration delegate, + public InsertBindingSetCursor(CloseableIteration delegate, BindingSet bindings) { super(delegate); this.bindings = bindings; diff --git a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/query/QueryStringUtil.java b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/query/QueryStringUtil.java index d9de8d5215a..02c8e40ed38 100644 --- a/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/query/QueryStringUtil.java +++ b/core/repository/sparql/src/main/java/org/eclipse/rdf4j/repository/sparql/query/QueryStringUtil.java @@ -15,6 +15,7 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.util.Literals; import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.BindingSet; @@ -171,7 +172,7 @@ private static StringBuilder appendValue(StringBuilder sb, Literal lit) { if (Literals.isLanguageLiteral(lit)) { sb.append('@'); sb.append(lit.getLanguage().get()); - } else if (!lit.getDatatype().equals(XSD.STRING)) { + } else if (lit.getCoreDatatype() != CoreDatatype.XSD.STRING) { // Don't append type if it's xsd:string, this keeps it compatible with RDF 1.0 sb.append("^^<"); sb.append(lit.getDatatype().stringValue()); diff --git a/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLConnectionTest.java b/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLConnectionTest.java index e799ffb264a..081b9d09e07 100644 --- a/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLConnectionTest.java +++ b/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLConnectionTest.java @@ -39,13 +39,13 @@ public class SPARQLConnectionTest { private final ValueFactory vf = SimpleValueFactory.getInstance(); @BeforeEach - public void setUp() throws Exception { + public void setUp() { client = mock(SPARQLProtocolSession.class); subject = new SPARQLConnection(null, client); } @Test - public void setParserConfigPassesToProtocolSession() throws Exception { + public void setParserConfigPassesToProtocolSession() { ParserConfig config = new ParserConfig(); subject.setParserConfig(config); diff --git a/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLRepositoryTest.java b/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLRepositoryTest.java index e00b5c217c1..d89d35ad1b1 100644 --- a/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLRepositoryTest.java +++ b/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/SPARQLRepositoryTest.java @@ -28,7 +28,7 @@ public class SPARQLRepositoryTest { TupleQueryResultFormat customPreferred = TupleQueryResultFormat.CSV; @BeforeEach - public void setUp() throws Exception { + public void setUp() { } @Test @@ -67,7 +67,7 @@ public RDF4JProtocolSession createRDF4JProtocolSession(String serverURL) { assertThat(rep.createSPARQLProtocolSession().getPreferredTupleQueryResultFormat()).isEqualTo(customPreferred); } - public void testPassThroughEnabled() throws Exception { + public void testPassThroughEnabled() { SPARQLRepository rep = new SPARQLRepository(endpointUrl); assertThat(rep.getPassThroughEnabled()).isNull(); assertThat(rep.createSPARQLProtocolSession()).isNotNull(); diff --git a/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedServiceTest.java b/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedServiceTest.java index 564d5e64078..91659abc7d7 100644 --- a/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedServiceTest.java +++ b/core/repository/sparql/src/test/java/org/eclipse/rdf4j/repository/sparql/federation/RepositoryFederatedServiceTest.java @@ -17,7 +17,7 @@ public class RepositoryFederatedServiceTest { @Test - public void testInsertValuesClause() throws Exception { + public void testInsertValuesClause() { // dummy instance for test RepositoryFederatedService inst = new RepositoryFederatedService(null); diff --git a/core/rio/api/pom.xml b/core/rio/api/pom.xml index fdc87a2b33f..27149ff4de7 100644 --- a/core/rio/api/pom.xml +++ b/core/rio/api/pom.xml @@ -61,10 +61,6 @@ - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/AbstractRDFParser.java b/core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/AbstractRDFParser.java index 27a8a80266f..a1b064b7a19 100644 --- a/core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/AbstractRDFParser.java +++ b/core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/AbstractRDFParser.java @@ -31,6 +31,7 @@ import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.rio.ParseErrorListener; import org.eclipse.rdf4j.rio.ParseLocationListener; @@ -489,6 +490,21 @@ protected Literal createLiteral(String label, String lang, IRI datatype, long li valueFactory, lineNo, columnNo); } + /** + * Creates a {@link Literal} object with the supplied parameters, using the lineNo and columnNo to enhance error + * messages or exceptions that may be generated during the creation of the literal. + * + * @see org.eclipse.rdf4j.rio.helpers.RDFParserHelper#createLiteral(String, String, IRI, ParserConfig, + * ParseErrorListener, ValueFactory, long, long) + */ + protected Literal createLiteral(String label, String lang, CoreDatatype datatype, long lineNo, long columnNo) + throws RDFParseException { + + return RDFParserHelper.createLiteral(label, lang, datatype.getIri(), getParserConfig(), getParseErrorListener(), + valueFactory, lineNo, columnNo); + + } + /** * Creates a new {@link Statement} object with the supplied components. */ diff --git a/core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/XMLReaderBasedParser.java b/core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/XMLReaderBasedParser.java index a0b2a86a8a4..d1edb1d59a3 100644 --- a/core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/XMLReaderBasedParser.java +++ b/core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/XMLReaderBasedParser.java @@ -10,10 +10,8 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.helpers; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Set; import org.eclipse.rdf4j.common.xml.XMLReaderFactory; @@ -31,10 +29,13 @@ */ public abstract class XMLReaderBasedParser extends AbstractRDFParser { - private final static Set> compulsoryXmlFeatureSettings = new HashSet<>( - Arrays.asList(XMLParserSettings.SECURE_PROCESSING, XMLParserSettings.DISALLOW_DOCTYPE_DECL, - XMLParserSettings.EXTERNAL_GENERAL_ENTITIES, XMLParserSettings.EXTERNAL_PARAMETER_ENTITIES, - XMLParserSettings.LOAD_EXTERNAL_DTD)); + private final static Set> compulsoryXmlFeatureSettings = Set.of( + XMLParserSettings.SECURE_PROCESSING, + XMLParserSettings.DISALLOW_DOCTYPE_DECL, + XMLParserSettings.EXTERNAL_GENERAL_ENTITIES, + XMLParserSettings.EXTERNAL_PARAMETER_ENTITIES, + XMLParserSettings.LOAD_EXTERNAL_DTD + ); protected XMLReaderBasedParser(ValueFactory f) { super(f); diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/AbstractParserHandlingTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/AbstractParserHandlingTest.java index 048fbb93cb2..a17d8f161e5 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/AbstractParserHandlingTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/AbstractParserHandlingTest.java @@ -124,7 +124,7 @@ public abstract class AbstractParserHandlingTest { * @param unknownDatatypeStatements A {@link Model} containing statements which all contain unknown datatypes. * @return An InputStream based on the given parameters. */ - protected InputStream getUnknownDatatypeStream(Model model) throws Exception { + protected InputStream getUnknownDatatypeStream(Model model) { return serialize(model); } @@ -135,7 +135,7 @@ protected InputStream getUnknownDatatypeStream(Model model) throws Exception { * @param knownDatatypeStatements A {@link Model} containing statements which all contain known datatypes. * @return An InputStream based on the given parameters. */ - protected InputStream getKnownDatatypeStream(Model model) throws Exception { + protected InputStream getKnownDatatypeStream(Model model) { return serialize(model); } @@ -146,7 +146,7 @@ protected InputStream getKnownDatatypeStream(Model model) throws Exception { * @param unknownLanguageStatements A {@link Model} containing statements which all contain unknown language tags. * @return An InputStream based on the given parameters. */ - protected InputStream getUnknownLanguageStream(Model model) throws Exception { + protected InputStream getUnknownLanguageStream(Model model) { return serialize(model); } @@ -157,7 +157,7 @@ protected InputStream getUnknownLanguageStream(Model model) throws Exception { * @param knownLanguageStatements A {@link Model} containing statements which all contain known language tags. * @return An InputStream based on the given parameters. */ - protected InputStream getKnownLanguageStream(Model model) throws Exception { + protected InputStream getKnownLanguageStream(Model model) { return serialize(model); } @@ -211,10 +211,9 @@ protected RDFWriter createWriter(OutputStream output) { } /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { testParser = getParser(); testParser.setValueFactory(vf); @@ -226,10 +225,9 @@ public void setUp() throws Exception { } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { testListener.reset(); testListener = null; testStatements.clear(); diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/BaseURIHandlingTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/BaseURIHandlingTest.java index 5985c688cff..17f96c7afe0 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/BaseURIHandlingTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/BaseURIHandlingTest.java @@ -35,7 +35,7 @@ public void testParseWithoutBaseUri_Absolute() throws Exception { } @Test - public void testParseWithoutBaseUri_Relative() throws Exception { + public void testParseWithoutBaseUri_Relative() { StatementCollector collector = new StatementCollector(); RDFParser parser = getParserFactory().getParser(); parser.setRDFHandler(collector); diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RDFWriterTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RDFWriterTest.java index 537e9b6f24f..375f91c2da7 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RDFWriterTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RDFWriterTest.java @@ -660,7 +660,7 @@ public void testIllegalPrefix() throws RDFHandlerException, RDFParseException, I } @Test - public void testDefaultNamespace() throws Exception { + public void testDefaultNamespace() { ByteArrayOutputStream out = new ByteArrayOutputStream(); RDFWriter rdfWriter = rdfWriterFactory.getWriter(out); setupWriterConfig(rdfWriter.getWriterConfig()); @@ -1860,7 +1860,7 @@ public void testRDFStarConversion() throws IOException { } @Test - public void testGetSupportedSettings() throws Exception { + public void testGetSupportedSettings() { RDFWriter writer = rdfWriterFactory.getWriter(System.out); Collection> supportedSettings = writer.getSupportedSettings(); diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RioConfigTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RioConfigTest.java index d9cd230eda1..236f3b20d44 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RioConfigTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RioConfigTest.java @@ -27,7 +27,7 @@ public class RioConfigTest { private final BooleanRioSetting testSetting = new BooleanRioSetting(key, "test setting", true); @BeforeEach - public void setUp() throws Exception { + public void setUp() { config = new RioConfig(); } @@ -37,38 +37,38 @@ public void cleanup() { } @Test - public void testIsSetDefault() throws Exception { + public void testIsSetDefault() { assertThat(config.isSet(testSetting)).isFalse(); } @Test - public void testIsSetWithSystemPropertyOverride() throws Exception { + public void testIsSetWithSystemPropertyOverride() { System.setProperty(key, "false"); assertThat(config.isSet(testSetting)).isTrue(); } @Test - public void testIsSetWithExplicitSet() throws Exception { + public void testIsSetWithExplicitSet() { config.set(testSetting, false); assertThat(config.isSet(testSetting)).isTrue(); } @Test - public void testUseDefaultsNoOverride() throws Exception { + public void testUseDefaultsNoOverride() { config.set(testSetting, false); config.useDefaults(); assertThat(config.isSet(testSetting)).isFalse(); } @Test - public void testUseDefaultsWithOverride() throws Exception { + public void testUseDefaultsWithOverride() { System.setProperty(key, "false"); config.useDefaults(); assertThat(config.isSet(testSetting)).isTrue(); } @Test - public void testGetWithSystemPropertyOverride() throws Exception { + public void testGetWithSystemPropertyOverride() { System.setProperty(key, "false"); assertThat(config.get(testSetting)).as("default setting overridden by system prop").isFalse(); @@ -86,7 +86,7 @@ public void testGetWithSystemPropertyOverride() throws Exception { } @Test - public void testGetWithUnsupportedConversionType() throws Exception { + public void testGetWithUnsupportedConversionType() { // we deliberately do not use StringRioSetting as that supports conversion of system property values AbstractRioSetting nonConvertableSetting = new AbstractRioSetting<>(key, "test setting", "default value") { diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RioTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RioTest.java index abe12332309..b3165949885 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RioTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/RioTest.java @@ -97,12 +97,12 @@ public void parseReader_CustomConfig() throws Exception { } @Test - public void createParser_existing() throws Exception { + public void createParser_existing() { RDFParser parser = Rio.createParser(TEST_FORMAT); assertThat(parser).isEqualTo(mockParser); } - public void createParser_unknown() throws Exception { + public void createParser_unknown() { RDFFormat unknownFormat = new RDFFormat("unknown", "test/unknown", StandardCharsets.UTF_8, "unknown", false, false, false); diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/AbstractRDFParserTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/AbstractRDFParserTest.java index 43a7b489160..195eacf4ffa 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/AbstractRDFParserTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/AbstractRDFParserTest.java @@ -14,7 +14,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.IOException; import java.io.InputStream; import java.io.Reader; @@ -38,12 +37,12 @@ public RDFFormat getRDFFormat() { } @Override - public void parse(InputStream in, String baseURI) throws IOException, RDFParseException, RDFHandlerException { + public void parse(InputStream in, String baseURI) throws RDFParseException, RDFHandlerException { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void parse(Reader reader, String baseURI) throws IOException, RDFParseException, RDFHandlerException { + public void parse(Reader reader, String baseURI) throws RDFParseException, RDFHandlerException { throw new UnsupportedOperationException("Not supported yet."); } @@ -57,12 +56,12 @@ public Resource getBNode(String id) { } @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = new MyRDFParser(); } @Test - public void testSkolemOrigin() throws Exception { + public void testSkolemOrigin() { parser.getParserConfig().set(BasicParserSettings.SKOLEMIZE_ORIGIN, "http://www.example.com"); assertTrue(parser.getBNode().toString().startsWith("http://www.example.com")); @@ -70,7 +69,7 @@ public void testSkolemOrigin() throws Exception { } @Test - public void testSkolemOriginReset() throws Exception { + public void testSkolemOriginReset() { parser.getParserConfig().set(BasicParserSettings.SKOLEMIZE_ORIGIN, "http://www.example.com"); parser.getParserConfig().set(BasicParserSettings.SKOLEMIZE_ORIGIN, ""); @@ -80,7 +79,7 @@ public void testSkolemOriginReset() throws Exception { } @Test - public void testNodeIdHashing() throws Exception { + public void testNodeIdHashing() { // node ids look like "genid_.*-suffix assertThat(parser.createNode("someid").stringValue()) .endsWith("-someid"); diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/BooleanRioSettingTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/BooleanRioSettingTest.java index 779347aab02..49aceec0e52 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/BooleanRioSettingTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/BooleanRioSettingTest.java @@ -21,11 +21,11 @@ public class BooleanRioSettingTest extends RioSettingTest { @Test @Override @Disabled - public void testConvertIllegal() throws Exception { + public void testConvertIllegal() { } @Test - public void testConvertLegalStringVariants() throws Exception { + public void testConvertLegalStringVariants() { assertThat(subject.convert("True")).isTrue(); assertThat(subject.convert("Foo")).isFalse(); assertThat(subject.convert("false")).isFalse(); diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/NTriplesUtilTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/NTriplesUtilTest.java index e61f509c257..ea59547447e 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/NTriplesUtilTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/NTriplesUtilTest.java @@ -39,7 +39,7 @@ public class NTriplesUtilTest { private final ValueFactory f = SimpleValueFactory.getInstance(); @BeforeEach - public void setUp() throws Exception { + public void setUp() { appendable = new StringBuilder(); } diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/RDFParserHelperTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/RDFParserHelperTest.java index dd526345f31..2213d046d69 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/RDFParserHelperTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/RDFParserHelperTest.java @@ -54,10 +54,9 @@ public class RDFParserHelperTest { private ValueFactory valueFactory; /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { parserConfig = new ParserConfig(); // By default we wipe out the SPI loaded datatype and language handlers parserConfig.set(BasicParserSettings.DATATYPE_HANDLERS, Collections.emptyList()); @@ -69,10 +68,9 @@ public void setUp() throws Exception { } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } /** @@ -81,7 +79,7 @@ public void tearDown() throws Exception { * . */ @Test - public final void testCreateLiteralLabelNull() throws Exception { + public final void testCreateLiteralLabelNull() { assertThatThrownBy( () -> RDFParserHelper.createLiteral(null, null, null, parserConfig, errListener, valueFactory)) .isInstanceOf(NullPointerException.class) @@ -94,7 +92,7 @@ public final void testCreateLiteralLabelNull() throws Exception { * . */ @Test - public final void testCreateLiteralLabelOnly() throws Exception { + public final void testCreateLiteralLabelOnly() { Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, null, null, parserConfig, errListener, valueFactory); @@ -109,7 +107,7 @@ public final void testCreateLiteralLabelOnly() throws Exception { * . */ @Test - public final void testCreateLiteralLabelAndLanguage() throws Exception { + public final void testCreateLiteralLabelAndLanguage() { Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, LANG_EN, null, parserConfig, errListener, valueFactory); @@ -124,7 +122,7 @@ public final void testCreateLiteralLabelAndLanguage() throws Exception { * . */ @Test - public final void testCreateLiteralLabelAndDatatype() throws Exception { + public final void testCreateLiteralLabelAndDatatype() { Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, null, XSD.STRING, parserConfig, errListener, valueFactory); @@ -142,7 +140,7 @@ public final void testCreateLiteralLabelAndDatatype() throws Exception { * cases where {@link RDF#LANGSTRING} is given and there is a language. */ @Test - public final void testCreateLiteralLabelAndLanguageWithRDFLangString() throws Exception { + public final void testCreateLiteralLabelAndLanguageWithRDFLangString() { Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, LANG_EN, RDF.LANGSTRING, parserConfig, errListener, valueFactory); @@ -165,7 +163,7 @@ public final void testCreateLiteralLabelAndLanguageWithRDFLangString() throws Ex * and there is NO given language. */ @Test - public final void testCreateLiteralLabelNoLanguageWithRDFLangStringWithVerify() throws Exception { + public final void testCreateLiteralLabelNoLanguageWithRDFLangStringWithVerify() { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); assertThatThrownBy(() -> RDFParserHelper.createLiteral(LABEL_TESTA, null, RDF.LANGSTRING, parserConfig, @@ -174,7 +172,7 @@ public final void testCreateLiteralLabelNoLanguageWithRDFLangStringWithVerify() } @Test - public final void testCreateLiteralLabelNoLanguageWithRDFLangStringWithNoVerify() throws Exception { + public final void testCreateLiteralLabelNoLanguageWithRDFLangStringWithNoVerify() { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, false); Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, null, RDF.LANGSTRING, parserConfig, errListener, valueFactory); @@ -183,7 +181,7 @@ public final void testCreateLiteralLabelNoLanguageWithRDFLangStringWithNoVerify( } @Test - public final void testReportErrorStringFatalActive() throws Exception { + public final void testReportErrorStringFatalActive() { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); assertThatThrownBy( @@ -195,7 +193,7 @@ public final void testReportErrorStringFatalActive() throws Exception { } @Test - public final void testReportErrorStringNonFatalActive() throws Exception { + public final void testReportErrorStringNonFatalActive() { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); parserConfig.addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES); @@ -205,7 +203,7 @@ public final void testReportErrorStringNonFatalActive() throws Exception { } @Test - public final void testReportErrorStringFatalInactive() throws Exception { + public final void testReportErrorStringFatalInactive() { assertFalse(parserConfig.get(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES)); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, parserConfig, errListener); @@ -213,7 +211,7 @@ public final void testReportErrorStringFatalInactive() throws Exception { } @Test - public final void testReportErrorStringNonFatalInactive() throws Exception { + public final void testReportErrorStringNonFatalInactive() { assertFalse(parserConfig.get(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES)); parserConfig.addNonFatalError(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, @@ -222,7 +220,7 @@ public final void testReportErrorStringNonFatalInactive() throws Exception { } @Test - public final void testReportErrorStringIntIntFatalActive() throws Exception { + public final void testReportErrorStringIntIntFatalActive() { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); assertThatThrownBy( @@ -236,7 +234,7 @@ public final void testReportErrorStringIntIntFatalActive() throws Exception { } @Test - public final void testReportErrorStringIntIntNonFatalActive() throws Exception { + public final void testReportErrorStringIntIntNonFatalActive() { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); parserConfig.addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES); @@ -246,7 +244,7 @@ public final void testReportErrorStringIntIntNonFatalActive() throws Exception { } @Test - public final void testReportErrorStringIntIntFatalInactive() throws Exception { + public final void testReportErrorStringIntIntFatalInactive() { assertFalse(parserConfig.get(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES)); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, 1, 1, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, parserConfig, errListener); @@ -254,7 +252,7 @@ public final void testReportErrorStringIntIntFatalInactive() throws Exception { } @Test - public final void testReportErrorStringIntIntNonFatalInactive() throws Exception { + public final void testReportErrorStringIntIntNonFatalInactive() { assertFalse(parserConfig.get(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES)); parserConfig.addNonFatalError(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, 1, 1, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, @@ -269,7 +267,7 @@ public final void testReportErrorStringIntIntNonFatalInactive() throws Exception */ @Disabled @Test - public final void testReportErrorExceptionIntInt() throws Exception { + public final void testReportErrorExceptionIntInt() { fail("Not yet implemented"); // TODO } @@ -280,7 +278,7 @@ public final void testReportErrorExceptionIntInt() throws Exception { */ @Disabled @Test - public final void testReportFatalErrorString() throws Exception { + public final void testReportFatalErrorString() { fail("Not yet implemented"); // TODO } @@ -291,7 +289,7 @@ public final void testReportFatalErrorString() throws Exception { */ @Disabled @Test - public final void testReportFatalErrorStringIntInt() throws Exception { + public final void testReportFatalErrorStringIntInt() { fail("Not yet implemented"); // TODO } @@ -302,7 +300,7 @@ public final void testReportFatalErrorStringIntInt() throws Exception { */ @Disabled @Test - public final void testReportFatalErrorException() throws Exception { + public final void testReportFatalErrorException() { fail("Not yet implemented"); // TODO } @@ -313,7 +311,7 @@ public final void testReportFatalErrorException() throws Exception { */ @Disabled @Test - public final void testReportFatalErrorExceptionIntInt() throws Exception { + public final void testReportFatalErrorExceptionIntInt() { fail("Not yet implemented"); // TODO } diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/RioSettingTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/RioSettingTest.java index cc18f3a2f8b..510c64811f7 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/RioSettingTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/RioSettingTest.java @@ -29,22 +29,22 @@ public abstract class RioSettingTest { protected RioSetting subject; @BeforeEach - public void setUp() throws Exception { + public void setUp() { subject = createRioSetting(TEST_KEY, TEST_DESCRIPTION, getDefaultValue()); } @Test - public void testDefaultValue() throws Exception { + public void testDefaultValue() { assertThat(subject.getDefaultValue()).isEqualTo(getDefaultValue()); } @Test - public void testConvert() throws Exception { + public void testConvert() { assertThat(subject.convert(getLegalStringValue())).isEqualTo(getConvertedStringValue()); } @Test - public void testConvertIllegal() throws Exception { + public void testConvertIllegal() { assertThatThrownBy(() -> subject.convert(getIllegalStringValue())) .isInstanceOf(RioConfigurationException.class); } diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/StatementCollectorTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/StatementCollectorTest.java index 8068f1ed29b..9196a80a110 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/StatementCollectorTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/StatementCollectorTest.java @@ -35,24 +35,22 @@ public class StatementCollectorTest { /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } /** * Test method for {@link org.eclipse.rdf4j.rio.helpers.StatementCollector#StatementCollector()}. */ @Test - public final void testStatementCollector() throws Exception { + public final void testStatementCollector() { StatementCollector collector = new StatementCollector(); assertNotNull(collector.getStatements()); @@ -64,7 +62,7 @@ public final void testStatementCollector() throws Exception { * . */ @Test - public final void testStatementCollectorList() throws Exception { + public final void testStatementCollectorList() { List testList = new ArrayList<>(); StatementCollector collector = new StatementCollector(testList); @@ -79,7 +77,7 @@ public final void testStatementCollectorList() throws Exception { * . */ @Test - public final void testStatementCollectorSet() throws Exception { + public final void testStatementCollectorSet() { Set testList = new LinkedHashSet<>(); StatementCollector collector = new StatementCollector(testList); @@ -94,7 +92,7 @@ public final void testStatementCollectorSet() throws Exception { * . */ @Test - public final void testStatementCollectorCollectionModel() throws Exception { + public final void testStatementCollectorCollectionModel() { Model testList = new LinkedHashModel(); StatementCollector collector = new StatementCollector(testList); @@ -122,7 +120,7 @@ public final void testStatementCollectorCollectionModel() throws Exception { * . */ @Test - public final void testStatementCollectorCollectionModelMapIndependent() throws Exception { + public final void testStatementCollectorCollectionModelMapIndependent() { Model testList = new LinkedHashModel(); Map testNamespaces = new LinkedHashMap<>(); StatementCollector collector = new StatementCollector(testList, testNamespaces); @@ -140,7 +138,7 @@ public final void testStatementCollectorCollectionModelMapIndependent() throws E * . */ @Test - public final void testStatementCollectorCollectionMapModel() throws Exception { + public final void testStatementCollectorCollectionMapModel() { Collection testList = new LinkedHashModel(); Map testNamespaces = new LinkedHashMap<>(); StatementCollector collector = new StatementCollector(testList, testNamespaces); @@ -155,7 +153,7 @@ public final void testStatementCollectorCollectionMapModel() throws Exception { * Test method for {@link org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler#startRDF()}. */ @Test - public final void testStartRDF() throws Exception { + public final void testStartRDF() { StatementCollector testCollector = new StatementCollector(); testCollector.startRDF(); } @@ -164,7 +162,7 @@ public final void testStartRDF() throws Exception { * Test method for {@link org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler#endRDF()}. */ @Test - public final void testEndRDF() throws Exception { + public final void testEndRDF() { StatementCollector testCollector = new StatementCollector(); testCollector.startRDF(); testCollector.endRDF(); @@ -173,10 +171,9 @@ public final void testEndRDF() throws Exception { /** * Test method for {@link org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler#handleComment(java.lang.String)} . * - * @throws Exception */ @Test - public final void testHandleComment() throws Exception { + public final void testHandleComment() { StatementCollector testCollector = new StatementCollector(); // StatementCollector must be able to handle comments, but does not // preserve them diff --git a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/StringRioSettingTest.java b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/StringRioSettingTest.java index 23897ada686..66413135e1f 100644 --- a/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/StringRioSettingTest.java +++ b/core/rio/api/src/test/java/org/eclipse/rdf4j/rio/helpers/StringRioSettingTest.java @@ -19,7 +19,7 @@ public class StringRioSettingTest extends RioSettingTest { @Test @Override @Disabled - public void testConvertIllegal() throws Exception { + public void testConvertIllegal() { } @Override diff --git a/core/rio/binary/src/main/java/org/eclipse/rdf4j/rio/binary/BinaryRDFParser.java b/core/rio/binary/src/main/java/org/eclipse/rdf4j/rio/binary/BinaryRDFParser.java index 493da30669c..0a9556c2a9e 100644 --- a/core/rio/binary/src/main/java/org/eclipse/rdf4j/rio/binary/BinaryRDFParser.java +++ b/core/rio/binary/src/main/java/org/eclipse/rdf4j/rio/binary/BinaryRDFParser.java @@ -244,13 +244,13 @@ private Resource readBNode() throws IOException, RDFParseException { private Literal readPlainLiteral() throws IOException, RDFParseException { String label = readString(); - return createLiteral(label, null, null, -1, -1); + return createLiteral(label, null, ((IRI) null), -1, -1); } private Literal readLangLiteral() throws IOException, RDFParseException { String label = readString(); String language = readString(); - return createLiteral(label, language, null, -1, -1); + return createLiteral(label, language, ((IRI) null), -1, -1); } private Literal readDatatypeLiteral() throws IOException, RDFParseException { diff --git a/core/rio/binary/src/test/java/org/eclipse/rdf4j/rio/binary/BinaryRDFWriterBackgroundTest.java b/core/rio/binary/src/test/java/org/eclipse/rdf4j/rio/binary/BinaryRDFWriterBackgroundTest.java index 63691763cc0..9513cbec87e 100644 --- a/core/rio/binary/src/test/java/org/eclipse/rdf4j/rio/binary/BinaryRDFWriterBackgroundTest.java +++ b/core/rio/binary/src/test/java/org/eclipse/rdf4j/rio/binary/BinaryRDFWriterBackgroundTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.binary; -import java.io.IOException; import java.io.InputStream; import org.eclipse.rdf4j.model.Model; @@ -31,7 +30,7 @@ public BinaryRDFWriterBackgroundTest() { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); diff --git a/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/AbstractDatatypeHandlerTest.java b/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/AbstractDatatypeHandlerTest.java index 9f84c88b975..60829dfcc5f 100644 --- a/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/AbstractDatatypeHandlerTest.java +++ b/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/AbstractDatatypeHandlerTest.java @@ -88,13 +88,13 @@ public abstract class AbstractDatatypeHandlerTest { private ValueFactory vf; @BeforeEach - public void setUp() throws Exception { + public void setUp() { testHandler = getNewDatatypeHandler(); vf = getValueFactory(); } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { testHandler = null; vf = null; } @@ -103,7 +103,7 @@ public void tearDown() throws Exception { * Test method for {@link org.eclipse.rdf4j.rio.DatatypeHandler#isRecognizedDatatype(org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testIsRecognizedDatatypeNull() throws Exception { + public void testIsRecognizedDatatypeNull() { assertThatThrownBy(() -> testHandler.isRecognizedDatatype(null)) .isInstanceOf(NullPointerException.class); } @@ -112,7 +112,7 @@ public void testIsRecognizedDatatypeNull() throws Exception { * Test method for {@link org.eclipse.rdf4j.rio.DatatypeHandler#isRecognizedDatatype(org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testIsRecognizedDatatypeTrue() throws Exception { + public void testIsRecognizedDatatypeTrue() { assertTrue(testHandler.isRecognizedDatatype(getRecognisedDatatypeUri())); } @@ -120,7 +120,7 @@ public void testIsRecognizedDatatypeTrue() throws Exception { * Test method for {@link org.eclipse.rdf4j.rio.DatatypeHandler#isRecognizedDatatype(org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testIsRecognizedDatatypeFalse() throws Exception { + public void testIsRecognizedDatatypeFalse() { assertFalse(testHandler.isRecognizedDatatype(getUnrecognisedDatatypeUri())); } @@ -129,7 +129,7 @@ public void testIsRecognizedDatatypeFalse() throws Exception { * {@link org.eclipse.rdf4j.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testVerifyDatatypeNullDatatypeUri() throws Exception { + public void testVerifyDatatypeNullDatatypeUri() { assertThatThrownBy(() -> testHandler.verifyDatatype(getValueMatchingRecognisedDatatypeUri(), null)) .isInstanceOf(NullPointerException.class); } @@ -139,7 +139,7 @@ public void testVerifyDatatypeNullDatatypeUri() throws Exception { * {@link org.eclipse.rdf4j.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testVerifyDatatypeNullValueRecognised() throws Exception { + public void testVerifyDatatypeNullValueRecognised() { assertThatThrownBy(() -> testHandler.verifyDatatype(null, getRecognisedDatatypeUri())) .isInstanceOf(NullPointerException.class); } @@ -149,7 +149,7 @@ public void testVerifyDatatypeNullValueRecognised() throws Exception { * {@link org.eclipse.rdf4j.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testVerifyDatatypeNullValueUnrecognised() throws Exception { + public void testVerifyDatatypeNullValueUnrecognised() { assertThatThrownBy(() -> testHandler.verifyDatatype(null, getUnrecognisedDatatypeUri())) .isInstanceOf(LiteralUtilException.class); } @@ -159,7 +159,7 @@ public void testVerifyDatatypeNullValueUnrecognised() throws Exception { * {@link org.eclipse.rdf4j.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testVerifyDatatypeUnrecognisedDatatypeUri() throws Exception { + public void testVerifyDatatypeUnrecognisedDatatypeUri() { assertThatThrownBy( () -> testHandler.verifyDatatype(getValueMatchingRecognisedDatatypeUri(), getUnrecognisedDatatypeUri())) .isInstanceOf(LiteralUtilException.class); @@ -170,7 +170,7 @@ public void testVerifyDatatypeUnrecognisedDatatypeUri() throws Exception { * {@link org.eclipse.rdf4j.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testVerifyDatatypeInvalidValue() throws Exception { + public void testVerifyDatatypeInvalidValue() { assertFalse(testHandler.verifyDatatype(getValueNotMatchingRecognisedDatatypeUri(), getRecognisedDatatypeUri())); } @@ -179,7 +179,7 @@ public void testVerifyDatatypeInvalidValue() throws Exception { * {@link org.eclipse.rdf4j.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.eclipse.rdf4j.model.IRI)} . */ @Test - public void testVerifyDatatypeValidValue() throws Exception { + public void testVerifyDatatypeValidValue() { assertTrue(testHandler.verifyDatatype(getValueMatchingRecognisedDatatypeUri(), getRecognisedDatatypeUri())); } @@ -189,7 +189,7 @@ public void testVerifyDatatypeValidValue() throws Exception { * . */ @Test - public void testNormalizeDatatypeNullDatatypeUri() throws Exception { + public void testNormalizeDatatypeNullDatatypeUri() { assertThatThrownBy(() -> testHandler.normalizeDatatype(getValueMatchingRecognisedDatatypeUri(), null, vf)) .isInstanceOf(NullPointerException.class); } @@ -200,7 +200,7 @@ public void testNormalizeDatatypeNullDatatypeUri() throws Exception { * . */ @Test - public void testNormalizeDatatypeNullValue() throws Exception { + public void testNormalizeDatatypeNullValue() { assertThatThrownBy(() -> testHandler.normalizeDatatype(null, getRecognisedDatatypeUri(), vf)) .isInstanceOf(NullPointerException.class); } @@ -211,7 +211,7 @@ public void testNormalizeDatatypeNullValue() throws Exception { * . */ @Test - public void testNormalizeDatatypeUnrecognisedDatatypeUri() throws Exception { + public void testNormalizeDatatypeUnrecognisedDatatypeUri() { assertThatThrownBy(() -> testHandler.normalizeDatatype(getValueMatchingRecognisedDatatypeUri(), getUnrecognisedDatatypeUri(), vf)) .isInstanceOf(LiteralUtilException.class); @@ -223,7 +223,7 @@ public void testNormalizeDatatypeUnrecognisedDatatypeUri() throws Exception { * . */ @Test - public void testNormalizeDatatypeInvalidValue() throws Exception { + public void testNormalizeDatatypeInvalidValue() { assertThatThrownBy(() -> testHandler.normalizeDatatype(getValueNotMatchingRecognisedDatatypeUri(), getRecognisedDatatypeUri(), vf)) .isInstanceOf(LiteralUtilException.class); @@ -235,7 +235,7 @@ public void testNormalizeDatatypeInvalidValue() throws Exception { * . */ @Test - public void testNormalizeDatatypeValidValue() throws Exception { + public void testNormalizeDatatypeValidValue() { Literal result = testHandler.normalizeDatatype(getValueMatchingRecognisedDatatypeUri(), getRecognisedDatatypeUri(), vf); Literal expectedResult = getNormalisedLiteralForRecognisedDatatypeAndValue(); @@ -253,7 +253,7 @@ public void testNormalizeDatatypeValidValue() throws Exception { * Test method for {@link org.eclipse.rdf4j.rio.DatatypeHandler#getKey()}. */ @Test - public void testGetKey() throws Exception { + public void testGetKey() { String result = testHandler.getKey(); String expectedResult = getExpectedKey(); diff --git a/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/DBPediaCelsiusDatatypeHandlerTest.java b/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/DBPediaCelsiusDatatypeHandlerTest.java index 324f21422fb..1154b49fd4e 100644 --- a/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/DBPediaCelsiusDatatypeHandlerTest.java +++ b/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/DBPediaCelsiusDatatypeHandlerTest.java @@ -29,13 +29,13 @@ public class DBPediaCelsiusDatatypeHandlerTest extends AbstractDatatypeHandlerTe @Disabled("DBPedia datatypes are not currently verified") @Test @Override - public void testVerifyDatatypeInvalidValue() throws Exception { + public void testVerifyDatatypeInvalidValue() { } @Disabled("DBPedia datatypes are not currently normalised") @Test @Override - public void testNormalizeDatatypeInvalidValue() throws Exception { + public void testNormalizeDatatypeInvalidValue() { } // ------------------------------------- diff --git a/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/RDFLangStringDatatypeHandlerTest.java b/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/RDFLangStringDatatypeHandlerTest.java index 1e149463ab4..b6f327e308f 100644 --- a/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/RDFLangStringDatatypeHandlerTest.java +++ b/core/rio/datatypes/src/test/java/org/eclipse/rdf4j/rio/datatypes/RDFLangStringDatatypeHandlerTest.java @@ -30,19 +30,19 @@ public class RDFLangStringDatatypeHandlerTest extends AbstractDatatypeHandlerTes @Disabled("There are no invalid values for RDF LangString other than null, which is tested seperately") @Test @Override - public void testVerifyDatatypeInvalidValue() throws Exception { + public void testVerifyDatatypeInvalidValue() { } @Disabled("There are no invalid values for RDF LangString other than null, which is tested seperately") @Test @Override - public void testNormalizeDatatypeInvalidValue() throws Exception { + public void testNormalizeDatatypeInvalidValue() { } @Disabled("This test relies on a null language, which is not allowed for RDF.LANGSTRING") @Test @Override - public void testNormalizeDatatypeValidValue() throws Exception { + public void testNormalizeDatatypeValidValue() { } // ------------------------------------- diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/CRC32.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/CRC32.java index 4223303386b..206edcc16f6 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/CRC32.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/CRC32.java @@ -82,6 +82,6 @@ public long getValue() { @Override public void reset() { - value = 0xFFFFFFFF; + value = 0; } } diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArray.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArray.java index 0e9908d225c..42c84866f50 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArray.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArray.java @@ -35,7 +35,7 @@ * @author Bart Hanssens */ abstract class HDTArray extends HDTPart { - protected enum Type { + enum Type { LOG64(1), UINT32(2), UINT64(3); @@ -47,7 +47,7 @@ protected enum Type { * * @return value 1,2 or 3 */ - public int getValue() { + int getValue() { return value; } @@ -56,22 +56,22 @@ public int getValue() { } } - protected int nrbits; - protected int entries; + int nrbits; + int entries; /** * Get the type of the array * * @return byte */ - protected abstract int getType(); + abstract int getType(); /** * Get number of bits used to encode an entry * * @return positive integer value */ - protected int getNrBits() { + int getNrBits() { return nrbits; } @@ -80,7 +80,7 @@ protected int getNrBits() { * * @return positive integer value */ - protected int size() { + int size() { return entries; } @@ -90,10 +90,10 @@ protected int size() { * @param i zero-based index * @return entry */ - protected abstract int get(int i); + abstract int get(int i); @Override - protected void parse(InputStream is) throws IOException { + void parse(InputStream is) throws IOException { CRC8 crc8 = new CRC8(); crc8.update(getType()); diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayFactory.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayFactory.java index 5f1b24177f9..3e222c617e5 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayFactory.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayFactory.java @@ -20,7 +20,7 @@ */ class HDTArrayFactory { - protected static HDTArray parse(InputStream is) throws IOException { + static HDTArray parse(InputStream is) throws IOException { int dtype = is.read(); if (dtype != HDTArray.Type.LOG64.getValue()) { throw new UnsupportedOperationException("Array section: encoding " + Long.toHexString(dtype) + diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayLog64.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayLog64.java index b6ef0c9e582..d3c084271b1 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayLog64.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTArrayLog64.java @@ -34,15 +34,15 @@ * @author Bart Hanssens */ class HDTArrayLog64 extends HDTArray { - private byte buffer[]; + private byte[] buffer; @Override - protected int getType() { + int getType() { return HDTArray.Type.LOG64.getValue(); } @Override - protected int get(int i) { + int get(int i) { // start byte of the value, and start bit in that start byte int bytePos = (i * nrbits) / 8; int bitPos = (i * nrbits) % 8; @@ -63,14 +63,14 @@ protected int get(int i) { } @Override - protected void parse(InputStream is) throws IOException { + void parse(InputStream is) throws IOException { super.parse(is); // don't close CheckedInputStream, as it will close the underlying inputstream try (UncloseableInputStream uis = new UncloseableInputStream(is); CheckedInputStream cis = new CheckedInputStream(uis, new CRC32())) { // read bytes, minimum 1 - long bytes = (nrbits * entries + 7) / 8; + long bytes = ((long) nrbits * entries + 7) / 8; if (bytes > Integer.MAX_VALUE) { throw new UnsupportedOperationException("Maximum number of bytes in array exceeded: " + bytes); } diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTBitmap.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTBitmap.java index ac60ac9e8c7..30bfc002709 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTBitmap.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTBitmap.java @@ -62,7 +62,7 @@ protected void parse(InputStream is) throws IOException { ", but only bitmap v1 is supported"); } - long b = (int) VByte.decode(cis); + long b = VByte.decode(cis); if (b > Integer.MAX_VALUE) { throw new UnsupportedOperationException("Maximum number of entries in bitmap exceeded: " + b); } diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionary.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionary.java index 8e904c3fccc..4a2bff3b557 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionary.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionary.java @@ -36,13 +36,13 @@ * @author Bart Hanssens */ class HDTDictionary extends HDTPart { - protected final static byte[] DICT_FORMAT = "" + final static byte[] DICT_FORMAT = "" .getBytes(StandardCharsets.US_ASCII); - protected final static String DICT_MAPPING = "mapping"; - protected final static String DICT_ELEMENTS = "elements"; + final static String DICT_MAPPING = "mapping"; + final static String DICT_ELEMENTS = "elements"; @Override - protected void parse(InputStream is) throws IOException { + void parse(InputStream is) throws IOException { // don't close CheckedInputStream, as it will close the underlying inputstream try (UncloseableInputStream uis = new UncloseableInputStream(is); CheckedInputStream cis = new CheckedInputStream(uis, new CRC16())) { diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySection.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySection.java index aef6e771a5d..cca1f79b9b4 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySection.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySection.java @@ -18,7 +18,7 @@ * @author Bart Hanssens */ abstract class HDTDictionarySection extends HDTPart { - protected enum Type { + enum Type { PLAIN(1), FRONT(2), HTFC(3), @@ -28,7 +28,7 @@ protected enum Type { private final int value; - protected int getValue() { + int getValue() { return value; } @@ -42,7 +42,7 @@ protected int getValue() { * * @return */ - protected abstract int size(); + abstract int size(); /** * Get the entry @@ -50,7 +50,7 @@ protected int getValue() { * @param i zero-based index * @return */ - protected abstract byte[] get(int i) throws IOException; + abstract byte[] get(int i) throws IOException; /** * Constructor @@ -58,7 +58,7 @@ protected int getValue() { * @param pos position * @param name name */ - protected HDTDictionarySection(String name, long pos) { + HDTDictionarySection(String name, long pos) { super(name, pos); } } diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySectionFactory.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySectionFactory.java index dd3387f80b2..293a664a1a4 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySectionFactory.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySectionFactory.java @@ -28,7 +28,7 @@ class HDTDictionarySectionFactory { * @return dictionary section * @throws IOException */ - protected static HDTDictionarySection parse(InputStream is, String name, long pos) throws IOException { + static HDTDictionarySection parse(InputStream is, String name, long pos) throws IOException { int dtype = is.read(); if (dtype != HDTDictionarySection.Type.FRONT.getValue()) { throw new UnsupportedOperationException("Dictionary " + name + ": encoding " diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySectionPFC.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySectionPFC.java index 50add6ab32a..625238881b9 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySectionPFC.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTDictionarySectionPFC.java @@ -74,17 +74,17 @@ protected boolean removeEldestEntry(Map.Entry eldest) { * @param name * @param pos */ - protected HDTDictionarySectionPFC(String name, long pos) { + HDTDictionarySectionPFC(String name, long pos) { super(name, pos); } @Override - protected int size() { + int size() { return totalStrings; } @Override - protected byte[] get(int i) throws IOException { + byte[] get(int i) throws IOException { // HDT index start counting from 1 int idx = i - 1; @@ -101,7 +101,7 @@ protected byte[] get(int i) throws IOException { } @Override - protected void parse(InputStream is) throws IOException { + void parse(InputStream is) throws IOException { CRC8 crc8 = new CRC8(); crc8.update((byte) HDTDictionarySection.Type.FRONT.getValue()); @@ -112,7 +112,7 @@ protected void parse(InputStream is) throws IOException { CheckedInputStream cis = new CheckedInputStream(uis, crc8)) { long val = VByte.decode(cis); - if (totalStrings > Integer.MAX_VALUE) { + if (val > Integer.MAX_VALUE) { throw new UnsupportedOperationException(getDebugPartStr() + " max number of strings exceeded: " + val); } totalStrings = (int) val; diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTGlobal.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTGlobal.java index 1fe16ca97e7..e9fad13c036 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTGlobal.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTGlobal.java @@ -38,12 +38,12 @@ * @author Bart Hanssens */ class HDTGlobal extends HDTPart { - protected final static byte[] GLOBAL_FORMAT = "".getBytes(StandardCharsets.US_ASCII); - protected final static String GLOBAL_BASEURI = "BaseUri"; - protected final static String GLOBAL_SOFTWARE = "Software"; + final static byte[] GLOBAL_FORMAT = "".getBytes(StandardCharsets.US_ASCII); + final static String GLOBAL_BASEURI = "BaseUri"; + final static String GLOBAL_SOFTWARE = "Software"; @Override - protected void parse(InputStream is) throws IOException { + void parse(InputStream is) throws IOException { // don't close CheckedInputStream, as it will close the underlying inputstream try (UncloseableInputStream uis = new UncloseableInputStream(is); CheckedInputStream cis = new CheckedInputStream(uis, new CRC16())) { diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTHeader.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTHeader.java index 00fc2221542..0c098087399 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTHeader.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTHeader.java @@ -37,13 +37,13 @@ */ class HDTHeader extends HDTPart { - protected final static byte[] HEADER_FORMAT = "ntriples".getBytes(StandardCharsets.US_ASCII); - protected final static String HEADER_LENGTH = "length"; + final static byte[] HEADER_FORMAT = "ntriples".getBytes(StandardCharsets.US_ASCII); + final static String HEADER_LENGTH = "length"; private byte[] headerData; @Override - protected void parse(InputStream is) throws IOException { + void parse(InputStream is) throws IOException { // don't close CheckedInputStream, as it will close the underlying inputstream try (UncloseableInputStream uis = new UncloseableInputStream(is); CheckedInputStream cis = new CheckedInputStream(uis, new CRC16())) { @@ -63,7 +63,7 @@ protected void parse(InputStream is) throws IOException { * * @return byte array */ - protected byte[] getHeaderData() { + byte[] getHeaderData() { return headerData; } @@ -75,7 +75,7 @@ protected byte[] getHeaderData() { * @throws IOException */ private byte[] parseHeaderData(InputStream is, int len) throws IOException { - byte b[] = new byte[len]; + byte[] b = new byte[len]; is.read(b); return b; } diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTParser.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTParser.java index e00e0a0cc8f..7c54643a52c 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTParser.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTParser.java @@ -10,13 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.hdt; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.Collection; -import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -88,8 +86,7 @@ public RDFFormat getRDFFormat() { @Override public Collection> getSupportedSettings() { - Set> result = new HashSet<>(); - return result; + return Set.of(); } @Override @@ -99,9 +96,9 @@ public synchronized void parse(InputStream in, String baseURI) throw new IllegalArgumentException("Input stream must not be 'null'"); } - if (in instanceof FileInputStream) { - // "TODO: use more optimized way to parse the file, eg. filechannel / membuffer" - } +// if (in instanceof FileInputStream) { +// TODO: use more optimized way to parse the file, eg. filechannel / membuffer +// } HDTDictionarySection shared = null; HDTDictionarySection subjects = null; @@ -165,9 +162,10 @@ public synchronized void parse(InputStream in, String baseURI) rdfHandler.startRDF(); } - int cnt = 0; + assert shared != null; int size = shared.size(); + assert section != null; while (section.hasNext()) { int[] t = section.next(); byte[] s = getSO(t[0], size, shared, subjects); @@ -190,7 +188,7 @@ public synchronized void parse(InputStream in, String baseURI) */ @Override public synchronized void parse(Reader reader, String baseURI) - throws IOException, RDFParseException, RDFHandlerException { + throws RDFParseException, RDFHandlerException { throw new UnsupportedOperationException("HDT is binary, text readers not supported."); } diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTPart.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTPart.java index c9d9f8c1f54..dc6b3e3a850 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTPart.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTPart.java @@ -34,7 +34,7 @@ * @author Bart Hanssens */ abstract class HDTPart { - protected enum Type { + enum Type { GLOBAL((byte) 1), HEADER((byte) 2), DICTIONARY((byte) 3), @@ -47,7 +47,7 @@ protected enum Type { * * @return value 1,2 or 3 */ - protected byte getValue() { + byte getValue() { return value; } @@ -56,14 +56,14 @@ protected byte getValue() { } } - protected final static byte[] COOKIE = "$HDT".getBytes(StandardCharsets.US_ASCII); + final static byte[] COOKIE = "$HDT".getBytes(StandardCharsets.US_ASCII); // TODO: make configurable, buffer for reading object values private final static int BUFLEN = 1 * 1024 * 1024; // for debugging purposes - protected final String name; - protected final long pos; - protected Map properties; + final String name; + final long pos; + Map properties; /** * Parse from input stream @@ -71,14 +71,14 @@ protected byte getValue() { * @param is * @throws IOException */ - protected abstract void parse(InputStream is) throws IOException; + abstract void parse(InputStream is) throws IOException; /** * Get properties, if any. * * @return key, value map */ - protected Map getProperties() { + Map getProperties() { return properties; } @@ -88,7 +88,7 @@ protected Map getProperties() { * @param name part name * @param pos starting position in input stream */ - protected HDTPart(String name, long pos) { + HDTPart(String name, long pos) { this.name = name; this.pos = pos; } @@ -96,7 +96,7 @@ protected HDTPart(String name, long pos) { /** * Constructor */ - protected HDTPart() { + HDTPart() { this("", -1); } @@ -105,7 +105,7 @@ protected HDTPart() { * * @return string */ - protected String getDebugPartStr() { + String getDebugPartStr() { if (name == null || name.isEmpty()) { return ""; } @@ -119,7 +119,7 @@ protected String getDebugPartStr() { * @param ctype control type * @throws IOException */ - protected static void checkControl(InputStream is, HDTPart.Type ctype) throws IOException { + static void checkControl(InputStream is, HDTPart.Type ctype) throws IOException { byte[] cookie = new byte[COOKIE.length]; is.read(cookie); if (!Arrays.equals(cookie, COOKIE)) { @@ -139,7 +139,7 @@ protected static void checkControl(InputStream is, HDTPart.Type ctype) throws IO * @param format * @throws IOException */ - protected static void checkFormat(InputStream is, byte[] format) throws IOException { + static void checkFormat(InputStream is, byte[] format) throws IOException { byte[] b = new byte[format.length]; is.read(b); if (!Arrays.equals(b, format)) { @@ -155,7 +155,7 @@ protected static void checkFormat(InputStream is, byte[] format) throws IOExcept * @return * @throws IOException */ - protected static byte[] readToNull(InputStream is) throws IOException { + static byte[] readToNull(InputStream is) throws IOException { byte[] buf = new byte[BUFLEN]; int len = 0; @@ -176,7 +176,7 @@ protected static byte[] readToNull(InputStream is) throws IOException { * @param start position to start from * @return position of first NULL byte */ - protected static int countToNull(byte[] b, int start) throws IOException { + static int countToNull(byte[] b, int start) throws IOException { for (int i = start; i < b.length; i++) { if (b[i] == 0b00) { return i; @@ -193,7 +193,7 @@ protected static int countToNull(byte[] b, int start) throws IOException { * @return key, value map * @throws IOException */ - protected static Map getProperties(InputStream is) throws IOException { + static Map getProperties(InputStream is) throws IOException { return mapProperties(readToNull(is)); } @@ -203,15 +203,15 @@ protected static Map getProperties(InputStream is) throws IOExce * @param props * @return */ - protected static Map mapProperties(byte[] props) { + static Map mapProperties(byte[] props) { Map map = new HashMap<>(); if (props == null || props.length == 0) { return map; } - String strs[] = new String(props, 0, props.length, StandardCharsets.US_ASCII).split(";"); - for (String str : strs) { - String prop[] = str.split("="); + String[] strings = new String(props, StandardCharsets.US_ASCII).split(";"); + for (String string : strings) { + String[] prop = string.split("="); if (prop.length == 2) { map.put(prop[0], prop[1]); } @@ -229,7 +229,7 @@ protected static Map mapProperties(byte[] props) { * @return positive integer * @throws IOException */ - protected int getIntegerProperty(Map props, String prop, String name) throws IOException { + int getIntegerProperty(Map props, String prop, String name) throws IOException { int len; String str = props.getOrDefault(prop, "0"); @@ -252,7 +252,7 @@ protected int getIntegerProperty(Map props, String prop, String * @param len number of bytes of the checksum * @throws IOException */ - protected static void checkCRC(CheckedInputStream cis, InputStream is, int len) throws IOException { + static void checkCRC(CheckedInputStream cis, InputStream is, int len) throws IOException { long calc = cis.getChecksum().getValue(); byte[] checksum = new byte[len]; diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriples.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriples.java index ec166aa7593..f18302bf008 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriples.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriples.java @@ -38,7 +38,7 @@ * @author Bart Hanssens */ class HDTTriples extends HDTPart { - protected enum Order { + enum Order { UNKNOWN(0), SPO(1), SOP(2), @@ -49,7 +49,7 @@ protected enum Order { private final int value; - protected int getValue() { + int getValue() { return value; } @@ -63,12 +63,12 @@ protected int getValue() { } } - protected final static byte[] FORMAT_LIST = "" + final static byte[] FORMAT_LIST = "" .getBytes(StandardCharsets.US_ASCII); - protected final static byte[] FORMAT_BITMAP = "" + final static byte[] FORMAT_BITMAP = "" .getBytes(StandardCharsets.US_ASCII); - protected final static String ORDER = "order"; - protected final static String NUM = "numTriples"; + final static String ORDER = "order"; + final static String NUM = "numTriples"; private Order order; private int nrtriples; @@ -78,12 +78,12 @@ protected int getValue() { * * @return enum */ - protected Order getOrder() { + Order getOrder() { return order; } @Override - protected void parse(InputStream is) throws IOException { + void parse(InputStream is) throws IOException { // don't close CheckedInputStream, as it will close the underlying inputstream try (UncloseableInputStream uis = new UncloseableInputStream(is); CheckedInputStream cis = new CheckedInputStream(uis, new CRC16())) { diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSection.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSection.java index d3d66a9fc33..baf6055e387 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSection.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSection.java @@ -27,5 +27,5 @@ abstract class HDTTriplesSection extends HDTPart implements Iterator { * @param order * @throws IOException */ - protected abstract void parse(InputStream is, HDTTriples.Order order) throws IOException; + abstract void parse(InputStream is, HDTTriples.Order order) throws IOException; } diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSectionBitmap.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSectionBitmap.java index 3e94463187c..fe9fd93866d 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSectionBitmap.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSectionBitmap.java @@ -79,12 +79,12 @@ public int[] next() { } @Override - protected void parse(InputStream is) throws IOException { + void parse(InputStream is) throws IOException { parse(is, HDTTriples.Order.SPO); } @Override - protected void parse(InputStream is, HDTTriples.Order order) throws IOException { + void parse(InputStream is, HDTTriples.Order order) throws IOException { bitmapY = new HDTBitmap(); bitmapY.parse(is); sizeY = bitmapY.size(); diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSectionFactory.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSectionFactory.java index b35f237dbf7..0d1b357d5d7 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSectionFactory.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/HDTTriplesSectionFactory.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.hdt; -import java.io.IOException; - /** * HDT Array factory. * @@ -19,7 +17,7 @@ */ class HDTTriplesSectionFactory { - protected static HDTTriplesSection parse(String str) throws IOException { + static HDTTriplesSection parse(String str) { if (!str.equals(new String(HDTTriples.FORMAT_BITMAP))) { throw new UnsupportedOperationException( "Triples section: " + str + ", but only bitmap encoding is supported"); diff --git a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/VByte.java b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/VByte.java index 0afa56534ff..1879c23aa3a 100644 --- a/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/VByte.java +++ b/core/rio/hdt/src/main/java/org/eclipse/rdf4j/rio/hdt/VByte.java @@ -72,7 +72,7 @@ public static long decode(InputStream is) throws IOException { int i = 0; do { buffer[i] = (byte) is.read(); - } while (i < buffer.length && hasNext(buffer[i++])); + } while (i + 1 < buffer.length && hasNext(buffer[i++])); return decode(buffer, i); } @@ -82,15 +82,14 @@ public static long decode(InputStream is) throws IOException { * @param b byte array * @param start starting position * @return decode value - * @throws IOException */ - public static long decodeFrom(byte[] b, int start) throws IOException { + public static long decodeFrom(byte[] b, int start) { byte[] buffer = new byte[8]; int i = 0; do { buffer[i] = b[start + i]; - } while (i < buffer.length && hasNext(buffer[i++])); + } while (i + 1 < buffer.length && hasNext(buffer[i++])); return decode(buffer, i); } diff --git a/core/rio/hdt/src/test/java/org/eclipse/rdf4j/rio/hdt/HDTParserTest.java b/core/rio/hdt/src/test/java/org/eclipse/rdf4j/rio/hdt/HDTParserTest.java index 6d2eaa6f2e2..8b27ad124b8 100644 --- a/core/rio/hdt/src/test/java/org/eclipse/rdf4j/rio/hdt/HDTParserTest.java +++ b/core/rio/hdt/src/test/java/org/eclipse/rdf4j/rio/hdt/HDTParserTest.java @@ -31,7 +31,7 @@ public class HDTParserTest { private RDFParser parser; @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = Rio.createParser(RDFFormat.HDT); parser.setParseLocationListener((line, col) -> System.err.println("byte " + line)); } diff --git a/core/rio/hdt/src/test/java/org/eclipse/rdf4j/rio/hdt/VByteTest.java b/core/rio/hdt/src/test/java/org/eclipse/rdf4j/rio/hdt/VByteTest.java index 8f70e8da175..b57f691cd84 100644 --- a/core/rio/hdt/src/test/java/org/eclipse/rdf4j/rio/hdt/VByteTest.java +++ b/core/rio/hdt/src/test/java/org/eclipse/rdf4j/rio/hdt/VByteTest.java @@ -34,7 +34,7 @@ public void test128() { @Test public void test128Input() { - byte b[] = new byte[] { (byte) 0x00, (byte) 0x81 }; + byte[] b = new byte[] { (byte) 0x00, (byte) 0x81 }; try (ByteArrayInputStream bis = new ByteArrayInputStream(b)) { assertEquals(128, VByte.decode(bis), "128 not correctly decoded"); diff --git a/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDParserCustomTest.java b/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDParserCustomTest.java index 6d89a17796c..42c4263a20e 100644 --- a/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDParserCustomTest.java +++ b/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDParserCustomTest.java @@ -124,7 +124,7 @@ public class JSONLDParserCustomTest { private final Literal testObjectLiteralUnquotedControlChar = F.createLiteral("42\u0009", XSD.STRING); @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = Rio.createParser(RDFFormat.JSONLD); errors = new ParseErrorCollector(); model = new LinkedHashModel(); @@ -132,7 +132,7 @@ public void setUp() throws Exception { parser.setRDFHandler(new ContextStatementCollector(model, F)); } - private void verifyParseResults(Resource nextSubject, IRI nextPredicate, Value nextObject) throws Exception { + private void verifyParseResults(Resource nextSubject, IRI nextPredicate, Value nextObject) { assertEquals(0, errors.getWarnings().size()); assertEquals(0, errors.getErrors().size()); assertEquals(0, errors.getFatalErrors().size()); @@ -143,13 +143,13 @@ private void verifyParseResults(Resource nextSubject, IRI nextPredicate, Value n } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { // 13 supported in JSONLDParser + 12 from AbstractRDFParser assertEquals(25, parser.getSupportedSettings().size()); } @Test - public void testAllowBackslashEscapingAnyCharacterDefault() throws Exception { + public void testAllowBackslashEscapingAnyCharacterDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(BACKSLASH_ESCAPED_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -163,7 +163,7 @@ public void testAllowBackslashEscapingAnyCharacterEnabled() throws Exception { } @Test - public void testAllowBackslashEscapingAnyCharacterDisabled() throws Exception { + public void testAllowBackslashEscapingAnyCharacterDisabled() { parser.set(JSONSettings.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, false); assertThatThrownBy(() -> parser.parse(new StringReader(BACKSLASH_ESCAPED_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -172,7 +172,7 @@ public void testAllowBackslashEscapingAnyCharacterDisabled() throws Exception { } @Test - public void testAllowCommentsDefault() throws Exception { + public void testAllowCommentsDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(COMMENTS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -186,7 +186,7 @@ public void testAllowCommentsEnabled() throws Exception { } @Test - public void testAllowCommentsDisabled() throws Exception { + public void testAllowCommentsDisabled() { parser.set(JSONSettings.ALLOW_COMMENTS, false); assertThatThrownBy(() -> parser.parse(new StringReader(COMMENTS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -194,7 +194,7 @@ public void testAllowCommentsDisabled() throws Exception { } @Test - public void testAllowNonNumericNumbersDefault() throws Exception { + public void testAllowNonNumericNumbersDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(NON_NUMERIC_NUMBERS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -211,7 +211,7 @@ public void testAllowNonNumericNumbersEnabled() throws Exception { } @Test - public void testAllowNonNumericNumbersDisabled() throws Exception { + public void testAllowNonNumericNumbersDisabled() { parser.set(JSONSettings.ALLOW_NON_NUMERIC_NUMBERS, false); assertThatThrownBy(() -> parser.parse(new StringReader(NON_NUMERIC_NUMBERS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -219,7 +219,7 @@ public void testAllowNonNumericNumbersDisabled() throws Exception { } @Test - public void testAllowNumericLeadingZeroesDefault() throws Exception { + public void testAllowNumericLeadingZeroesDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(NUMERIC_LEADING_ZEROES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -233,7 +233,7 @@ public void testAllowNumericLeadingZeroesEnabled() throws Exception { } @Test - public void testAllowNumericLeadingZeroesDisabled() throws Exception { + public void testAllowNumericLeadingZeroesDisabled() { parser.set(JSONSettings.ALLOW_NUMERIC_LEADING_ZEROS, false); assertThatThrownBy(() -> parser.parse(new StringReader(NUMERIC_LEADING_ZEROES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -241,7 +241,7 @@ public void testAllowNumericLeadingZeroesDisabled() throws Exception { } @Test - public void testAllowSingleQuotesDefault() throws Exception { + public void testAllowSingleQuotesDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(SINGLE_QUOTES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -255,7 +255,7 @@ public void testAllowSingleQuotesEnabled() throws Exception { } @Test - public void testAllowSingleQuotesDisabled() throws Exception { + public void testAllowSingleQuotesDisabled() { parser.set(JSONSettings.ALLOW_SINGLE_QUOTES, false); assertThatThrownBy(() -> parser.parse(new StringReader(SINGLE_QUOTES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -263,7 +263,7 @@ public void testAllowSingleQuotesDisabled() throws Exception { } @Test - public void testAllowUnquotedControlCharactersDefault() throws Exception { + public void testAllowUnquotedControlCharactersDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(UNQUOTED_CONTROL_CHARS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -277,7 +277,7 @@ public void testAllowUnquotedControlCharactersEnabled() throws Exception { } @Test - public void testAllowUnquotedControlCharactersDisabled() throws Exception { + public void testAllowUnquotedControlCharactersDisabled() { parser.set(JSONSettings.ALLOW_UNQUOTED_CONTROL_CHARS, false); assertThatThrownBy(() -> parser.parse(new StringReader(UNQUOTED_CONTROL_CHARS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -285,7 +285,7 @@ public void testAllowUnquotedControlCharactersDisabled() throws Exception { } @Test - public void testAllowUnquotedFieldNamesDefault() throws Exception { + public void testAllowUnquotedFieldNamesDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(UNQUOTED_FIELD_NAMES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -299,7 +299,7 @@ public void testAllowUnquotedFieldNamesEnabled() throws Exception { } @Test - public void testAllowUnquotedFieldNamesDisabled() throws Exception { + public void testAllowUnquotedFieldNamesDisabled() { parser.set(JSONSettings.ALLOW_UNQUOTED_FIELD_NAMES, false); assertThatThrownBy(() -> parser.parse(new StringReader(UNQUOTED_FIELD_NAMES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -307,7 +307,7 @@ public void testAllowUnquotedFieldNamesDisabled() throws Exception { } @Test - public void testAllowYamlCommentsDefault() throws Exception { + public void testAllowYamlCommentsDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(YAML_COMMENTS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -321,7 +321,7 @@ public void testAllowYamlCommentsEnabled() throws Exception { } @Test - public void testAllowYamlCommentsDisabled() throws Exception { + public void testAllowYamlCommentsDisabled() { parser.set(JSONSettings.ALLOW_YAML_COMMENTS, false); assertThatThrownBy(() -> parser.parse(new StringReader(YAML_COMMENTS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -329,7 +329,7 @@ public void testAllowYamlCommentsDisabled() throws Exception { } @Test - public void testAllowTrailingCommaDefault() throws Exception { + public void testAllowTrailingCommaDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(TRAILING_COMMA_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessageContaining("Could not parse JSONLD"); @@ -343,7 +343,7 @@ public void testAllowTrailingCommaEnabled() throws Exception { } @Test - public void testAllowTrailingCommaDisabled() throws Exception { + public void testAllowTrailingCommaDisabled() { parser.set(JSONSettings.ALLOW_TRAILING_COMMA, false); assertThatThrownBy(() -> parser.parse(new StringReader(TRAILING_COMMA_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -409,7 +409,7 @@ public void testStrictDuplicateDetectionDefault() throws Exception { } @Test - public void testStrictDuplicateDetectionEnabled() throws Exception { + public void testStrictDuplicateDetectionEnabled() { parser.set(JSONSettings.STRICT_DUPLICATE_DETECTION, true); assertThatThrownBy(() -> parser.parse(new StringReader(STRICT_DUPLICATE_DETECTION_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) diff --git a/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDWriterBackgroundTest.java b/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDWriterBackgroundTest.java index d65c7301756..871a40a4f8e 100644 --- a/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDWriterBackgroundTest.java +++ b/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDWriterBackgroundTest.java @@ -15,7 +15,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.io.InputStream; import org.eclipse.rdf4j.model.IRI; @@ -65,7 +64,7 @@ protected void setupParserConfig(ParserConfig config) { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); @@ -74,7 +73,7 @@ protected Model parse(InputStream reader, String baseURI) @Test @Override @Disabled("TODO: Determine why this test is breaking") - public void testIllegalPrefix() throws RDFHandlerException, RDFParseException, IOException { + public void testIllegalPrefix() throws RDFHandlerException, RDFParseException { } @Test diff --git a/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDWriterTest.java b/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDWriterTest.java index 69221f004d9..90cb83b5182 100644 --- a/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDWriterTest.java +++ b/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/jsonld/JSONLDWriterTest.java @@ -15,7 +15,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.io.StringWriter; import org.eclipse.rdf4j.model.IRI; @@ -67,11 +66,11 @@ protected void setupParserConfig(ParserConfig config) { @Test @Override @Disabled("TODO: Determine why this test is breaking") - public void testIllegalPrefix() throws RDFHandlerException, RDFParseException, IOException { + public void testIllegalPrefix() throws RDFHandlerException, RDFParseException { } @Test - public void testEmptyNamespace() throws Exception { + public void testEmptyNamespace() { IRI uri1 = vf.createIRI(exNs, "uri1"); IRI uri2 = vf.createIRI(exNs, "uri2"); diff --git a/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/ndjsonld/NDJSONLDWriterTest.java b/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/ndjsonld/NDJSONLDWriterTest.java index 4bf21400ca8..03364b3188c 100644 --- a/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/ndjsonld/NDJSONLDWriterTest.java +++ b/core/rio/jsonld/src/test/java/org/eclipse/rdf4j/rio/ndjsonld/NDJSONLDWriterTest.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.ndjsonld; -import java.io.IOException; - import org.eclipse.rdf4j.rio.ParserConfig; import org.eclipse.rdf4j.rio.RDFHandlerException; import org.eclipse.rdf4j.rio.RDFParseException; @@ -34,7 +32,7 @@ public NDJSONLDWriterTest() { @Test @Override @Disabled("TODO: See case for JSONLDWriterTest") - public void testIllegalPrefix() throws RDFHandlerException, RDFParseException, IOException { + public void testIllegalPrefix() throws RDFHandlerException, RDFParseException { } @Override diff --git a/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/AbstractNQuadsParserUnitTest.java b/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/AbstractNQuadsParserUnitTest.java index db709627503..87b9d1c91ae 100644 --- a/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/AbstractNQuadsParserUnitTest.java +++ b/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/AbstractNQuadsParserUnitTest.java @@ -65,14 +65,14 @@ public abstract class AbstractNQuadsParserUnitTest { private TestRDFHandler rdfHandler; @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = createRDFParser(); rdfHandler = new TestRDFHandler(); parser.setRDFHandler(this.rdfHandler); } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { parser = null; } @@ -641,7 +641,7 @@ public void assertHandler(int expected) { } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { assertThat(parser.getSupportedSettings()).hasSize(14); } diff --git a/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/AbstractNQuadsWriterTest.java b/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/AbstractNQuadsWriterTest.java index 1680f3dc0f3..3a086558dd3 100644 --- a/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/AbstractNQuadsWriterTest.java +++ b/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/AbstractNQuadsWriterTest.java @@ -47,7 +47,7 @@ protected AbstractNQuadsWriterTest(RDFWriterFactory writerF, RDFParserFactory pa } @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = rdfParserFactory.getParser(); vf = SimpleValueFactory.getInstance(); } diff --git a/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/NQuadsWriterBackgroundTest.java b/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/NQuadsWriterBackgroundTest.java index be5c3ea2514..004df3de113 100644 --- a/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/NQuadsWriterBackgroundTest.java +++ b/core/rio/nquads/src/test/java/org/eclipse/rdf4j/rio/nquads/NQuadsWriterBackgroundTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.nquads; -import java.io.IOException; import java.io.InputStream; import org.eclipse.rdf4j.model.Model; @@ -26,7 +25,7 @@ public NQuadsWriterBackgroundTest() { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); diff --git a/core/rio/ntriples/src/main/java/org/eclipse/rdf4j/rio/ntriples/NTriplesParser.java b/core/rio/ntriples/src/main/java/org/eclipse/rdf4j/rio/ntriples/NTriplesParser.java index 389e0e2959e..b5b48815022 100644 --- a/core/rio/ntriples/src/main/java/org/eclipse/rdf4j/rio/ntriples/NTriplesParser.java +++ b/core/rio/ntriples/src/main/java/org/eclipse/rdf4j/rio/ntriples/NTriplesParser.java @@ -280,7 +280,7 @@ private void parseLiteral() { } else if (lineChars[currentIndex] == '@') { parseLangLiteral(label); } else { - object = createLiteral(label, null, null, lineNo, lineChars[currentIndex]); + object = createLiteral(label, null, ((IRI) null), lineNo, lineChars[currentIndex]); } } @@ -329,7 +329,7 @@ private void parseLangLiteral(String label) { if (currentIndex >= lineChars.length) { throwEOFException(); } - object = createLiteral(label, new String(lineChars, startIndex, currentIndex - startIndex), null, + object = createLiteral(label, new String(lineChars, startIndex, currentIndex - startIndex), ((IRI) null), lineNo, lineChars[currentIndex]); } diff --git a/core/rio/ntriples/src/test/java/org/eclipse/rdf4j/rio/ntriples/AbstractNTriplesParserUnitTest.java b/core/rio/ntriples/src/test/java/org/eclipse/rdf4j/rio/ntriples/AbstractNTriplesParserUnitTest.java index 354cdecbeed..6787dedc80a 100644 --- a/core/rio/ntriples/src/test/java/org/eclipse/rdf4j/rio/ntriples/AbstractNTriplesParserUnitTest.java +++ b/core/rio/ntriples/src/test/java/org/eclipse/rdf4j/rio/ntriples/AbstractNTriplesParserUnitTest.java @@ -294,7 +294,7 @@ public void testBlankNodeIdentifiersRDF11() throws Exception { } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { assertEquals(14, createRDFParser().getSupportedSettings().size()); } @@ -367,7 +367,7 @@ public void testBlankNodeIdentifiersWithDot() throws Exception { } @Test - public void testBlankNodeIdentifiersWithDotAsFirstCahracter() throws Exception { + public void testBlankNodeIdentifiersWithDotAsFirstCahracter() { // The character . may appear anywhere except the first or last character. RDFParser ntriplesParser = new NTriplesParser(); Model model = new LinkedHashModel(); @@ -385,7 +385,7 @@ public void testBlankNodeIdentifiersWithDotAsFirstCahracter() throws Exception { } @Test - public void testBlankNodeIdentifiersWithDotAsLastCahracter() throws Exception { + public void testBlankNodeIdentifiersWithDotAsLastCahracter() { // The character . may appear anywhere except the first or last character. RDFParser ntriplesParser = new NTriplesParser(); Model model = new LinkedHashModel(); @@ -399,7 +399,7 @@ public void testBlankNodeIdentifiersWithDotAsLastCahracter() throws Exception { } @Test - public void testBlankNodeIdentifiersWithOtherCharacters() throws Exception { + public void testBlankNodeIdentifiersWithOtherCharacters() { // The characters -, U+00B7, U+0300 to U+036F and U+203F to U+2040 are permitted anywhere except the first // character. List charactersList = new ArrayList<>(); @@ -436,7 +436,7 @@ public void testBlankNodeIdentifiersWithOtherCharacters() throws Exception { } @Test - public void testBlankNodeIdentifiersWithOtherCharactersAsFirstCharacter() throws Exception { + public void testBlankNodeIdentifiersWithOtherCharactersAsFirstCharacter() { // The characters -, U+00B7, U+0300 to U+036F and U+203F to U+2040 are permitted anywhere except the first // character. List charactersList = new ArrayList<>(); diff --git a/core/rio/ntriples/src/test/java/org/eclipse/rdf4j/rio/ntriples/NTriplesWriterBackgroundTest.java b/core/rio/ntriples/src/test/java/org/eclipse/rdf4j/rio/ntriples/NTriplesWriterBackgroundTest.java index 29e5b4e5a3f..9c1cd0f08c2 100644 --- a/core/rio/ntriples/src/test/java/org/eclipse/rdf4j/rio/ntriples/NTriplesWriterBackgroundTest.java +++ b/core/rio/ntriples/src/test/java/org/eclipse/rdf4j/rio/ntriples/NTriplesWriterBackgroundTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.ntriples; -import java.io.IOException; import java.io.InputStream; import org.eclipse.rdf4j.model.Model; @@ -31,7 +30,7 @@ public NTriplesWriterBackgroundTest() { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); diff --git a/core/rio/rdfjson/src/test/java/org/eclipse/rdf4j/rio/rdfjson/RDFJSONParserCustomTest.java b/core/rio/rdfjson/src/test/java/org/eclipse/rdf4j/rio/rdfjson/RDFJSONParserCustomTest.java index 343645cbf7c..965d9f7f084 100644 --- a/core/rio/rdfjson/src/test/java/org/eclipse/rdf4j/rio/rdfjson/RDFJSONParserCustomTest.java +++ b/core/rio/rdfjson/src/test/java/org/eclipse/rdf4j/rio/rdfjson/RDFJSONParserCustomTest.java @@ -120,7 +120,7 @@ public class RDFJSONParserCustomTest { .createLiteral("42\u0009", XSD.STRING); @BeforeEach - public void setUp() throws Exception { + public void setUp() { parser = Rio.createParser(RDFFormat.RDFJSON); errors = new ParseErrorCollector(); model = new LinkedHashModel(); @@ -128,7 +128,7 @@ public void setUp() throws Exception { parser.setRDFHandler(new ContextStatementCollector(model, SimpleValueFactory.getInstance())); } - private void verifyParseResults(Resource nextSubject, IRI nextPredicate, Value nextObject) throws Exception { + private void verifyParseResults(Resource nextSubject, IRI nextPredicate, Value nextObject) { assertEquals(0, errors.getWarnings().size()); assertEquals(0, errors.getErrors().size()); assertEquals(0, errors.getFatalErrors().size()); @@ -139,13 +139,13 @@ private void verifyParseResults(Resource nextSubject, IRI nextPredicate, Value n } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { // 17 supported in RDFJSONParser + 13 from AbstractRDFParser assertEquals(30, parser.getSupportedSettings().size()); } @Test - public void testAllowBackslashEscapingAnyCharacterDefault() throws Exception { + public void testAllowBackslashEscapingAnyCharacterDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(BACKSLASH_ESCAPED_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 1, column 5]"); @@ -159,7 +159,7 @@ public void testAllowBackslashEscapingAnyCharacterEnabled() throws Exception { } @Test - public void testAllowBackslashEscapingAnyCharacterDisabled() throws Exception { + public void testAllowBackslashEscapingAnyCharacterDisabled() { parser.set(JSONSettings.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, false); assertThatThrownBy(() -> parser.parse(new StringReader(BACKSLASH_ESCAPED_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -167,7 +167,7 @@ public void testAllowBackslashEscapingAnyCharacterDisabled() throws Exception { } @Test - public void testAllowCommentsDefault() throws Exception { + public void testAllowCommentsDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(COMMENTS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 1, column 3]"); @@ -181,7 +181,7 @@ public void testAllowCommentsEnabled() throws Exception { } @Test - public void testAllowCommentsDisabled() throws Exception { + public void testAllowCommentsDisabled() { parser.set(JSONSettings.ALLOW_COMMENTS, false); assertThatThrownBy(() -> parser.parse(new StringReader(COMMENTS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -189,7 +189,7 @@ public void testAllowCommentsDisabled() throws Exception { } @Test - public void testAllowNonNumericNumbersDefault() throws Exception { + public void testAllowNonNumericNumbersDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(NON_NUMERIC_NUMBERS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 1, column 74]"); @@ -203,7 +203,7 @@ public void testAllowNonNumericNumbersEnabled() throws Exception { } @Test - public void testAllowNonNumericNumbersDisabled() throws Exception { + public void testAllowNonNumericNumbersDisabled() { parser.set(JSONSettings.ALLOW_NON_NUMERIC_NUMBERS, false); assertThatThrownBy(() -> parser.parse(new StringReader(NON_NUMERIC_NUMBERS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -211,7 +211,7 @@ public void testAllowNonNumericNumbersDisabled() throws Exception { } @Test - public void testAllowNumericLeadingZeroesDefault() throws Exception { + public void testAllowNumericLeadingZeroesDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(NUMERIC_LEADING_ZEROES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 1, column 72]"); @@ -225,7 +225,7 @@ public void testAllowNumericLeadingZeroesEnabled() throws Exception { } @Test - public void testAllowNumericLeadingZeroesDisabled() throws Exception { + public void testAllowNumericLeadingZeroesDisabled() { parser.set(JSONSettings.ALLOW_NUMERIC_LEADING_ZEROS, false); assertThatThrownBy(() -> parser.parse(new StringReader(NUMERIC_LEADING_ZEROES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -233,7 +233,7 @@ public void testAllowNumericLeadingZeroesDisabled() throws Exception { } @Test - public void testAllowSingleQuotesDefault() throws Exception { + public void testAllowSingleQuotesDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(SINGLE_QUOTES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 1, column 3]"); @@ -247,7 +247,7 @@ public void testAllowSingleQuotesEnabled() throws Exception { } @Test - public void testAllowSingleQuotesDisabled() throws Exception { + public void testAllowSingleQuotesDisabled() { parser.set(JSONSettings.ALLOW_SINGLE_QUOTES, false); assertThatThrownBy(() -> parser.parse(new StringReader(SINGLE_QUOTES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -255,7 +255,7 @@ public void testAllowSingleQuotesDisabled() throws Exception { } @Test - public void testAllowUnquotedControlCharactersDefault() throws Exception { + public void testAllowUnquotedControlCharactersDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(UNQUOTED_CONTROL_CHARS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 1, column 75]"); @@ -269,7 +269,7 @@ public void testAllowUnquotedControlCharactersEnabled() throws Exception { } @Test - public void testAllowUnquotedControlCharactersDisabled() throws Exception { + public void testAllowUnquotedControlCharactersDisabled() { parser.set(JSONSettings.ALLOW_UNQUOTED_CONTROL_CHARS, false); assertThatThrownBy(() -> parser.parse(new StringReader(UNQUOTED_CONTROL_CHARS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -277,7 +277,7 @@ public void testAllowUnquotedControlCharactersDisabled() throws Exception { } @Test - public void testAllowUnquotedFieldNamesDefault() throws Exception { + public void testAllowUnquotedFieldNamesDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(UNQUOTED_FIELD_NAMES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 1, column 63]"); @@ -291,7 +291,7 @@ public void testAllowUnquotedFieldNamesEnabled() throws Exception { } @Test - public void testAllowUnquotedFieldNamesDisabled() throws Exception { + public void testAllowUnquotedFieldNamesDisabled() { parser.set(JSONSettings.ALLOW_UNQUOTED_FIELD_NAMES, false); assertThatThrownBy(() -> parser.parse(new StringReader(UNQUOTED_FIELD_NAMES_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -299,7 +299,7 @@ public void testAllowUnquotedFieldNamesDisabled() throws Exception { } @Test - public void testAllowYamlCommentsDefault() throws Exception { + public void testAllowYamlCommentsDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(YAML_COMMENTS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 2, column 2]"); @@ -313,7 +313,7 @@ public void testAllowYamlCommentsEnabled() throws Exception { } @Test - public void testAllowYamlCommentsDisabled() throws Exception { + public void testAllowYamlCommentsDisabled() { parser.set(JSONSettings.ALLOW_YAML_COMMENTS, false); assertThatThrownBy(() -> parser.parse(new StringReader(YAML_COMMENTS_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -321,7 +321,7 @@ public void testAllowYamlCommentsDisabled() throws Exception { } @Test - public void testAllowTrailingCommaDefault() throws Exception { + public void testAllowTrailingCommaDefault() { assertThatThrownBy(() -> parser.parse(new StringReader(TRAILING_COMMA_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) .hasMessage("Found IOException during parsing [line 1, column 113]"); @@ -335,7 +335,7 @@ public void testAllowTrailingCommaEnabled() throws Exception { } @Test - public void testAllowTrailingCommaDisabled() throws Exception { + public void testAllowTrailingCommaDisabled() { parser.set(JSONSettings.ALLOW_TRAILING_COMMA, false); assertThatThrownBy(() -> parser.parse(new StringReader(TRAILING_COMMA_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -394,7 +394,7 @@ public void testIncludeSourceLocationDisabled() throws Exception { } @Test - public void testStrictDuplicateDetectionDefault() throws Exception { + public void testStrictDuplicateDetectionDefault() { parser.set(JSONSettings.STRICT_DUPLICATE_DETECTION, false); assertThatThrownBy(() -> parser.parse(new StringReader(STRICT_DUPLICATE_DETECTION_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -404,7 +404,7 @@ public void testStrictDuplicateDetectionDefault() throws Exception { } @Test - public void testStrictDuplicateDetectionEnabled() throws Exception { + public void testStrictDuplicateDetectionEnabled() { parser.set(JSONSettings.STRICT_DUPLICATE_DETECTION, true); assertThatThrownBy(() -> parser.parse(new StringReader(STRICT_DUPLICATE_DETECTION_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) @@ -412,7 +412,7 @@ public void testStrictDuplicateDetectionEnabled() throws Exception { } @Test - public void testStrictDuplicateDetectionDisabled() throws Exception { + public void testStrictDuplicateDetectionDisabled() { parser.set(JSONSettings.STRICT_DUPLICATE_DETECTION, false); assertThatThrownBy(() -> parser.parse(new StringReader(STRICT_DUPLICATE_DETECTION_TEST_STRING), "")) .isInstanceOf(RDFParseException.class) diff --git a/core/rio/rdfjson/src/test/java/org/eclipse/rdf4j/rio/rdfjson/RDFJSONWriterTest.java b/core/rio/rdfjson/src/test/java/org/eclipse/rdf4j/rio/rdfjson/RDFJSONWriterTest.java index b5778225b46..54621f3bc88 100644 --- a/core/rio/rdfjson/src/test/java/org/eclipse/rdf4j/rio/rdfjson/RDFJSONWriterTest.java +++ b/core/rio/rdfjson/src/test/java/org/eclipse/rdf4j/rio/rdfjson/RDFJSONWriterTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.rdfjson; -import java.io.IOException; import java.io.InputStream; import org.eclipse.rdf4j.model.Model; @@ -35,7 +34,7 @@ public RDFJSONWriterTest() { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); diff --git a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLParserCustomTest.java b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLParserCustomTest.java index f194cd0077d..f7d38643716 100644 --- a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLParserCustomTest.java +++ b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLParserCustomTest.java @@ -218,7 +218,7 @@ public void testParseCommentAtStart() throws Exception { } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { assertEquals(26, Rio.createParser(RDFFormat.RDFXML).getSupportedSettings().size()); } diff --git a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLParserTest.java b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLParserTest.java index 8419abd3da1..24528f1cab2 100644 --- a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLParserTest.java +++ b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLParserTest.java @@ -54,7 +54,7 @@ public class RDFXMLParserTest { private Locale platformLocale; @BeforeEach - public void setUp() throws Exception { + public void setUp() { platformLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); @@ -68,7 +68,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { Locale.setDefault(platformLocale); } @@ -219,8 +219,9 @@ public void testInsertUsedContextPrefixes() { + " 0\n" + " 0\n" + - " \"^^)"; - String s2 = "(http://mycorp.example.com/papers/NobelPaper1, http://purl.org/metadata/dublin_core#Creator, \"David Hume\")"; + " \"^^) [null]"; + + String s2 = "(http://mycorp.example.com/papers/NobelPaper1, http://purl.org/metadata/dublin_core#Creator, \"David Hume\") [null]"; expectedLiteral[0] = s1; expectedLiteral[1] = s2; diff --git a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLPrettyWriterBackgroundTest.java b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLPrettyWriterBackgroundTest.java index 00192b433f4..31534c0be62 100644 --- a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLPrettyWriterBackgroundTest.java +++ b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLPrettyWriterBackgroundTest.java @@ -52,7 +52,7 @@ protected void setupWriterConfig(WriterConfig config) { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); diff --git a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLPrettyWriterTest.java b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLPrettyWriterTest.java index 88657bc1643..a7cb0ed4cdc 100644 --- a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLPrettyWriterTest.java +++ b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLPrettyWriterTest.java @@ -18,7 +18,6 @@ import java.io.PrintStream; import java.io.StringReader; import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -118,8 +117,7 @@ public void outOfSequenceItemsAreNotAbbreviated() throws RDFHandlerException, IO } @Test - public void compactXMLPrintTest() throws RDFHandlerException, IOException, ClassNotFoundException, - NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { + public void compactXMLPrintTest() throws RDFHandlerException { OutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream); System.setOut(printStream); diff --git a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLWriterBackgroundTest.java b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLWriterBackgroundTest.java index 330f07d0187..0087d2c0499 100644 --- a/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLWriterBackgroundTest.java +++ b/core/rio/rdfxml/src/test/java/org/eclipse/rdf4j/rio/rdfxml/RDFXMLWriterBackgroundTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.rdfxml; -import java.io.IOException; import java.io.InputStream; import org.eclipse.rdf4j.model.Model; @@ -33,7 +32,7 @@ protected void setupWriterConfig(WriterConfig config) { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); diff --git a/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGParserCustomTest.java b/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGParserCustomTest.java index e2d3d43938b..7f60657a274 100644 --- a/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGParserCustomTest.java +++ b/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGParserCustomTest.java @@ -55,10 +55,9 @@ public class TriGParserCustomTest { private StatementCollector statementCollector; /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { vf = SimpleValueFactory.getInstance(); settingsNoVerifyLangTag = new ParserConfig(); settingsNoVerifyLangTag.set(BasicParserSettings.VERIFY_LANGUAGE_TAGS, false); @@ -193,7 +192,7 @@ public void testBadPname02() throws Exception { } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { assertThat(Rio.createParser(RDFFormat.TRIG).getSupportedSettings()).hasSize(15); } diff --git a/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGPrettyWriterBackgroundTest.java b/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGPrettyWriterBackgroundTest.java index 545cf766c8a..1b00a55810a 100644 --- a/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGPrettyWriterBackgroundTest.java +++ b/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGPrettyWriterBackgroundTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.trig; -import java.io.IOException; import java.io.InputStream; import org.eclipse.rdf4j.model.Model; @@ -38,7 +37,7 @@ protected void setupWriterConfig(WriterConfig config) { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); diff --git a/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGWriterBackgroundTest.java b/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGWriterBackgroundTest.java index 1375489d7c7..e75397e711a 100644 --- a/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGWriterBackgroundTest.java +++ b/core/rio/trig/src/test/java/org/eclipse/rdf4j/rio/trig/TriGWriterBackgroundTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.rio.trig; -import java.io.IOException; import java.io.InputStream; import org.eclipse.rdf4j.model.Model; @@ -36,7 +35,7 @@ protected void setupWriterConfig(WriterConfig config) { @Override protected Model parse(InputStream reader, String baseURI) - throws RDFParseException, RDFHandlerException, IOException { + throws RDFParseException, RDFHandlerException { return QueryResults .asModel(QueryResults.parseGraphBackground(reader, baseURI, rdfParserFactory.getRDFFormat(), null)); diff --git a/core/rio/trix/src/test/java/org/eclipse/rdf4j/rio/trix/TriXParserTest.java b/core/rio/trix/src/test/java/org/eclipse/rdf4j/rio/trix/TriXParserTest.java index dfe20c8b5b2..d17e72526a7 100644 --- a/core/rio/trix/src/test/java/org/eclipse/rdf4j/rio/trix/TriXParserTest.java +++ b/core/rio/trix/src/test/java/org/eclipse/rdf4j/rio/trix/TriXParserTest.java @@ -44,7 +44,7 @@ public class TriXParserTest { private Locale platformLocale; @BeforeEach - public void setUp() throws Exception { + public void setUp() { platformLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); @@ -57,7 +57,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { Locale.setDefault(platformLocale); } diff --git a/core/rio/turtle/src/main/java/org/eclipse/rdf4j/rio/turtle/TurtleParser.java b/core/rio/turtle/src/main/java/org/eclipse/rdf4j/rio/turtle/TurtleParser.java index 0840571b9dd..71b7cd89f45 100644 --- a/core/rio/turtle/src/main/java/org/eclipse/rdf4j/rio/turtle/TurtleParser.java +++ b/core/rio/turtle/src/main/java/org/eclipse/rdf4j/rio/turtle/TurtleParser.java @@ -31,6 +31,7 @@ import org.eclipse.rdf4j.model.Triple; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.util.Values; import org.eclipse.rdf4j.model.vocabulary.RDF; @@ -638,7 +639,7 @@ protected Literal parseQuotedLiteral() throws IOException, RDFParseException, RD unread(c); - return createLiteral(label, lang.toString(), null, getLineNumber(), -1); + return createLiteral(label, lang.toString(), ((IRI) null), getLineNumber(), -1); } else if (c == '^') { readCodePoint(); @@ -659,7 +660,7 @@ protected Literal parseQuotedLiteral() throws IOException, RDFParseException, RD } return createLiteral(label, null, (IRI) datatype, getLineNumber(), -1); } else { - return createLiteral(label, null, null, getLineNumber(), -1); + return createLiteral(label, null, ((IRI) null), getLineNumber(), -1); } } @@ -991,10 +992,10 @@ protected Value parseQNameOrBoolean() throws IOException, RDFParseException { if (value.equals("true")) { unread(c); - return createLiteral("true", null, XSD.BOOLEAN, getLineNumber(), -1); + return createLiteral("true", null, CoreDatatype.XSD.BOOLEAN, getLineNumber(), -1); } else if (value.equals("false")) { unread(c); - return createLiteral("false", null, XSD.BOOLEAN, getLineNumber(), -1); + return createLiteral("false", null, CoreDatatype.XSD.BOOLEAN, getLineNumber(), -1); } } diff --git a/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/CustomTurtleParserTest.java b/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/CustomTurtleParserTest.java index 9bbc137d313..5a8cbda732a 100644 --- a/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/CustomTurtleParserTest.java +++ b/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/CustomTurtleParserTest.java @@ -67,10 +67,9 @@ public class CustomTurtleParserTest { private final Logger logger = LoggerFactory.getLogger(getClass()); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { vf = SimpleValueFactory.getInstance(); settingsNoVerifyLangTag = new ParserConfig(); settingsNoVerifyLangTag.set(BasicParserSettings.VERIFY_LANGUAGE_TAGS, false); @@ -161,7 +160,7 @@ public void testSES1887CloseSquareBracket() throws Exception { } @Test - public void testLiteralWithNewlines() throws Exception { + public void testLiteralWithNewlines() { String namespace = "http://www.foo.com/bar#"; String okLiteralString = "Literal \n without \n new line at the beginning. \n "; String errLiteralString = "\n Literal \n with \n new line at the beginning. \n "; @@ -184,7 +183,7 @@ public void testLiteralWithNewlines() throws Exception { } @Test - public void testSupportedSettings() throws Exception { + public void testSupportedSettings() { assertThat(parser.getSupportedSettings()).hasSize(15); } diff --git a/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtlePrettyWriterTest.java b/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtlePrettyWriterTest.java index 6339c2ca70c..feac209a0c8 100644 --- a/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtlePrettyWriterTest.java +++ b/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtlePrettyWriterTest.java @@ -113,7 +113,7 @@ public void testRoundTripPreserveBNodeIds() throws Exception { } @Test - public void testAbbreviateNumbers() throws Exception { + public void testAbbreviateNumbers() { StringWriter sw = new StringWriter(); WriterConfig config = new WriterConfig(); @@ -128,7 +128,7 @@ public void testAbbreviateNumbers() throws Exception { } @Test - public void testDontAbbreviateNumbers() throws Exception { + public void testDontAbbreviateNumbers() { StringWriter sw = new StringWriter(); WriterConfig config = new WriterConfig(); diff --git a/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleUtilTest.java b/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleUtilTest.java index 41e451d18fd..d884ca41496 100644 --- a/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleUtilTest.java +++ b/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleUtilTest.java @@ -26,17 +26,15 @@ public class TurtleUtilTest { /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { } /** diff --git a/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleWriterTest.java b/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleWriterTest.java index 17364444068..d0b8bee32d8 100644 --- a/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleWriterTest.java +++ b/core/rio/turtle/src/test/java/org/eclipse/rdf4j/rio/turtle/TurtleWriterTest.java @@ -673,7 +673,7 @@ public void testBlankNodeInlining_indirectCircularReferenceWithIRI() throws Exce } @Test - public void testIgnoreAbbreviateNumbers() throws Exception { + public void testIgnoreAbbreviateNumbers() { StringWriter sw = new StringWriter(); WriterConfig config = new WriterConfig(); diff --git a/core/sail/api/pom.xml b/core/sail/api/pom.xml index fcff65ad0bf..946090c1350 100644 --- a/core/sail/api/pom.xml +++ b/core/sail/api/pom.xml @@ -52,12 +52,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/common/concurrent/locks/LockingIteration.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/common/concurrent/locks/LockingIteration.java index aebbc25682e..c247c611e92 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/common/concurrent/locks/LockingIteration.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/common/concurrent/locks/LockingIteration.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.EmptyIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.IterationWrapper; /** @@ -23,7 +22,7 @@ * before the lock is released. This iterator closes itself as soon as all elements have been read. */ @Deprecated(since = "4.1.0") -public class LockingIteration extends IterationWrapper { +public class LockingIteration extends IterationWrapper { /** * The lock to release when the Iteration is closed. @@ -37,7 +36,7 @@ public class LockingIteration extends IterationWrappernull. */ @Deprecated(since = "4.1.0", forRemoval = true) - public LockingIteration(Lock lock, Iteration iter) { + public LockingIteration(Lock lock, CloseableIteration iter) { super(iter); if (iter instanceof EmptyIteration) { lock.release(); @@ -47,8 +46,8 @@ public LockingIteration(Lock lock, Iteration iter) { } } - public static CloseableIteration getInstance(Lock lock, - CloseableIteration iter) { + public static CloseableIteration getInstance(Lock lock, + CloseableIteration iter) { if (iter instanceof EmptyIteration) { lock.release(); return iter; @@ -58,7 +57,7 @@ public static CloseableIteration getInstance(Lock } @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/SailConnection.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/SailConnection.java index f25d5414681..8fa0a25df88 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/SailConnection.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/SailConnection.java @@ -24,7 +24,6 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.Query; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.query.algebra.UpdateExpr; @@ -88,7 +87,7 @@ default Optional prepareQuery(QueryLanguage ql, Query.QueryType type, * @throws SailException If the Sail object encountered an error or unexpected situation internally. * @throws IllegalStateException If the connection has been closed. */ - CloseableIteration evaluate(TupleExpr tupleExpr, + CloseableIteration evaluate(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException; /** @@ -97,7 +96,7 @@ CloseableIteration evaluate(Tupl * @return An iterator over the context identifiers, should not contain any duplicates. * @throws IllegalStateException If the connection has been closed. */ - CloseableIteration getContextIDs() throws SailException; + CloseableIteration getContextIDs() throws SailException; /** * Gets all statements from the specified contexts that have a specific subject, predicate and/or object. All three @@ -116,7 +115,7 @@ CloseableIteration evaluate(Tupl * @throws SailException If the Sail object encountered an error or unexpected situation internally. * @throws IllegalStateException If the connection has been closed. */ - CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + CloseableIteration getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException; /** @@ -141,7 +140,7 @@ CloseableIteration getStatements(Resource su default boolean hasStatement(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { - try (CloseableIteration stIter = getStatements(subj, pred, obj, + try (CloseableIteration stIter = getStatements(subj, pred, obj, includeInferred, contexts)) { return stIter.hasNext(); } @@ -365,7 +364,7 @@ void removeStatement(UpdateContext op, Resource subj, IRI pred, Value obj, Resou * @throws SailException If the Sail object encountered an error or unexpected situation internally. * @throws IllegalStateException If the connection has been closed. */ - CloseableIteration getNamespaces() throws SailException; + CloseableIteration getNamespaces() throws SailException; /** * Gets the namespace that is associated with the specified prefix, if any. diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/AbstractDelegatingSailImplConfig.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/AbstractDelegatingSailImplConfig.java index c8b963169a2..aa6062ab3e9 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/AbstractDelegatingSailImplConfig.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/AbstractDelegatingSailImplConfig.java @@ -24,9 +24,6 @@ public abstract class AbstractDelegatingSailImplConfig extends AbstractSailImplConfig implements DelegatingSailImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private SailImplConfig delegate; /** @@ -71,15 +68,26 @@ public void validate() throws SailConfigException { @Override public Resource export(Model m) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(m); + } + + Resource implNode = super.export(m); + + if (delegate != null) { + Resource delegateNode = delegate.export(m); + m.add(implNode, CONFIG.delegate, delegateNode); + } + + return implNode; + } + + private Resource exportLegacy(Model m) { Resource implNode = super.export(m); if (delegate != null) { Resource delegateNode = delegate.export(m); - if (USE_CONFIG) { - m.add(implNode, CONFIG.delegate, delegateNode); - } else { - m.add(implNode, DELEGATE, delegateNode); - } + m.add(implNode, DELEGATE, delegateNode); } return implNode; diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/AbstractSailImplConfig.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/AbstractSailImplConfig.java index 8e321c0c2be..00f05ae489f 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/AbstractSailImplConfig.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/AbstractSailImplConfig.java @@ -30,9 +30,6 @@ */ public abstract class AbstractSailImplConfig implements SailImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private String type; private long iterationCacheSyncThreshold; @@ -70,30 +67,41 @@ public void validate() throws SailConfigException { @Override public Resource export(Model m) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(m); + } + + BNode implNode = bnode(); + + m.setNamespace(CONFIG.NS); + if (type != null) { + m.add(implNode, CONFIG.Sail.type, literal(type)); + } + + if (iterationCacheSyncThreshold > 0) { + m.add(implNode, CONFIG.Sail.iterationCacheSyncThreshold, literal(iterationCacheSyncThreshold)); + } + + if (connectionTimeOut > 0) { + m.add(implNode, CONFIG.Sail.connectionTimeOut, literal(connectionTimeOut)); + } + return implNode; + } + + private Resource exportLegacy(Model m) { BNode implNode = bnode(); + m.setNamespace("sail", SailConfigSchema.NAMESPACE); if (type != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Sail.type, literal(type)); - } else { - m.add(implNode, SAILTYPE, literal(type)); - } + m.add(implNode, SAILTYPE, literal(type)); } if (iterationCacheSyncThreshold > 0) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Sail.iterationCacheSyncThreshold, literal(iterationCacheSyncThreshold)); - } else { - m.add(implNode, ITERATION_CACHE_SYNC_THRESHOLD, literal(iterationCacheSyncThreshold)); - } + m.add(implNode, ITERATION_CACHE_SYNC_THRESHOLD, literal(iterationCacheSyncThreshold)); } if (connectionTimeOut > 0) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Sail.connectionTimeOut, literal(connectionTimeOut)); - } else { - m.add(implNode, CONNECTION_TIME_OUT, literal(connectionTimeOut)); - } + m.add(implNode, CONNECTION_TIME_OUT, literal(connectionTimeOut)); } return implNode; } diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/SailConfigSchema.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/SailConfigSchema.java index f2c742857f7..c9dde7b866c 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/SailConfigSchema.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/config/SailConfigSchema.java @@ -30,7 +30,7 @@ public class SailConfigSchema { public static final String NAMESPACE = "http://www.openrdf.org/config/sail#"; /** - * @deprecated use {@link CONFIG#type} instead. + * @deprecated use {@link CONFIG.Sail#type} instead. */ public final static IRI SAILTYPE = iri(NAMESPACE, "sailType"); @@ -40,13 +40,12 @@ public class SailConfigSchema { public final static IRI DELEGATE = iri(NAMESPACE, "delegate"); /** - * @deprecated use {@link CONFIG#iterationCacheSyncThreshold} instead. + * @deprecated use {@link CONFIG.Sail#iterationCacheSyncThreshold} instead. */ public final static IRI ITERATION_CACHE_SYNC_THRESHOLD = iri(NAMESPACE, "iterationCacheSyncThreshold"); /** - * @deprecated use {@link CONFIG#connectionTimeOut} instead. + * @deprecated use {@link CONFIG.Sail#connectionTimeOut} instead. */ public final static IRI CONNECTION_TIME_OUT = iri(NAMESPACE, "connectionTimeOut"); - } diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/AbstractSailConnection.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/AbstractSailConnection.java index ad56bb28e9e..edd7507e123 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/AbstractSailConnection.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/AbstractSailConnection.java @@ -40,7 +40,6 @@ import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.sail.SailConnection; import org.eclipse.rdf4j.sail.SailException; @@ -106,16 +105,8 @@ public abstract class AbstractSailConnection implements SailConnection { * Lock used to prevent concurrent calls to update methods like addStatement, clear, commit, etc. within a * transaction. * - * @deprecated Will be made private. */ - @Deprecated(since = "4.1.0") - protected final ReentrantLock updateLock = new ReentrantLock(); - - @Deprecated(since = "4.1.0", forRemoval = true) - protected final ReentrantReadWriteLock connectionLock = new ReentrantReadWriteLock(); - - @InternalUseOnly - protected boolean useConnectionLock = true; + private final ReentrantLock updateLock = new ReentrantLock(); private final LongAdder iterationsOpened = new LongAdder(); private final LongAdder iterationsClosed = new LongAdder(); @@ -203,9 +194,6 @@ public void begin(IsolationLevel isolationLevel) throws SailException { } this.transactionIsolationLevel = compatibleLevel; - if (useConnectionLock) { - connectionLock.readLock().lock(); - } blockClose.increment(); try { verifyIsOpen(); @@ -223,10 +211,6 @@ public void begin(IsolationLevel isolationLevel) throws SailException { } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } - } startUpdate(null); } @@ -254,9 +238,6 @@ public final void close() throws SailException { if (!IS_OPEN.compareAndSet(this, true, false)) { return; } - if (useConnectionLock) { - connectionLock.writeLock().lock(); - } try { while (true) { @@ -299,16 +280,9 @@ public final void close() throws SailException { sailBase.connectionClosed(this); } } finally { - try { - if (deadlockPreventionThread != null) { - deadlockPreventionThread.interrupt(); - } - } finally { - if (useConnectionLock) { - connectionLock.writeLock().unlock(); - } + if (deadlockPreventionThread != null) { + deadlockPreventionThread.interrupt(); } - } } @@ -359,16 +333,14 @@ private Thread startDeadlockPreventionThread() { } @Override - public final CloseableIteration evaluate(TupleExpr tupleExpr, + public final CloseableIteration evaluate(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { flushPendingUpdates(); - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); - CloseableIteration iteration = null; + CloseableIteration iteration = null; try { iteration = evaluateInternal(tupleExpr, dataset, bindings, includeInferred); if (assertsEnabled) { @@ -383,41 +355,31 @@ public final CloseableIteration } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @Override - public final CloseableIteration getContextIDs() throws SailException { + public final CloseableIteration getContextIDs() throws SailException { flushPendingUpdates(); - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); return registerIteration(getContextIDsInternal()); } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @Override - public final CloseableIteration getStatements(Resource subj, IRI pred, + public final CloseableIteration getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { flushPendingUpdates(); - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); - CloseableIteration iteration = null; + CloseableIteration iteration = null; try { iteration = getStatementsInternal(subj, pred, obj, includeInferred, contexts); return registerIteration(iteration); @@ -429,9 +391,6 @@ public final CloseableIteration getStatement } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -439,18 +398,13 @@ public final CloseableIteration getStatement public final boolean hasStatement(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { flushPendingUpdates(); - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); return hasStatementInternal(subj, pred, obj, includeInferred, contexts); } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -465,18 +419,13 @@ protected boolean hasStatementInternal(Resource subj, IRI pred, Value obj, boole @Override public final long size(Resource... contexts) throws SailException { flushPendingUpdates(); - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); return sizeInternal(contexts); } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -514,9 +463,7 @@ public final void prepare() throws SailException { if (isActive()) { endUpdate(null); } - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); @@ -532,9 +479,6 @@ public final void prepare() throws SailException { } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -544,9 +488,6 @@ public final void commit() throws SailException { endUpdate(null); } - if (useConnectionLock) { - connectionLock.readLock().lock(); - } blockClose.increment(); try { verifyIsOpen(); @@ -566,9 +507,6 @@ public final void commit() throws SailException { } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -580,9 +518,7 @@ public final void rollback() throws SailException { synchronized (removed) { removed.clear(); } - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); @@ -605,9 +541,6 @@ public final void rollback() throws SailException { } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -701,9 +634,7 @@ public void removeStatement(UpdateContext op, Resource subj, IRI pred, Value obj @Override public final void endUpdate(UpdateContext op) throws SailException { - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); @@ -717,9 +648,7 @@ public final void endUpdate(UpdateContext op) throws SailException { } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } + if (op != null) { flush(); } @@ -756,9 +685,7 @@ protected void endUpdateInternal(UpdateContext op) throws SailException { @Override public final void clear(Resource... contexts) throws SailException { flushPendingUpdates(); - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); @@ -773,26 +700,18 @@ public final void clear(Resource... contexts) throws SailException { } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @Override - public final CloseableIteration getNamespaces() throws SailException { - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + public final CloseableIteration getNamespaces() throws SailException { + blockClose.increment(); try { verifyIsOpen(); return registerIteration(getNamespacesInternal()); } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -801,18 +720,13 @@ public final String getNamespace(String prefix) throws SailException { if (prefix == null) { throw new NullPointerException("prefix must not be null"); } - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); return getNamespaceInternal(prefix); } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -824,9 +738,7 @@ public final void setNamespace(String prefix, String name) throws SailException if (name == null) { throw new NullPointerException("name must not be null"); } - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); @@ -840,9 +752,6 @@ public final void setNamespace(String prefix, String name) throws SailException } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -851,9 +760,7 @@ public final void removeNamespace(String prefix) throws SailException { if (prefix == null) { throw new NullPointerException("prefix must not be null"); } - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); @@ -867,17 +774,12 @@ public final void removeNamespace(String prefix) throws SailException { } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @Override public final void clearNamespaces() throws SailException { - if (useConnectionLock) { - connectionLock.readLock().lock(); - } + blockClose.increment(); try { verifyIsOpen(); @@ -891,9 +793,6 @@ public final void clearNamespaces() throws SailException { } } finally { unblockClose.increment(); - if (useConnectionLock) { - connectionLock.readLock().unlock(); - } } } @@ -915,21 +814,6 @@ protected void setStatementsRemoved() { statementsRemoved = true; } - @Deprecated(forRemoval = true) - protected Lock getSharedConnectionLock() throws SailException { - return new JavaLock(connectionLock.readLock()); - } - - @Deprecated(forRemoval = true) - protected Lock getExclusiveConnectionLock() throws SailException { - return new JavaLock(connectionLock.writeLock()); - } - - @Deprecated(forRemoval = true) - protected Lock getTransactionLock() throws SailException { - return new JavaLock(updateLock); - } - /** * This is for internal use only. It returns the thread that opened this connection. * @@ -944,7 +828,7 @@ public Thread getOwner() { * Registers an iteration as active by wrapping it in a {@link SailBaseIteration} object and adding it to the list * of active iterations. */ - protected CloseableIteration registerIteration(CloseableIteration iter) { + protected CloseableIteration registerIteration(CloseableIteration iter) { if (iter instanceof EmptyIteration) { return iter; } @@ -972,13 +856,13 @@ protected void iterationClosed(SailBaseIteration iter) { protected abstract void closeInternal() throws SailException; - protected abstract CloseableIteration evaluateInternal( + protected abstract CloseableIteration evaluateInternal( TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException; - protected abstract CloseableIteration getContextIDsInternal() + protected abstract CloseableIteration getContextIDsInternal() throws SailException; - protected abstract CloseableIteration getStatementsInternal(Resource subj, + protected abstract CloseableIteration getStatementsInternal(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException; protected abstract long sizeInternal(Resource... contexts) throws SailException; @@ -1001,7 +885,7 @@ protected abstract void removeStatementsInternal(Resource subj, IRI pred, Value protected abstract void clearInternal(Resource... contexts) throws SailException; - protected abstract CloseableIteration getNamespacesInternal() + protected abstract CloseableIteration getNamespacesInternal() throws SailException; protected abstract String getNamespaceInternal(String prefix) throws SailException; @@ -1060,7 +944,6 @@ private void forceCloseActiveOperations() throws SailException { "Connection closed before all iterations were closed: " + entry.getKey().toString(), entry.getValue()); } - } } finally { if (deadlockPreventionThread != null) { diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/CleanerIteration.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/CleanerIteration.java index cd0ba5ab527..f85a652e1d9 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/CleanerIteration.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/CleanerIteration.java @@ -17,67 +17,60 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -final class CleanerIteration implements CloseableIteration { +final class CleanerIteration implements CloseableIteration { private static final Logger logger = LoggerFactory.getLogger(CleanerIteration.class); - private final CloseableIteration delegate; + private final CloseableIteration delegate; private final Cleaner.Cleanable cleanable; - private final CleanableState state; + private final CleanableState state; - public CleanerIteration(CloseableIteration delegate, ConcurrentCleaner cleaner) { + public CleanerIteration(CloseableIteration delegate, ConcurrentCleaner cleaner) { this.delegate = delegate; this.state = new CleanableState<>(delegate); this.cleanable = cleaner.register(this, state); } @Override - public void close() throws X { + public void close() { state.close(); cleanable.clean(); } @Override - public boolean hasNext() throws X { + public boolean hasNext() { return delegate.hasNext(); } @Override - public E next() throws X { + public E next() { return delegate.next(); } @Override - public void remove() throws X { + public void remove() { delegate.remove(); } - private final static class CleanableState implements Runnable { + private final static class CleanableState implements Runnable { - private final CloseableIteration iteration; + private final CloseableIteration iteration; private boolean closed = false; - public CleanableState(CloseableIteration iteration) { + public CleanableState(CloseableIteration iteration) { this.iteration = iteration; } @Override public void run() { if (!closed) { - try { - logger.warn( - "Forced closing of unclosed iteration. Set the system property 'org.eclipse.rdf4j.repository.debug' to 'true' to get stack traces."); - iteration.close(); - } catch (Exception e) { - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - throw new RuntimeException(e); - } + logger.warn( + "Forced closing of unclosed iteration. Set the system property 'org.eclipse.rdf4j.repository.debug' to 'true' to get stack traces."); + iteration.close(); } } - public void close() throws X { + public void close() { closed = true; iteration.close(); } diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/SailBaseIteration.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/SailBaseIteration.java index e671da309fa..2260ce35f3b 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/SailBaseIteration.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/SailBaseIteration.java @@ -19,7 +19,7 @@ * * @author Jeen Broekstra */ -class SailBaseIteration extends IterationWrapper { +class SailBaseIteration extends IterationWrapper { private final AbstractSailConnection connection; @@ -29,13 +29,13 @@ class SailBaseIteration extends IterationWrapper { * @param iter the wrapped iteration over sail objects. * @param connection the connection from which this iteration originates. */ - public SailBaseIteration(CloseableIteration iter, AbstractSailConnection connection) { + public SailBaseIteration(CloseableIteration iter, AbstractSailConnection connection) { super(iter); this.connection = connection; } @Override - public boolean hasNext() throws E { + public boolean hasNext() { if (isClosed()) { return false; } @@ -50,7 +50,7 @@ public boolean hasNext() throws E { } @Override - protected void handleClose() throws E { + protected void handleClose() { try { super.handleClose(); } finally { diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/SailConnectionWrapper.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/SailConnectionWrapper.java index b6b21948aa4..0ca7b23c735 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/SailConnectionWrapper.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/SailConnectionWrapper.java @@ -23,7 +23,6 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.Query; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolver; @@ -108,18 +107,18 @@ public Optional prepareQuery(QueryLanguage ql, Query.QueryType type, } @Override - public CloseableIteration evaluate(TupleExpr tupleExpr, + public CloseableIteration evaluate(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { return wrappedCon.evaluate(tupleExpr, dataset, bindings, includeInferred); } @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { return wrappedCon.getContextIDs(); } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { return wrappedCon.getStatements(subj, pred, obj, includeInferred, contexts); } @@ -191,7 +190,7 @@ public void clear(Resource... contexts) throws SailException { } @Override - public CloseableIteration getNamespaces() throws SailException { + public CloseableIteration getNamespaces() throws SailException { return wrappedCon.getNamespaces(); } diff --git a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/TupleExprWrapperIteration.java b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/TupleExprWrapperIteration.java index 0c3fb48ebd3..9ead444f571 100644 --- a/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/TupleExprWrapperIteration.java +++ b/core/sail/api/src/main/java/org/eclipse/rdf4j/sail/helpers/TupleExprWrapperIteration.java @@ -23,13 +23,13 @@ * * @author Håvard M. Ottestad */ -class TupleExprWrapperIteration implements CloseableIteration { +class TupleExprWrapperIteration implements CloseableIteration { - private final CloseableIteration delegate; + private final CloseableIteration delegate; private final TupleExpr tupleExpr; private final TupleExpr tupleExprClone; - public TupleExprWrapperIteration(CloseableIteration delegate, TupleExpr tupleExpr) { + public TupleExprWrapperIteration(CloseableIteration delegate, TupleExpr tupleExpr) { this.delegate = delegate; this.tupleExpr = tupleExpr; this.tupleExprClone = tupleExpr.clone(); @@ -41,22 +41,22 @@ public Stream stream() { } @Override - public void close() throws X { + public void close() { delegate.close(); } @Override - public boolean hasNext() throws X { + public boolean hasNext() { return delegate.hasNext(); } @Override - public T next() throws X { + public T next() { return delegate.next(); } @Override - public void remove() throws X { + public void remove() { delegate.remove(); } diff --git a/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/AbstractReadWriteLockManagerTest.java b/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/AbstractReadWriteLockManagerTest.java index 63de809d2f2..4dc0a9c11cb 100644 --- a/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/AbstractReadWriteLockManagerTest.java +++ b/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/AbstractReadWriteLockManagerTest.java @@ -644,13 +644,13 @@ private void readLock(AbstractReadWriteLockManager lockManager) throws Interrupt assertTrue(lock.isActive()); } - private void writeLockTry(AbstractReadWriteLockManager lockManager) throws InterruptedException { + private void writeLockTry(AbstractReadWriteLockManager lockManager) { Lock lock = lockManager.tryWriteLock(); assertNotNull(lock); assertTrue(lock.isActive()); } - private void readLockTry(AbstractReadWriteLockManager lockManager) throws InterruptedException { + private void readLockTry(AbstractReadWriteLockManager lockManager) { Lock lock = lockManager.tryReadLock(); assertNotNull(lock); assertTrue(lock.isActive()); diff --git a/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/ReadPrefReadWriteLockManagerTestIT.java b/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/ReadPrefReadWriteLockManagerTestIT.java index 4cc00d13306..0ccae7ab537 100644 --- a/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/ReadPrefReadWriteLockManagerTestIT.java +++ b/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/ReadPrefReadWriteLockManagerTestIT.java @@ -25,7 +25,7 @@ void setUpLockManagers() { } @Override - void writeLockShouldSucceed() throws InterruptedException { + void writeLockShouldSucceed() { // this test can take a very long time to succeed } } diff --git a/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/benchmarks/BaseLockManagerBenchmark.java b/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/benchmarks/BaseLockManagerBenchmark.java index e29e03fc880..cdae8228540 100644 --- a/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/benchmarks/BaseLockManagerBenchmark.java +++ b/core/sail/api/src/test/java/org/eclipse/rdf4j/common/concurrent/locks/benchmarks/BaseLockManagerBenchmark.java @@ -30,14 +30,14 @@ public class BaseLockManagerBenchmark { ExecutorService executorService; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ReadPrefReadWriteLockManager.class.getName()); root.setLevel(ch.qos.logback.classic.Level.ERROR); executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); } @TearDown(Level.Trial) - public void tearDown() throws InterruptedException { + public void tearDown() { executorService.shutdownNow(); } diff --git a/core/sail/api/src/test/java/org/eclipse/rdf4j/sail/helpers/AbstractSailTest.java b/core/sail/api/src/test/java/org/eclipse/rdf4j/sail/helpers/AbstractSailTest.java index c77a36204c1..c1c64931f40 100644 --- a/core/sail/api/src/test/java/org/eclipse/rdf4j/sail/helpers/AbstractSailTest.java +++ b/core/sail/api/src/test/java/org/eclipse/rdf4j/sail/helpers/AbstractSailTest.java @@ -38,7 +38,7 @@ public class AbstractSailTest { private final Random random = new Random(43252333); @BeforeEach - public void setUp() throws Exception { + public void setUp() { subject = new AbstractSail() { diff --git a/core/sail/api/src/test/java/org/eclipse/rdf4j/sail/helpers/NotifyingSailConnectionWrapperTest.java b/core/sail/api/src/test/java/org/eclipse/rdf4j/sail/helpers/NotifyingSailConnectionWrapperTest.java index ba051e6e5a4..42d73fbaf13 100644 --- a/core/sail/api/src/test/java/org/eclipse/rdf4j/sail/helpers/NotifyingSailConnectionWrapperTest.java +++ b/core/sail/api/src/test/java/org/eclipse/rdf4j/sail/helpers/NotifyingSailConnectionWrapperTest.java @@ -33,12 +33,12 @@ public class NotifyingSailConnectionWrapperTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterAll - public static void afterAll() throws Exception { + public static void afterAll() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } diff --git a/core/sail/base/pom.xml b/core/sail/base/pom.xml index 3b315c67fe6..6a5ce26a073 100644 --- a/core/sail/base/pom.xml +++ b/core/sail/base/pom.xml @@ -52,12 +52,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/TripleSourceIterationWrapper.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/TripleSourceIterationWrapper.java index 874bd051a38..1a057dc595a 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/TripleSourceIterationWrapper.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/TripleSourceIterationWrapper.java @@ -19,12 +19,12 @@ import org.eclipse.rdf4j.query.QueryEvaluationException; @InternalUseOnly -public class TripleSourceIterationWrapper implements CloseableIteration { +public class TripleSourceIterationWrapper implements CloseableIteration { - private final CloseableIteration delegate; + private final CloseableIteration delegate; private boolean closed = false; - public TripleSourceIterationWrapper(CloseableIteration delegate) { + public TripleSourceIterationWrapper(CloseableIteration delegate) { this.delegate = Objects.requireNonNull(delegate, "The iterator was null"); } diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/DelegatingSailDataset.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/DelegatingSailDataset.java index d47bda586ac..5f342e17a2e 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/DelegatingSailDataset.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/DelegatingSailDataset.java @@ -48,7 +48,7 @@ public void close() throws SailException { } @Override - public CloseableIteration getNamespaces() throws SailException { + public CloseableIteration getNamespaces() throws SailException { return delegate.getNamespaces(); } @@ -58,18 +58,18 @@ public String getNamespace(String prefix) throws SailException { } @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { return delegate.getContextIDs(); } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { return delegate.getStatements(subj, pred, obj, contexts); } @Override - public CloseableIteration getTriples(Resource subj, IRI pred, + public CloseableIteration getTriples(Resource subj, IRI pred, Value obj) throws SailException { return delegate.getTriples(subj, pred, obj); } diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/DistinctModelReducingUnionIteration.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/DistinctModelReducingUnionIteration.java index e486b64179a..2095c4e71e2 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/DistinctModelReducingUnionIteration.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/DistinctModelReducingUnionIteration.java @@ -40,13 +40,13 @@ * There is no overflow to disk for this cache. *

**/ -public class DistinctModelReducingUnionIteration extends LookAheadIteration { +public class DistinctModelReducingUnionIteration extends LookAheadIteration { - private final CloseableIteration iterator; + private final CloseableIteration iterator; private final Consumer approvedRemover; private final Supplier> approvedSupplier; - DistinctModelReducingUnionIteration(CloseableIteration iterator, + DistinctModelReducingUnionIteration(CloseableIteration iterator, Consumer approvedRemover, Supplier> approvedSupplier) { this.iterator = iterator; diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/ObservingSailDataset.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/ObservingSailDataset.java index da4744502fb..3105ef7382f 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/ObservingSailDataset.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/ObservingSailDataset.java @@ -58,13 +58,13 @@ public void close() throws SailException { } @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { observer.observe(null, null, null); return super.getContextIDs(); } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { observer.observe(subj, pred, obj, contexts); return super.getStatements(subj, pred, obj, contexts); diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailClosingIteration.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailClosingIteration.java index 65d1e27fb51..8e032cf717f 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailClosingIteration.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailClosingIteration.java @@ -16,28 +16,27 @@ import java.util.NoSuchElementException; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.IterationWrapper; import org.eclipse.rdf4j.sail.SailException; /** - * An {@link Iteration} that holds on to a {@link SailClosable} until the Iteration is closed. Upon closing, the - * underlying Iteration is closed before the lock is released. This iterator closes itself as soon as all elements have - * been read. + * An {@link CloseableIteration} that holds on to a {@link SailClosable} until the Iteration is closed. Upon closing, + * the underlying Iteration is closed before the lock is released. This iterator closes itself as soon as all elements + * have been read. * * @author James Leigh */ -abstract class SailClosingIteration extends IterationWrapper { +abstract class SailClosingIteration extends IterationWrapper { /** - * Creates a new {@link Iteration} that automatically closes the given {@link SailClosable}s. + * Creates a new {@link CloseableIteration} that automatically closes the given {@link SailClosable}s. * * @param iter The underlying Iteration, must not be null. * @param closes The {@link SailClosable}s to {@link SailClosable#close()} when the itererator is closed. * @return a {@link CloseableIteration} that closes the given {@link SailClosable} */ public static SailClosingIteration makeClosable( - CloseableIteration iter, SailClosable... closes) { + CloseableIteration iter, SailClosable... closes) { return new SailClosingIteration<>(iter, closes) { @Override @@ -61,12 +60,12 @@ protected void handleSailException(SailException e) throws SailException { *--------------*/ /** - * Creates a new {@link Iteration} that automatically closes the given {@link SailClosable}s. + * Creates a new {@link CloseableIteration} that automatically closes the given {@link SailClosable}s. * * @param iter The underlying Iteration, must not be null. * @param closes The {@link SailClosable}s to {@link SailClosable#close()} when the itererator is closed. */ - public SailClosingIteration(CloseableIteration iter, SailClosable... closes) { + public SailClosingIteration(CloseableIteration iter, SailClosable... closes) { super(iter); this.closes = closes; } @@ -76,7 +75,7 @@ public SailClosingIteration(CloseableIteration iter, SailClosabl *---------*/ @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (isClosed()) { return false; } @@ -89,7 +88,7 @@ public boolean hasNext() throws X { } @Override - public T next() throws X { + public T next() { if (isClosed()) { throw new NoSuchElementException("Iteration has been closed"); } @@ -102,7 +101,7 @@ public T next() throws X { } @Override - public void remove() throws X { + public void remove() { if (isClosed()) { throw new IllegalStateException(); } @@ -115,7 +114,7 @@ public void remove() throws X { } @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDataset.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDataset.java index ff5acc46a01..45e12e39a4f 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDataset.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDataset.java @@ -43,7 +43,7 @@ public interface SailDataset extends SailClosable { * @return An iterator over the relevant namespaces, should not contain any duplicates. * @throws SailException If this object encountered an error or unexpected situation internally. */ - CloseableIteration getNamespaces() throws SailException; + CloseableIteration getNamespaces() throws SailException; /** * Gets the namespace that is associated with the specified prefix, if any. @@ -61,7 +61,7 @@ public interface SailDataset extends SailClosable { * * @return An iterator over the context identifiers, should not contain any duplicates. */ - CloseableIteration getContextIDs() throws SailException; + CloseableIteration getContextIDs() throws SailException; /** * Gets all statements that have a specific subject, predicate and/or object. All three parameters may be null to @@ -76,7 +76,7 @@ public interface SailDataset extends SailClosable { * @return An iterator over the relevant statements. * @throws SailException If the triple source failed to get the statements. */ - CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException; /** @@ -89,7 +89,7 @@ CloseableIteration getStatements(Resource su * @return An iterator over the relevant triples. * @throws SailException If the triple source failed to get the RDF-star triples. */ - default CloseableIteration getTriples(Resource subj, IRI pred, Value obj) + default CloseableIteration getTriples(Resource subj, IRI pred, Value obj) throws SailException { throw new SailException("RDF-star triple retrieval not supported by this store"); } diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDatasetImpl.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDatasetImpl.java index 476c2c913c1..809aaad7793 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDatasetImpl.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDatasetImpl.java @@ -43,9 +43,9 @@ */ class SailDatasetImpl implements SailDataset { - private static final EmptyIteration TRIPLE_EMPTY_ITERATION = new EmptyIteration<>(); - private static final EmptyIteration NAMESPACES_EMPTY_ITERATION = new EmptyIteration<>(); - private static final EmptyIteration STATEMENT_EMPTY_ITERATION = new EmptyIteration<>(); + private static final EmptyIteration TRIPLE_EMPTY_ITERATION = new EmptyIteration<>(); + private static final EmptyIteration NAMESPACES_EMPTY_ITERATION = new EmptyIteration<>(); + private static final EmptyIteration STATEMENT_EMPTY_ITERATION = new EmptyIteration<>(); /** * {@link SailDataset} of the backing {@link SailSource}. @@ -95,8 +95,8 @@ public String getNamespace(String prefix) throws SailException { } @Override - public CloseableIteration getNamespaces() throws SailException { - final CloseableIteration namespaces; + public CloseableIteration getNamespaces() throws SailException { + final CloseableIteration namespaces; if (changes.isNamespaceCleared()) { namespaces = NAMESPACES_EMPTY_ITERATION; } else { @@ -178,8 +178,8 @@ public void handleClose() throws SailException { } @Override - public CloseableIteration getContextIDs() throws SailException { - final CloseableIteration contextIDs; + public CloseableIteration getContextIDs() throws SailException { + final CloseableIteration contextIDs; contextIDs = derivedFrom.getContextIDs(); Iterator added = null; Set removed = null; @@ -260,10 +260,10 @@ public void handleClose() throws SailException { } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { Set deprecatedContexts = changes.getDeprecatedContexts(); - CloseableIteration iter; + CloseableIteration iter; if (changes.isStatementCleared() || contexts == null && deprecatedContexts != null && deprecatedContexts.contains(null) || contexts != null && contexts.length > 0 && deprecatedContexts != null @@ -298,10 +298,10 @@ public CloseableIteration getStatements(Reso } @Override - public CloseableIteration getTriples(Resource subj, IRI pred, Value obj) + public CloseableIteration getTriples(Resource subj, IRI pred, Value obj) throws SailException { - CloseableIteration iter; + CloseableIteration iter; if (changes.isStatementCleared()) { // nothing in the backing source is relevant, but we may still need to return approved data // from the changeset @@ -316,7 +316,7 @@ public CloseableIteration getTriples(Resource s if (changes.hasApproved()) { if (iter != null) { - CloseableIteratorIteration tripleExceptionCloseableIteratorIteration = new CloseableIteratorIteration<>( + CloseableIteratorIteration tripleExceptionCloseableIteratorIteration = new CloseableIteratorIteration<>( changes.getApprovedTriples(subj, pred, obj).iterator()); // merge newly approved triples in the changeset with data from the backing source @@ -333,9 +333,9 @@ public CloseableIteration getTriples(Resource s } } - private CloseableIteration difference( - CloseableIteration result, Function excluded) { - return new FilterIteration(result) { + private CloseableIteration difference( + CloseableIteration result, Function excluded) { + return new FilterIteration(result) { @Override protected boolean accept(Statement stmt) { @@ -344,9 +344,9 @@ protected boolean accept(Statement stmt) { }; } - private CloseableIteration triplesDifference( - CloseableIteration result, Function excluded) { - return new FilterIteration(result) { + private CloseableIteration triplesDifference( + CloseableIteration result, Function excluded) { + return new FilterIteration(result) { @Override protected boolean accept(Triple stmt) { @@ -358,7 +358,7 @@ protected boolean accept(Triple stmt) { private boolean isDeprecated(Triple triple, List deprecatedStatements) { // the triple is deprecated if the changeset deprecates all existing statements in the backing dataset that // involve this triple. - try (CloseableIteration subjectStatements = derivedFrom + try (CloseableIteration subjectStatements = derivedFrom .getStatements(triple, null, null)) { while (subjectStatements.hasNext()) { Statement st = subjectStatements.next(); @@ -367,7 +367,7 @@ private boolean isDeprecated(Triple triple, List deprecatedStatements } } } - try (CloseableIteration objectStatements = derivedFrom + try (CloseableIteration objectStatements = derivedFrom .getStatements(null, null, triple)) { while (objectStatements.hasNext()) { Statement st = objectStatements.next(); diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDatasetTripleSource.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDatasetTripleSource.java index d5a737bece4..d1b7f48354b 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDatasetTripleSource.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailDatasetTripleSource.java @@ -45,9 +45,9 @@ public String toString() { } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { - CloseableIteration statements = null; + CloseableIteration statements = null; try { statements = dataset.getStatements(subj, pred, obj, contexts); return new TripleSourceIterationWrapper<>(statements); @@ -68,9 +68,9 @@ public ValueFactory getValueFactory() { } @Override - public CloseableIteration getRdfStarTriples(Resource subj, IRI pred, + public CloseableIteration getRdfStarTriples(Resource subj, IRI pred, Value obj) throws QueryEvaluationException { - CloseableIteration triples = null; + CloseableIteration triples = null; TripleSourceIterationWrapper iterationWrapper = null; try { // In contrast to statement retrieval (which gets de-duplicated later on when handling things like diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailSourceConnection.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailSourceConnection.java index 0f6c7a9e6d9..b414b14969a 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailSourceConnection.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/SailSourceConnection.java @@ -213,7 +213,7 @@ protected EvaluationStrategy getEvaluationStrategy(Dataset dataset, TripleSource } @Override - protected CloseableIteration evaluateInternal(TupleExpr tupleExpr, + protected CloseableIteration evaluateInternal(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { logger.trace("Incoming query model:\n{}", tupleExpr); @@ -230,7 +230,7 @@ protected CloseableIteration eva SailSource branch = null; SailDataset rdfDataset = null; - CloseableIteration iteration = null; + CloseableIteration iteration = null; boolean allGood = false; try { branch = branch(IncludeInferred.fromBoolean(includeInferred)); @@ -351,7 +351,7 @@ private boolean runQueryForExplain(TupleExpr tupleExpr, Dataset dataset, Binding try { selfInterruptOnTimeoutThread.start(); - try (CloseableIteration evaluate = evaluate(tupleExpr, + try (CloseableIteration evaluate = evaluate(tupleExpr, dataset, bindings, includeInferred)) { while (evaluate.hasNext()) { if (Thread.interrupted()) { @@ -390,14 +390,14 @@ protected void closeInternal() throws SailException { } @Override - protected CloseableIteration getContextIDsInternal() throws SailException { + protected CloseableIteration getContextIDsInternal() throws SailException { SailSource branch = branch(IncludeInferred.explicitOnly); SailDataset snapshot = branch.dataset(getIsolationLevel()); return SailClosingIteration.makeClosable(snapshot.getContextIDs(), snapshot, branch); } @Override - protected CloseableIteration getStatementsInternal(Resource subj, IRI pred, + protected CloseableIteration getStatementsInternal(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { SailSource branch = branch(IncludeInferred.fromBoolean(includeInferred)); SailDataset snapshot = branch.dataset(getIsolationLevel()); @@ -412,7 +412,7 @@ protected long sizeInternal(Resource... contexts) throws SailException { } @Override - protected CloseableIteration getNamespacesInternal() throws SailException { + protected CloseableIteration getNamespacesInternal() throws SailException { SailSource branch = branch(IncludeInferred.explicitOnly); SailDataset snapshot = branch.dataset(getIsolationLevel()); return SailClosingIteration.makeClosable(snapshot.getNamespaces(), snapshot, branch); @@ -804,7 +804,7 @@ private boolean remove(Resource subj, IRI pred, Value obj, SailDataset dataset, boolean statementsRemoved = false; - try (CloseableIteration iter = dataset.getStatements(subj, pred, obj, + try (CloseableIteration iter = dataset.getStatements(subj, pred, obj, contexts)) { while (iter.hasNext()) { Statement st = iter.next(); @@ -986,8 +986,8 @@ private SailSource branch(IncludeInferred includeinferred) throws SailException } } - private CloseableIteration interlock( - CloseableIteration iter, SailClosable... closes) { + private CloseableIteration interlock( + CloseableIteration iter, SailClosable... closes) { return new SailClosingIteration(iter, closes) { @Override @@ -999,7 +999,7 @@ protected void handleSailException(SailException e) throws QueryEvaluationExcept private boolean hasStatement(SailDataset dataset, Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { - try (CloseableIteration iter = dataset.getStatements(subj, pred, obj, + try (CloseableIteration iter = dataset.getStatements(subj, pred, obj, contexts)) { return iter.hasNext(); } diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/UnionSailDataset.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/UnionSailDataset.java index 87ec83e8549..060ae133e5f 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/UnionSailDataset.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/UnionSailDataset.java @@ -61,10 +61,10 @@ public void close() throws SailException { } @Override - public CloseableIteration getNamespaces() throws SailException { + public CloseableIteration getNamespaces() throws SailException { - CloseableIteration iteration1 = null; - CloseableIteration iteration2 = null; + CloseableIteration iteration1 = null; + CloseableIteration iteration2 = null; try { iteration1 = dataset1.getNamespaces(); iteration2 = dataset2.getNamespaces(); @@ -94,9 +94,9 @@ public String getNamespace(String prefix) throws SailException { } @Override - public CloseableIteration getContextIDs() throws SailException { - CloseableIteration iteration1 = null; - CloseableIteration iteration2 = null; + public CloseableIteration getContextIDs() throws SailException { + CloseableIteration iteration1 = null; + CloseableIteration iteration2 = null; try { iteration1 = dataset1.getContextIDs(); iteration2 = dataset2.getContextIDs(); @@ -116,11 +116,11 @@ public CloseableIteration getContextIDs() thr } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { - CloseableIteration iteration1 = null; - CloseableIteration iteration2 = null; + CloseableIteration iteration1 = null; + CloseableIteration iteration2 = null; try { iteration1 = dataset1.getStatements(subj, pred, obj, contexts); iteration2 = dataset2.getStatements(subj, pred, obj, contexts); @@ -141,11 +141,11 @@ public CloseableIteration getStatements(Reso } @Override - public CloseableIteration getTriples(Resource subj, IRI pred, Value obj) + public CloseableIteration getTriples(Resource subj, IRI pred, Value obj) throws SailException { - CloseableIteration iteration1 = null; - CloseableIteration iteration2 = null; + CloseableIteration iteration1 = null; + CloseableIteration iteration2 = null; try { iteration1 = dataset1.getTriples(subj, pred, obj); iteration2 = dataset2.getTriples(subj, pred, obj); @@ -165,9 +165,9 @@ public CloseableIteration getTriples(Resource s } - private CloseableIteration union( - CloseableIteration iteration1, - CloseableIteration iteration2) { + private CloseableIteration union( + CloseableIteration iteration1, + CloseableIteration iteration2) { return DualUnionIteration.getWildcardInstance(iteration1, iteration2); } diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/config/BaseSailConfig.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/config/BaseSailConfig.java index 0543e644103..379ed8c4162 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/config/BaseSailConfig.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/config/BaseSailConfig.java @@ -28,9 +28,6 @@ public abstract class BaseSailConfig extends AbstractSailImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private String evalStratFactoryClassName; private QueryEvaluationMode defaultQueryEvaluationMode; @@ -65,22 +62,32 @@ public EvaluationStrategyFactory getEvaluationStrategyFactory() throws SailConfi @Override public Resource export(Model graph) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(graph); + } + + Resource implNode = super.export(graph); + + if (evalStratFactoryClassName != null) { + graph.add(implNode, CONFIG.Sail.evaluationStrategyFactory, literal(evalStratFactoryClassName)); + + } + getDefaultQueryEvaluationMode().ifPresent(mode -> { + graph.add(implNode, CONFIG.Sail.defaultQueryEvaluationMode, literal(mode.getValue())); + }); + + return implNode; + } + + private Resource exportLegacy(Model graph) { Resource implNode = super.export(graph); if (evalStratFactoryClassName != null) { - if (USE_CONFIG) { - graph.add(implNode, CONFIG.Sail.evaluationStrategyFactory, literal(evalStratFactoryClassName)); - } else { - graph.add(implNode, EVALUATION_STRATEGY_FACTORY, literal(evalStratFactoryClassName)); - } + graph.add(implNode, EVALUATION_STRATEGY_FACTORY, literal(evalStratFactoryClassName)); } getDefaultQueryEvaluationMode().ifPresent(mode -> { - if (USE_CONFIG) { - graph.add(implNode, CONFIG.Sail.defaultQueryEvaluationMode, literal(mode.getValue())); - } else { - graph.add(implNode, DEFAULT_QUERY_EVALUATION_MODE, literal(mode.getValue())); - } + graph.add(implNode, DEFAULT_QUERY_EVALUATION_MODE, literal(mode.getValue())); }); return implNode; diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/config/BaseSailSchema.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/config/BaseSailSchema.java index af0e1d06953..5b3c5bbdf9e 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/config/BaseSailSchema.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/base/config/BaseSailSchema.java @@ -29,12 +29,12 @@ public class BaseSailSchema { public static final String NAMESPACE = "http://www.openrdf.org/config/sail/base#"; /** - * @deprecated use {@link CONFIG#evaluationStrategyFactory} instead. + * @deprecated use {@link CONFIG.Sail#evaluationStrategyFactory} instead. */ public final static IRI EVALUATION_STRATEGY_FACTORY = iri(NAMESPACE, "evaluationStrategyFactory"); /** - * @deprecated use {@link CONFIG#defaultQueryEvaluationMode} instead. + * @deprecated use {@link CONFIG.Sail#defaultQueryEvaluationMode} instead. */ public final static IRI DEFAULT_QUERY_EVALUATION_MODE = iri(NAMESPACE, "defaultQueryEvaluationMode"); diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/evaluation/SailTripleSource.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/evaluation/SailTripleSource.java index d85ab9426ec..d473224676f 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/evaluation/SailTripleSource.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/evaluation/SailTripleSource.java @@ -37,9 +37,9 @@ public SailTripleSource(SailConnection conn, boolean includeInferred, ValueFacto } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { - CloseableIteration iter = null; + CloseableIteration iter = null; try { iter = conn.getStatements(subj, pred, obj, includeInferred, contexts); return new TripleSourceIterationWrapper(iter); diff --git a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/inferencer/InferencerConnectionWrapper.java b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/inferencer/InferencerConnectionWrapper.java index e152d485001..5ce2f15424b 100644 --- a/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/inferencer/InferencerConnectionWrapper.java +++ b/core/sail/base/src/main/java/org/eclipse/rdf4j/sail/inferencer/InferencerConnectionWrapper.java @@ -17,7 +17,6 @@ import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.helpers.NotifyingSailConnectionWrapper; @@ -103,7 +102,7 @@ public void commit() throws SailException { * Calls {@link #flushUpdates()} before forwarding the call to the wrapped connection. */ @Override - public CloseableIteration evaluate(TupleExpr tupleExpr, + public CloseableIteration evaluate(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { flushUpdates(); return super.evaluate(tupleExpr, dataset, bindings, includeInferred); @@ -113,7 +112,7 @@ public CloseableIteration evalua * Calls {@link #flushUpdates()} before forwarding the call to the wrapped connection. */ @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { flushUpdates(); return super.getContextIDs(); } @@ -129,7 +128,7 @@ public boolean hasStatement(Resource subj, IRI pred, Value obj, boolean includeI * Calls {@link #flushUpdates()} before forwarding the call to the wrapped connection. */ @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { flushUpdates(); return super.getStatements(subj, pred, obj, includeInferred, contexts); diff --git a/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/ChangesetTest.java b/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/ChangesetTest.java index 85a2f9aab80..b20c87a4d39 100644 --- a/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/ChangesetTest.java +++ b/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/ChangesetTest.java @@ -34,7 +34,7 @@ public class ChangesetTest { Resource[] allGraph = {}; @Test - public void testConcurrency() throws InterruptedException, ExecutionException { + public void testConcurrency() { Changeset changeset = getChangeset(); diff --git a/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/SnapshotSailStoreTest.java b/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/SnapshotSailStoreTest.java index d9906aff675..375b91c559b 100644 --- a/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/SnapshotSailStoreTest.java +++ b/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/SnapshotSailStoreTest.java @@ -171,7 +171,7 @@ public void close() throws SailException { } @Override - public CloseableIteration getNamespaces() throws SailException { + public CloseableIteration getNamespaces() throws SailException { return new EmptyIteration<>(); } @@ -181,12 +181,12 @@ public String getNamespace(String prefix) throws SailException { } @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { return new EmptyIteration<>(); } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { return new EmptyIteration<>(); diff --git a/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/config/BaseSailConfigTest.java b/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/config/BaseSailConfigTest.java index c6db324658b..56086ad17f3 100644 --- a/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/config/BaseSailConfigTest.java +++ b/core/sail/base/src/test/java/org/eclipse/rdf4j/sail/base/config/BaseSailConfigTest.java @@ -17,23 +17,26 @@ import org.eclipse.rdf4j.common.transaction.QueryEvaluationMode; import org.eclipse.rdf4j.model.util.ModelBuilder; +import org.eclipse.rdf4j.model.vocabulary.CONFIG; import org.eclipse.rdf4j.sail.config.SailConfigException; import org.junit.jupiter.api.Test; public class BaseSailConfigTest { @Test - public void testParseQueryEvaluationMode() throws Exception { + public void testParseQueryEvaluationMode() { var implNode = bnode(); + // capitalization wrong + var incorrectEvalMode = literal("standard"); + var correctEvalMode = literal("STANDARD"); + { var config = new BaseSailConfig("stub") { }; - // capitalization wrong - var incorrectEvalMode = literal("standard"); var model = new ModelBuilder() - .add(implNode, BaseSailSchema.DEFAULT_QUERY_EVALUATION_MODE, incorrectEvalMode) + .add(implNode, CONFIG.Sail.defaultQueryEvaluationMode, incorrectEvalMode) .build(); assertThatExceptionOfType(SailConfigException.class).isThrownBy(() -> config.parse(model, implNode)); @@ -42,7 +45,18 @@ public void testParseQueryEvaluationMode() throws Exception { { var config = new BaseSailConfig("stub") { }; - var correctEvalMode = literal("STANDARD"); + + var model = new ModelBuilder() + .add(implNode, CONFIG.Sail.defaultQueryEvaluationMode, correctEvalMode) + .build(); + + config.parse(model, implNode); + assertThat(config.getDefaultQueryEvaluationMode()).hasValue(QueryEvaluationMode.STANDARD); + } + + { + var config = new BaseSailConfig("stub") { + }; var model = new ModelBuilder() .add(implNode, BaseSailSchema.DEFAULT_QUERY_EVALUATION_MODE, correctEvalMode) .build(); @@ -51,6 +65,17 @@ public void testParseQueryEvaluationMode() throws Exception { assertThat(config.getDefaultQueryEvaluationMode()).hasValue(QueryEvaluationMode.STANDARD); } + { + var config = new BaseSailConfig("stub") { + }; + var model = new ModelBuilder() + .add(implNode, BaseSailSchema.DEFAULT_QUERY_EVALUATION_MODE, correctEvalMode) + .add(implNode, CONFIG.Sail.defaultQueryEvaluationMode, incorrectEvalMode) + .build(); + + assertThatExceptionOfType(SailConfigException.class).isThrownBy(() -> config.parse(model, implNode)); + } + { var config = new BaseSailConfig("stub") { }; diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchContextStatement.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchContextStatement.java deleted file mode 100644 index 8cc8fd7d4f7..00000000000 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchContextStatement.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.sail.elasticsearchstore; - -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.extensiblestore.valuefactory.ExtensibleContextStatement; - -/** - * @author Håvard Mikkelsen Ottestad - */ -class ElasticsearchContextStatement extends ExtensibleContextStatement implements ElasticsearchId { - - private final String elasticsearchId; - - ElasticsearchContextStatement(String elasticsearchId, Resource subject, IRI predicate, Value object, - Resource context, boolean inferred) { - super(subject, predicate, object, context, inferred); - this.elasticsearchId = elasticsearchId; - } - - @Override - public String getElasticsearchId() { - return elasticsearchId; - } -} diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchDataStructure.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchDataStructure.java index fcf5dd4963e..583d4091f0b 100644 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchDataStructure.java +++ b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchDataStructure.java @@ -162,7 +162,7 @@ public void flushForCommit() { } @Override - public CloseableIteration getStatements(Resource subject, + public CloseableIteration getStatements(Resource subject, IRI predicate, Value object, boolean inferred, Resource... context) { @@ -170,7 +170,7 @@ public CloseableIteration getState return new LookAheadIteration<>() { - final CloseableIteration iterator = ElasticsearchHelper + final CloseableIteration iterator = ElasticsearchHelper .getScrollingIterator(queryBuilder, clientProvider.getClient(), index, scrollTimeout); @Override @@ -584,7 +584,7 @@ public synchronized boolean removeStatementsByQuery(Resource subj, IRI pred, Val // Elasticsearch delete by query is slow. It's still faster when deleting a lot of data. We assume that // getStatement and bulk delete is faster up to 1000 statements. If there are more, then we instead use // elasticsearch delete by query. - try (CloseableIteration statements = getStatements(subj, pred, + try (CloseableIteration statements = getStatements(subj, pred, obj, inferred, contexts)) { List statementsToDelete = new ArrayList<>(); diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchHelper.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchHelper.java index be65aa41235..386db386c93 100644 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchHelper.java +++ b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchHelper.java @@ -24,7 +24,7 @@ class ElasticsearchHelper { - static CloseableIteration getScrollingIterator(QueryBuilder queryBuilder, + static CloseableIteration getScrollingIterator(QueryBuilder queryBuilder, Client client, String index, int scrollTimeout) { return new CloseableIteration<>() { diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchStatement.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchStatement.java index 81641b5e9e1..67d64b4ad34 100644 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchStatement.java +++ b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchStatement.java @@ -22,8 +22,9 @@ class ElasticsearchStatement extends ExtensibleStatementImpl implements Elastics private final String elasticsearchId; - ElasticsearchStatement(String elasticsearchId, Resource subject, IRI predicate, Value object, boolean inferred) { - super(subject, predicate, object, inferred); + ElasticsearchStatement(String elasticsearchId, Resource subject, IRI predicate, Value object, + Resource context, boolean inferred) { + super(subject, predicate, object, context, inferred); this.elasticsearchId = elasticsearchId; } diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchValueFactory.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchValueFactory.java index 1f9660cb7a8..0fa9876f7b6 100644 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchValueFactory.java +++ b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchValueFactory.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; -import org.eclipse.rdf4j.sail.extensiblestore.valuefactory.ExtensibleContextStatement; import org.eclipse.rdf4j.sail.extensiblestore.valuefactory.ExtensibleStatement; import org.eclipse.rdf4j.sail.extensiblestore.valuefactory.ExtensibleStatementHelper; import org.eclipse.rdf4j.sail.extensiblestore.valuefactory.ExtensibleStatementImpl; @@ -47,22 +46,22 @@ private ElasticsearchValueFactory() { } ExtensibleStatement createStatement(Resource subject, IRI predicate, Value object, boolean inferred) { - return new ExtensibleStatementImpl(subject, predicate, object, inferred); + return new ExtensibleStatementImpl(subject, predicate, object, null, inferred); } ExtensibleStatement createStatement(Resource subject, IRI predicate, Value object, Resource context, boolean inferred) { - return new ExtensibleContextStatement(subject, predicate, object, context, inferred); + return new ExtensibleStatementImpl(subject, predicate, object, context, inferred); } ElasticsearchStatement createStatement(String elasticsearchID, Resource subject, IRI predicate, Value object, boolean inferred) { - return new ElasticsearchStatement(elasticsearchID, subject, predicate, object, inferred); + return new ElasticsearchStatement(elasticsearchID, subject, predicate, object, null, inferred); } - ElasticsearchContextStatement createStatement(String elasticsearchID, Resource subject, IRI predicate, Value object, + ElasticsearchStatement createStatement(String elasticsearchID, Resource subject, IRI predicate, Value object, Resource context, boolean inferred) { - return new ElasticsearchContextStatement(elasticsearchID, subject, predicate, object, context, inferred); + return new ElasticsearchStatement(elasticsearchID, subject, predicate, object, context, inferred); } @Override diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/SingletonClientProvider.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/SingletonClientProvider.java index 8abc3687a27..c0c62158ace 100644 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/SingletonClientProvider.java +++ b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/SingletonClientProvider.java @@ -68,7 +68,7 @@ public boolean isClosed() { } @Override - synchronized public void close() throws Exception { + synchronized public void close() { if (!closed) { closed = true; if (client != null) { diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/UnclosableClientProvider.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/UnclosableClientProvider.java index 53c826fd8fb..87ccb6977c3 100644 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/UnclosableClientProvider.java +++ b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/UnclosableClientProvider.java @@ -35,7 +35,7 @@ public boolean isClosed() { } @Override - public void close() throws Exception { + public void close() { logger.debug("Client was provided by user and was not closed."); // no op diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/UserProvidedClientProvider.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/UserProvidedClientProvider.java index be595e2b728..a41e48e8ad8 100644 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/UserProvidedClientProvider.java +++ b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/UserProvidedClientProvider.java @@ -39,7 +39,7 @@ public boolean isClosed() { } @Override - synchronized public void close() throws Exception { + synchronized public void close() { if (!closed) { closed = true; } diff --git a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreConfig.java b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreConfig.java index 907a075ce76..ffe91938b1b 100644 --- a/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreConfig.java +++ b/core/sail/elasticsearch-store/src/main/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreConfig.java @@ -28,9 +28,6 @@ */ public class ElasticsearchStoreConfig extends BaseSailConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private String hostname; private int port = -1; private String clusterName; @@ -42,35 +39,42 @@ public ElasticsearchStoreConfig() { @Override public Resource export(Model m) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(m); + } + + Resource implNode = super.export(m); + + if (hostname != null) { + m.add(implNode, CONFIG.Ess.hostname, literal(hostname)); + } + if (clusterName != null) { + m.add(implNode, CONFIG.Ess.clusterName, literal(clusterName)); + } + if (index != null) { + m.add(implNode, CONFIG.Ess.index, literal(index)); + } + if (port != -1) { + m.add(implNode, CONFIG.Ess.port, literal(port)); + } + + return implNode; + } + + private Resource exportLegacy(Model m) { Resource implNode = super.export(m); if (hostname != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Ess.hostname, literal(hostname)); - } else { - m.add(implNode, ElasticsearchStoreSchema.hostname, literal(hostname)); - } + m.add(implNode, ElasticsearchStoreSchema.hostname, literal(hostname)); } if (clusterName != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Ess.clusterName, literal(clusterName)); - } else { - m.add(implNode, ElasticsearchStoreSchema.clusterName, literal(clusterName)); - } + m.add(implNode, ElasticsearchStoreSchema.clusterName, literal(clusterName)); } if (index != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Ess.index, literal(index)); - } else { - m.add(implNode, ElasticsearchStoreSchema.index, literal(index)); - } + m.add(implNode, ElasticsearchStoreSchema.index, literal(index)); } if (port != -1) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Ess.port, literal(port)); - } else { - m.add(implNode, ElasticsearchStoreSchema.port, literal(port)); - } + m.add(implNode, ElasticsearchStoreSchema.port, literal(port)); } return implNode; diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/AbstractElasticsearchStoreIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/AbstractElasticsearchStoreIT.java index c64925ce851..708e0166d4b 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/AbstractElasticsearchStoreIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/AbstractElasticsearchStoreIT.java @@ -35,7 +35,7 @@ public abstract class AbstractElasticsearchStoreIT { private static final Logger logger = LoggerFactory.getLogger(AbstractElasticsearchStoreIT.class); @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/ClientProviderWithDebugStats.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/ClientProviderWithDebugStats.java index 67e7bca39a5..25f14f807cc 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/ClientProviderWithDebugStats.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/ClientProviderWithDebugStats.java @@ -60,7 +60,7 @@ public boolean isClosed() { } @Override - synchronized public void close() throws Exception { + synchronized public void close() { if (!closed) { closed = true; if (client != null) { diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchStoreTransactionsIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchStoreTransactionsIT.java index c34caa3779c..6a2b5a8a255 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchStoreTransactionsIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/ElasticsearchStoreTransactionsIT.java @@ -14,7 +14,6 @@ import static org.junit.Assert.assertThrows; import java.io.IOException; -import java.net.UnknownHostException; import java.util.Arrays; import java.util.Comparator; import java.util.Date; @@ -57,7 +56,7 @@ public class ElasticsearchStoreTransactionsIT extends AbstractElasticsearchStore private static ElasticsearchStore elasticsearchStore; @BeforeEach - public void before() throws UnknownHostException { + public void before() { elasticsearchStore = new ElasticsearchStore("localhost", TestHelpers.PORT, TestHelpers.CLUSTER, "testindex"); elasticsearchStore.setElasticsearchScrollTimeout(60000); @@ -590,7 +589,7 @@ public void testHashCollision() { // RepositoryException or something like that @Disabled("slow test") @Test - public void testScrollTimeout() throws InterruptedException { + public void testScrollTimeout() { assertThrows(RepositoryException.class, () -> { SailRepository elasticsearchStore = new SailRepository(this.elasticsearchStore); this.elasticsearchStore.setElasticsearchScrollTimeout(1); diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/InferenceIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/InferenceIT.java index 58df65f134f..64300c174cb 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/InferenceIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/InferenceIT.java @@ -15,8 +15,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import java.io.IOException; - import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; @@ -41,7 +39,7 @@ public class InferenceIT extends AbstractElasticsearchStoreIT { private static SingletonClientProvider singletonClientProvider; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); singletonClientProvider = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/AddBenchmark.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/AddBenchmark.java index d3c1ac7ddad..f4f5cb0f0ef 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/AddBenchmark.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/AddBenchmark.java @@ -50,7 +50,7 @@ public class AddBenchmark { private SailRepository elasticsearchStore; @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() { // JMH does not correctly set JAVA_HOME. Change the JAVA_HOME below if you the following error: // [EmbeddedElsHandler] INFO p.a.t.e.ElasticServer - could not find java; set JAVA_HOME or ensure java is in // PATH diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/DeleteBenchmark.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/DeleteBenchmark.java index ea04a572f60..72e8f48d95b 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/DeleteBenchmark.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/DeleteBenchmark.java @@ -54,7 +54,7 @@ public class DeleteBenchmark { private SailRepository elasticsearchStore; @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() { // JMH does not correctly set JAVA_HOME. Change the JAVA_HOME below if you the following error: // [EmbeddedElsHandler] INFO p.a.t.e.ElasticServer - could not find java; set JAVA_HOME or ensure java is in // PATH diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/InitBenchmark.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/InitBenchmark.java index 5e25f73e67d..8cd2e7fedf4 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/InitBenchmark.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/InitBenchmark.java @@ -12,7 +12,6 @@ package org.eclipse.rdf4j.sail.elasticsearchstore.benchmark; import java.io.File; -import java.io.IOException; import java.util.concurrent.TimeUnit; import org.assertj.core.util.Files; @@ -52,7 +51,7 @@ public class InitBenchmark { SingletonClientProvider clientPool; @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() { // JMH does not correctly set JAVA_HOME. Change the JAVA_HOME below if you the following error: // [EmbeddedElsHandler] INFO p.a.t.e.ElasticServer - could not find java; set JAVA_HOME or ensure java is in // PATH diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/QueryBenchmark.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/QueryBenchmark.java index a8e1f856ad0..fbb7019834c 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/QueryBenchmark.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/QueryBenchmark.java @@ -82,7 +82,7 @@ public class QueryBenchmark { private List statementList; @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() throws IOException { // JMH does not correctly set JAVA_HOME. Change the JAVA_HOME below if you the following error: // [EmbeddedElsHandler] INFO p.a.t.e.ElasticServer - could not find java; set JAVA_HOME or ensure java is in // PATH diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/ReadCacheBenchmark.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/ReadCacheBenchmark.java index d874d0057bf..0c73caceae1 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/ReadCacheBenchmark.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/ReadCacheBenchmark.java @@ -72,7 +72,7 @@ public class ReadCacheBenchmark { } @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() throws IOException { // JMH does not correctly set JAVA_HOME. Change the JAVA_HOME below if you the following error: // [EmbeddedElsHandler] INFO p.a.t.e.ElasticServer - could not find java; set JAVA_HOME or ensure java is in // PATH diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/TransactionBenchmark.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/TransactionBenchmark.java index f9aa60c36bc..12e3c3850b2 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/TransactionBenchmark.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/TransactionBenchmark.java @@ -50,7 +50,7 @@ public class TransactionBenchmark { private SailRepository repository; @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() throws IOException { // JMH does not correctly set JAVA_HOME. Change the JAVA_HOME below if you the following error: // [EmbeddedElsHandler] INFO p.a.t.e.ElasticServer - could not find java; set JAVA_HOME or ensure java is in // PATH diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/TransactionParallelBenchmark.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/TransactionParallelBenchmark.java index 759c227cbd8..24898bc08ed 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/TransactionParallelBenchmark.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/benchmark/TransactionParallelBenchmark.java @@ -53,7 +53,7 @@ public class TransactionParallelBenchmark { private SailRepository repository; @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() throws IOException { // JMH does not correctly set JAVA_HOME. Change the JAVA_HOME below if you the following error: // [EmbeddedElsHandler] INFO p.a.t.e.ElasticServer - could not find java; set JAVA_HOME or ensure java is in // PATH diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchGraphQueryResultIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchGraphQueryResultIT.java index c6cc2a37f65..7c0de3a1b54 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchGraphQueryResultIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchGraphQueryResultIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.elasticsearchstore.ElasticsearchStore; @@ -26,7 +24,7 @@ public class ElasticsearchGraphQueryResultIT extends GraphQueryResultTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreConcurrencyIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreConcurrencyIT.java index 63d98987fef..460aec582cc 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreConcurrencyIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreConcurrencyIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.sail.NotifyingSail; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.SailException; @@ -31,7 +29,7 @@ public class ElasticsearchStoreConcurrencyIT extends SailConcurrencyTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreConnectionIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreConnectionIT.java index 9065a99ff71..4e06eba0c6c 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreConnectionIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreConnectionIT.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.common.transaction.IsolationLevel; import org.eclipse.rdf4j.common.transaction.IsolationLevels; @@ -29,7 +28,7 @@ public class ElasticsearchStoreConnectionIT extends RepositoryConnectionTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreContextIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreContextIT.java index 77ed9695f69..5d1ce3862c5 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreContextIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreContextIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.sail.NotifyingSail; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.elasticsearchstore.ElasticsearchStore; @@ -30,7 +28,7 @@ public class ElasticsearchStoreContextIT extends RDFNotifyingStoreTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreIT.java index 1f351e6a9b3..043d9e82361 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.sail.NotifyingSail; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.SailException; @@ -31,7 +29,7 @@ public class ElasticsearchStoreIT extends RDFNotifyingStoreTest { static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreInterruptIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreInterruptIT.java index c756bf01963..94dd45b5628 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreInterruptIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreInterruptIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.sail.NotifyingSail; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.elasticsearchstore.ElasticsearchStore; @@ -31,7 +29,7 @@ public class ElasticsearchStoreInterruptIT extends SailInterruptTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreIsolationLevelIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreIsolationLevelIT.java index d9d7b5769b0..c1397b6cc1a 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreIsolationLevelIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreIsolationLevelIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.sail.NotifyingSail; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.Sail; @@ -32,7 +30,7 @@ public class ElasticsearchStoreIsolationLevelIT extends SailIsolationLevelTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { SailIsolationLevelTest.setUpClass(); TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreRepositoryIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreRepositoryIT.java index e7f2c00a186..899df2fc981 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreRepositoryIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreRepositoryIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.elasticsearchstore.ElasticsearchStore; @@ -27,7 +25,7 @@ public class ElasticsearchStoreRepositoryIT extends RepositoryTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } @@ -47,7 +45,7 @@ protected Repository createRepository() { @Disabled @Override - public void testShutdownFollowedByInit() throws Exception { + public void testShutdownFollowedByInit() { // ignore test } } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreSparqlOrderByIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreSparqlOrderByIT.java index 3f2e88d2b2c..6cc77af2105 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreSparqlOrderByIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreSparqlOrderByIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.elasticsearchstore.ElasticsearchStore; @@ -26,7 +24,7 @@ public class ElasticsearchStoreSparqlOrderByIT extends SparqlOrderByTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } @@ -38,7 +36,7 @@ public static void afterClass() throws Exception { } @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { SailRepository sailRepository = new SailRepository( new ElasticsearchStore(clientPool, "index1")); return sailRepository; diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreSparqlRegexIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreSparqlRegexIT.java index 6b81f435ee6..3337a7438d6 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreSparqlRegexIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreSparqlRegexIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.elasticsearchstore.ElasticsearchStore; @@ -26,7 +24,7 @@ public class ElasticsearchStoreSparqlRegexIT extends SparqlRegexTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } @@ -38,7 +36,7 @@ public static void afterClass() throws Exception { } @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { SailRepository sailRepository = new SailRepository( new ElasticsearchStore(clientPool, "index1")); return sailRepository; diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreTupleQueryResultIT.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreTupleQueryResultIT.java index e3876839f19..227510ab985 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreTupleQueryResultIT.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/compliance/ElasticsearchStoreTupleQueryResultIT.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.elasticsearchstore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.elasticsearchstore.ElasticsearchStore; @@ -26,7 +24,7 @@ public class ElasticsearchStoreTupleQueryResultIT extends TupleQueryResultTest { private static SingletonClientProvider clientPool; @BeforeAll - public static void beforeClass() throws IOException, InterruptedException { + public static void beforeClass() { TestHelpers.openClient(); clientPool = new SingletonClientProvider("localhost", TestHelpers.PORT, TestHelpers.CLUSTER); } @@ -38,7 +36,7 @@ public static void afterClass() throws Exception { } @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { SailRepository sailRepository = new SailRepository(new ElasticsearchStore(clientPool, "index1")); return sailRepository; } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreConfigTest.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreConfigTest.java index b0fa88cd078..2f2f1d07dd8 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreConfigTest.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreConfigTest.java @@ -19,6 +19,7 @@ import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.impl.TreeModel; import org.eclipse.rdf4j.model.util.ModelBuilder; +import org.eclipse.rdf4j.model.vocabulary.CONFIG; import org.eclipse.rdf4j.sail.config.SailConfigException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -32,7 +33,7 @@ public class ElasticsearchStoreConfigTest { private ModelBuilder mb; @BeforeEach - public void setUp() throws Exception { + public void setUp() { subject = new ElasticsearchStoreConfig(); implNode = SimpleValueFactory.getInstance().createBNode(); mb = new ModelBuilder().subject(implNode); @@ -50,14 +51,10 @@ public void defaultsCorrectlySet() { @Test public void parseFromModelSetValuesCorrectly() { - // FIXME we need to set formatting guidelines for this kind of thing - // @formatter:off - mb - .add(ElasticsearchStoreSchema.hostname, "host1") + mb.add(ElasticsearchStoreSchema.hostname, "host1") .add(ElasticsearchStoreSchema.clusterName, "cluster1") .add(ElasticsearchStoreSchema.index, "index1") .add(ElasticsearchStoreSchema.port, 9300); - // @formatter:on subject.parse(mb.build(), implNode); @@ -70,8 +67,7 @@ public void parseFromModelSetValuesCorrectly() { @Test public void parseFromPartialModelSetValuesCorrectly() { - mb - .add(ElasticsearchStoreSchema.hostname, "host1") + mb.add(ElasticsearchStoreSchema.hostname, "host1") .add(ElasticsearchStoreSchema.port, 9300); subject.parse(mb.build(), implNode); @@ -83,8 +79,7 @@ public void parseFromPartialModelSetValuesCorrectly() { @Test public void parseInvalidModelGivesCorrectException() { - mb - .add(ElasticsearchStoreSchema.port, "port1"); + mb.add(ElasticsearchStoreSchema.port, "port1"); assertThrows(SailConfigException.class, () -> subject.parse(mb.build(), implNode)); @@ -93,22 +88,20 @@ public void parseInvalidModelGivesCorrectException() { @Test public void exportAddsAllConfigData() { - mb - .add(ElasticsearchStoreSchema.hostname, "host1") + mb.add(ElasticsearchStoreSchema.hostname, "host1") .add(ElasticsearchStoreSchema.clusterName, "cluster1") .add(ElasticsearchStoreSchema.index, "index1") .add(ElasticsearchStoreSchema.port, 9300); - // @formatter:on subject.parse(mb.build(), implNode); Model m = new TreeModel(); Resource node = subject.export(m); - assertThat(m.contains(node, ElasticsearchStoreSchema.hostname, null)).isTrue(); - assertThat(m.contains(node, ElasticsearchStoreSchema.clusterName, null)).isTrue(); - assertThat(m.contains(node, ElasticsearchStoreSchema.index, null)).isTrue(); - assertThat(m.contains(node, ElasticsearchStoreSchema.port, null)).isTrue(); + assertThat(m.contains(node, CONFIG.Ess.hostname, null)).isTrue(); + assertThat(m.contains(node, CONFIG.Ess.clusterName, null)).isTrue(); + assertThat(m.contains(node, CONFIG.Ess.index, null)).isTrue(); + assertThat(m.contains(node, CONFIG.Ess.port, null)).isTrue(); } diff --git a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreFactoryTest.java b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreFactoryTest.java index fb4e0b1ea43..520e706dec3 100644 --- a/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreFactoryTest.java +++ b/core/sail/elasticsearch-store/src/test/java/org/eclipse/rdf4j/sail/elasticsearchstore/config/ElasticsearchStoreFactoryTest.java @@ -23,7 +23,7 @@ public class ElasticsearchStoreFactoryTest { private ElasticsearchStoreFactory subject; @BeforeEach - public void setUp() throws Exception { + public void setUp() { subject = new ElasticsearchStoreFactory(); } diff --git a/core/sail/elasticsearch/src/main/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchBulkUpdater.java b/core/sail/elasticsearch/src/main/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchBulkUpdater.java index f1331c6bc4e..83b2ec4c3f3 100644 --- a/core/sail/elasticsearch/src/main/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchBulkUpdater.java +++ b/core/sail/elasticsearch/src/main/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchBulkUpdater.java @@ -30,14 +30,14 @@ public ElasticsearchBulkUpdater(Client client) { } @Override - public void add(SearchDocument doc) throws IOException { + public void add(SearchDocument doc) { ElasticsearchDocument esDoc = (ElasticsearchDocument) doc; bulkRequest.add( client.prepareIndex(esDoc.getIndex(), esDoc.getType(), esDoc.getId()).setSource(esDoc.getSource())); } @Override - public void update(SearchDocument doc) throws IOException { + public void update(SearchDocument doc) { ElasticsearchDocument esDoc = (ElasticsearchDocument) doc; bulkRequest.add(client.prepareUpdate(esDoc.getIndex(), esDoc.getType(), esDoc.getId()) .setIfSeqNo(esDoc.getSeqNo()) @@ -46,7 +46,7 @@ public void update(SearchDocument doc) throws IOException { } @Override - public void delete(SearchDocument doc) throws IOException { + public void delete(SearchDocument doc) { ElasticsearchDocument esDoc = (ElasticsearchDocument) doc; bulkRequest.add( client.prepareDelete(esDoc.getIndex(), esDoc.getType(), esDoc.getId()) diff --git a/core/sail/elasticsearch/src/main/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchQuery.java b/core/sail/elasticsearch/src/main/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchQuery.java deleted file mode 100644 index fd77d4b933d..00000000000 --- a/core/sail/elasticsearch/src/main/java/org/eclipse/rdf4j/sail/elasticsearch/ElasticsearchQuery.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.sail.elasticsearch; - -import java.io.IOException; - -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.sail.lucene.DocumentScore; -import org.eclipse.rdf4j.sail.lucene.SearchFields; -import org.eclipse.rdf4j.sail.lucene.SearchQuery; -import org.elasticsearch.action.search.SearchRequestBuilder; -import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.search.SearchHit; -import org.elasticsearch.search.SearchHits; -import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -/** - * To be removed, no longer used. - */ -@Deprecated(forRemoval = true) -public class ElasticsearchQuery implements SearchQuery { - - private final SearchRequestBuilder request; - - private final QueryBuilder qb; - - private final ElasticsearchIndex index; - - public ElasticsearchQuery(SearchRequestBuilder request, QueryBuilder qb, ElasticsearchIndex index) { - this.request = request; - this.qb = qb; - this.index = index; - } - - @Override - public Iterable query(Resource resource) throws IOException { - SearchHits hits; - if (resource != null) { - hits = index.search(resource, request, qb); - } else { - hits = index.search(request, qb); - } - return Iterables.transform(hits, new Function<>() { - - @Override - public DocumentScore apply(SearchHit hit) { - return new ElasticsearchDocumentScore(hit, null); - } - }); - } - - /** - * Highlights the given field or all fields if null. - */ - @Override - public void highlight(IRI property) { - String field = (property != null) - ? ElasticsearchIndex.toPropertyFieldName(SearchFields.getPropertyField(property)) - : ElasticsearchIndex.ALL_PROPERTY_FIELDS; - HighlightBuilder hb = new HighlightBuilder(); - hb.field(field); - hb.preTags(SearchFields.HIGHLIGHTER_PRE_TAG); - hb.postTags(SearchFields.HIGHLIGHTER_POST_TAG); - // Elastic Search doesn't really have the same support for fragments as Lucene. - // So, we have to get back the whole highlighted value (comma-separated if it is a list) - // and then post-process it into fragments ourselves. - hb.numOfFragments(0); - request.highlighter(hb); - } -} diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/DataStructureInterface.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/DataStructureInterface.java index 381f4967c10..c78c7fbfa80 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/DataStructureInterface.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/DataStructureInterface.java @@ -17,7 +17,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.extensiblestore.valuefactory.ExtensibleStatement; /** @@ -44,7 +43,7 @@ default void removeStatement(Collection statements) { } } - CloseableIteration getStatements( + CloseableIteration getStatements( Resource subject, IRI predicate, Value object, @@ -57,7 +56,7 @@ CloseableIteration getStatements( void init(); default void clear(boolean inferred, Resource[] contexts) { - try (CloseableIteration statements = getStatements(null, null, + try (CloseableIteration statements = getStatements(null, null, null, inferred, contexts)) { while (statements.hasNext()) { @@ -72,7 +71,7 @@ default void clear(boolean inferred, Resource[] contexts) { default boolean removeStatementsByQuery(Resource subj, IRI pred, Value obj, boolean inferred, Resource[] contexts) { boolean deleted = false; - try (CloseableIteration statements = getStatements(subj, pred, + try (CloseableIteration statements = getStatements(subj, pred, obj, inferred, contexts)) { while (statements.hasNext()) { diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/EagerReadCache.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/EagerReadCache.java index 114b0a33520..bc6247d1360 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/EagerReadCache.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/EagerReadCache.java @@ -60,7 +60,7 @@ public void removeStatement(ExtensibleStatement statement) { } @Override - public CloseableIteration getStatements(Resource subject, + public CloseableIteration getStatements(Resource subject, IRI predicate, Value object, boolean inferred, Resource... context) { Model cache = this.cache; diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleSailSource.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleSailSource.java index 4941b612ea9..0be1e79521d 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleSailSource.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleSailSource.java @@ -147,15 +147,15 @@ public String getNamespace(String prefix) throws SailException { } @Override - public CloseableIteration getNamespaces() { + public CloseableIteration getNamespaces() { return new CloseableIteratorIteration<>(namespaceStore.iterator()); // return new EmptyIteration<>(); } @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { return new CloseableIteration<>() { - final CloseableIteration statements = getStatements(null, null, + final CloseableIteration statements = getStatements(null, null, null); final Set contexts = new HashSet<>(); @@ -210,7 +210,7 @@ public void close() { } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { return dataStructure.getStatements(subj, pred, obj, inferred, contexts); } diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleSailStore.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleSailStore.java index eabc096036a..8f2f43158ca 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleSailStore.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleSailStore.java @@ -120,7 +120,7 @@ private void startRecalculateStatistics() { } private void addToStats(DynamicStatistics instance, - CloseableIteration statements) { + CloseableIteration statements) { long estimatedSize = dataStructure.getEstimatedSize(); diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleStoreConnection.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleStoreConnection.java index 1b005857570..b599d07a97d 100755 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleStoreConnection.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ExtensibleStoreConnection.java @@ -32,7 +32,6 @@ protected ExtensibleStoreConnection(E sail) { super(sail, sail.getSailStore(), sail.getEvaluationStrategyFactory()); this.sail = sail; sailChangedEvent = new DefaultSailChangedEvent(sail); - useConnectionLock = false; } public E getSail() { diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/FilteringIteration.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/FilteringIteration.java index 273e62300f3..741cc8e1cfd 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/FilteringIteration.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/FilteringIteration.java @@ -24,16 +24,16 @@ * IRI predicate, Value object, Resource... context). */ @Experimental -public class FilteringIteration extends LookAheadIteration { +public class FilteringIteration extends LookAheadIteration { - private final CloseableIteration wrappedIteration; + private final CloseableIteration wrappedIteration; private final Resource subject; private final IRI predicate; private final Value object; private final boolean inferred; private final Resource[] context; - public FilteringIteration(CloseableIteration wrappedIteration, Resource subject, IRI predicate, Value object, + public FilteringIteration(CloseableIteration wrappedIteration, Resource subject, IRI predicate, Value object, boolean inferred, Resource... context) { this.wrappedIteration = wrappedIteration; this.subject = subject; @@ -44,7 +44,7 @@ public FilteringIteration(CloseableIteration wrappedIteration, Resource su } @Override - protected E getNextElement() throws X { + protected E getNextElement() { while (wrappedIteration.hasNext()) { E next = wrappedIteration.next(); @@ -75,7 +75,7 @@ protected E getNextElement() throws X { } @Override - protected void handleClose() throws X { + protected void handleClose() { try { super.handleClose(); } finally { diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/LazyReadCache.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/LazyReadCache.java index 19d007559ad..e2da5a3ece4 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/LazyReadCache.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/LazyReadCache.java @@ -62,12 +62,12 @@ public void removeStatement(ExtensibleStatement statement) { } @Override - public CloseableIteration getStatements(Resource subject, + public CloseableIteration getStatements(Resource subject, IRI predicate, Value object, boolean inferred, Resource... context) { PartialStatement partialStatement = new PartialStatement(subject, predicate, object, inferred, context); - CloseableIteration cached = getCached(partialStatement); + CloseableIteration cached = getCached(partialStatement); if (cached != null) { logger.trace("cache hit"); return cached; @@ -77,7 +77,7 @@ public CloseableIteration getState return new CloseableIteration<>() { - final CloseableIteration statements = delegate.getStatements( + final CloseableIteration statements = delegate.getStatements( subject, predicate, object, inferred, context); List cache = new ArrayList<>(); @@ -122,7 +122,7 @@ public void close() throws SailException { } - synchronized private CloseableIteration getCached( + synchronized private CloseableIteration getCached( PartialStatement partialStatement) { List statements = cache.getIfPresent(partialStatement); diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ReadCommittedWrapper.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ReadCommittedWrapper.java index 04ab9dad29b..3fe7d747ba0 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ReadCommittedWrapper.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/ReadCommittedWrapper.java @@ -59,7 +59,7 @@ public void removeStatement(ExtensibleStatement statement) { } @Override - public CloseableIteration getStatements(Resource subject, + public CloseableIteration getStatements(Resource subject, IRI predicate, Value object, boolean inferred, Resource... context) { // must match single statement @@ -116,7 +116,7 @@ public CloseableIteration getState }) .iterator(); - final CloseableIteration right = dataStructure + final CloseableIteration right = dataStructure .getStatements( subject, predicate, object, inferred, context); diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/evaluationstatistics/EvaluationStatisticsWrapper.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/evaluationstatistics/EvaluationStatisticsWrapper.java index 8a39cad43ed..117770c998a 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/evaluationstatistics/EvaluationStatisticsWrapper.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/evaluationstatistics/EvaluationStatisticsWrapper.java @@ -17,7 +17,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.extensiblestore.DataStructureInterface; import org.eclipse.rdf4j.sail.extensiblestore.valuefactory.ExtensibleStatement; @@ -50,7 +49,7 @@ public void removeStatement(ExtensibleStatement statement) { } @Override - public CloseableIteration getStatements(Resource subject, + public CloseableIteration getStatements(Resource subject, IRI predicate, Value object, boolean inferred, Resource... context) { return delegate.getStatements(subject, predicate, object, inferred, context); diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleContextStatement.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleContextStatement.java deleted file mode 100644 index 1657bff4708..00000000000 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleContextStatement.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.sail.extensiblestore.valuefactory; - -import java.util.Objects; - -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.impl.ContextStatement; - -public class ExtensibleContextStatement extends ContextStatement implements ExtensibleStatement { - final boolean inferred; - - /** - * Creates a new Statement with the supplied subject, predicate and object for the specified associated context. - * - * @param subject The statement's subject, must not be null. - * @param predicate The statement's predicate, must not be null. - * @param object The statement's object, must not be null. - * @param context The statement's context, null to indicate no context is associated. - */ - public ExtensibleContextStatement(Resource subject, IRI predicate, Value object, Resource context, - boolean inferred) { - super(subject, predicate, object, context); - this.inferred = inferred; - } - - @Override - public boolean isInferred() { - return inferred; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof ExtensibleContextStatement)) { - return false; - } - if (!super.equals(o)) { - return false; - } - ExtensibleContextStatement that = (ExtensibleContextStatement) o; - return inferred == that.inferred; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), inferred); - } - -} diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleStatementHelper.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleStatementHelper.java index 7644ba23ebe..89dcba4980c 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleStatementHelper.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleStatementHelper.java @@ -31,13 +31,8 @@ public ExtensibleStatement fromStatement(Statement statement, boolean inferred) return (ExtensibleStatement) statement; } - if (statement.getContext() != null) { - return new ExtensibleContextStatement(statement.getSubject(), statement.getPredicate(), - statement.getObject(), statement.getContext(), inferred); - } - return new ExtensibleStatementImpl(statement.getSubject(), statement.getPredicate(), statement.getObject(), - inferred); + statement.getContext(), inferred); } } diff --git a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleStatementImpl.java b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleStatementImpl.java index 58ef4988aa3..b3f8ac04eb7 100644 --- a/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleStatementImpl.java +++ b/core/sail/extensible-store/src/main/java/org/eclipse/rdf4j/sail/extensiblestore/valuefactory/ExtensibleStatementImpl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Eclipse RDF4J contributors. + * Copyright (c) 2023 Eclipse RDF4J contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 @@ -7,7 +7,7 @@ * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ + ******************************************************************************/ package org.eclipse.rdf4j.sail.extensiblestore.valuefactory; import java.util.Objects; @@ -15,28 +15,23 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.impl.SimpleStatement; -import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.eclipse.rdf4j.model.impl.GenericStatement; -public class ExtensibleStatementImpl extends SimpleStatement implements ExtensibleStatement { +public class ExtensibleStatementImpl extends GenericStatement implements ExtensibleStatement { private final boolean inferred; /** - * Creates a new Statement with the supplied subject, predicate and object. * - *

- * Note that creating SimpleStatement objects directly via this constructor is not the recommended approach. - * Instead, use a {@link ValueFactory ValueFactory} (obtained from your repository or by using - * {@link SimpleValueFactory#getInstance()}) to create new Statement objects. + * Creates a new Statement with the supplied subject, predicate and object for the specified associated context. * * @param subject The statement's subject, must not be null. * @param predicate The statement's predicate, must not be null. * @param object The statement's object, must not be null. - * @see SimpleValueFactory#createStatement(Resource, IRI, Value) + * @param context The statement's context, null to indicate no context is associated. */ - public ExtensibleStatementImpl(Resource subject, IRI predicate, Value object, boolean inferred) { - super(subject, predicate, object); + public ExtensibleStatementImpl(Resource subject, IRI predicate, Value object, Resource context, + boolean inferred) { + super(subject, predicate, object, context); this.inferred = inferred; } @@ -64,4 +59,5 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(super.hashCode(), inferred); } + } diff --git a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/NaiveHashSetDataStructure.java b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/NaiveHashSetDataStructure.java index bc1000c9dce..eeac425ed01 100644 --- a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/NaiveHashSetDataStructure.java +++ b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/NaiveHashSetDataStructure.java @@ -19,7 +19,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.extensiblestore.valuefactory.ExtensibleStatement; public class NaiveHashSetDataStructure implements DataStructureInterface { @@ -39,7 +38,7 @@ synchronized public void removeStatement(ExtensibleStatement statement) { } @Override - synchronized public CloseableIteration getStatements(Resource subject, + synchronized public CloseableIteration getStatements(Resource subject, IRI predicate, Value object, boolean inferred, Resource... context) { return new FilteringIteration<>( diff --git a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/benchmark/ExtensibleDynamicEvaluationStatisticsBenchmark.java b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/benchmark/ExtensibleDynamicEvaluationStatisticsBenchmark.java index a9bc918086c..fd5fc650850 100644 --- a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/benchmark/ExtensibleDynamicEvaluationStatisticsBenchmark.java +++ b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/benchmark/ExtensibleDynamicEvaluationStatisticsBenchmark.java @@ -61,7 +61,7 @@ public static void main(String[] args) throws RunnerException { } @Setup(Level.Iteration) - public void beforeClassIteration() throws IOException, InterruptedException { + public void beforeClassIteration() throws InterruptedException { System.gc(); Thread.sleep(100); @@ -71,7 +71,7 @@ public void beforeClassIteration() throws IOException, InterruptedException { } @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() throws IOException { parse = Rio.parse(getResourceAsStream("bsbm-100.ttl"), "", RDFFormat.TURTLE); System.gc(); @@ -83,7 +83,7 @@ private static InputStream getResourceAsStream(String name) { } @Benchmark - public ExtensibleDynamicEvaluationStatistics addStatements() throws IOException, InterruptedException { + public ExtensibleDynamicEvaluationStatistics addStatements() throws InterruptedException { ExtensibleDynamicEvaluationStatistics extensibleDynamicEvaluationStatistics = new ExtensibleDynamicEvaluationStatistics( null); @@ -96,7 +96,7 @@ public ExtensibleDynamicEvaluationStatistics addStatements() throws IOException, } @Benchmark - public ExtensibleDynamicEvaluationStatistics instantiate() throws IOException { + public ExtensibleDynamicEvaluationStatistics instantiate() { ExtensibleDynamicEvaluationStatistics extensibleDynamicEvaluationStatistics = new ExtensibleDynamicEvaluationStatistics( null); diff --git a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/benchmark/ExtensibleDynamicEvaluationStatisticsLowMemBenchmark.java b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/benchmark/ExtensibleDynamicEvaluationStatisticsLowMemBenchmark.java index b627187d59d..a9d7d9dbab9 100644 --- a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/benchmark/ExtensibleDynamicEvaluationStatisticsLowMemBenchmark.java +++ b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/benchmark/ExtensibleDynamicEvaluationStatisticsLowMemBenchmark.java @@ -63,7 +63,7 @@ public static void main(String[] args) throws RunnerException { } @Setup(Level.Iteration) - public void beforeClassIteration() throws IOException, InterruptedException { + public void beforeClassIteration() throws InterruptedException { System.gc(); Thread.sleep(100); diff --git a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreSparqlOrderByTest.java b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreSparqlOrderByTest.java index e9d68650d7b..1d91cf3a5be 100644 --- a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreSparqlOrderByTest.java +++ b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreSparqlOrderByTest.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.extensiblestore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.extensiblestore.ExtensibleStoreImplForTests; @@ -20,7 +18,7 @@ public class ExtensibleStoreSparqlOrderByTest extends SparqlOrderByTest { @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new ExtensibleStoreImplForTests()); } diff --git a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreSparqlRegexTest.java b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreSparqlRegexTest.java index e0c034af8a1..f91c6fadd06 100644 --- a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreSparqlRegexTest.java +++ b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreSparqlRegexTest.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.extensiblestore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.extensiblestore.ExtensibleStoreImplForTests; @@ -20,7 +18,7 @@ public class ExtensibleStoreSparqlRegexTest extends SparqlRegexTest { @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new ExtensibleStoreImplForTests()); } diff --git a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreTupleQueryResultTest.java b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreTupleQueryResultTest.java index 314767ebc77..3a0379573d5 100644 --- a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreTupleQueryResultTest.java +++ b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/compliance/ExtensibleStoreTupleQueryResultTest.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.extensiblestore.compliance; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.extensiblestore.ExtensibleStoreImplForTests; @@ -20,7 +18,7 @@ public class ExtensibleStoreTupleQueryResultTest extends TupleQueryResultTest { @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new ExtensibleStoreImplForTests()); } diff --git a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/evaluationstatistics/EvaluationStatisticsTest.java b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/evaluationstatistics/EvaluationStatisticsTest.java index 47f7154651c..640ba7c79b1 100644 --- a/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/evaluationstatistics/EvaluationStatisticsTest.java +++ b/core/sail/extensible-store/src/test/java/org/eclipse/rdf4j/sail/extensiblestore/evaluationstatistics/EvaluationStatisticsTest.java @@ -129,28 +129,28 @@ public void testAcurracy() throws InterruptedException { new Var("b", RDF.TYPE), new Var("c", bdbmProductType)); - checkPattern(cardinalityCalculator, null_rdfType_bsbmProductType, 1); + checkPattern(cardinalityCalculator, null_rdfType_bsbmProductType, 5); StatementPattern null_null_null = new StatementPattern( new Var("a", null), new Var("b", null), new Var("c", null)); - checkPattern(cardinalityCalculator, null_null_null, 1); + checkPattern(cardinalityCalculator, null_null_null, 5); StatementPattern null_rdfType_null = new StatementPattern( new Var("a", null), new Var("b", RDF.TYPE), new Var("c", null)); - checkPattern(cardinalityCalculator, null_rdfType_null, 1); + checkPattern(cardinalityCalculator, null_rdfType_null, 5); StatementPattern nonExistent = new StatementPattern( new Var("a", null), new Var("b", vf.createIRI("http://example.com/fhjerhf2uhfjkdsbf32o")), new Var("c", null)); - checkPattern(cardinalityCalculator, nonExistent, 1); + checkPattern(cardinalityCalculator, nonExistent, 5); // this last pattern isn't very accurate, it's actually 46 statements, but the estimate is 100.4 StatementPattern bsbmProductType_null_null = new StatementPattern( diff --git a/core/sail/inferencer/pom.xml b/core/sail/inferencer/pom.xml index f286564799b..65e703e294b 100644 --- a/core/sail/inferencer/pom.xml +++ b/core/sail/inferencer/pom.xml @@ -90,12 +90,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/CustomGraphQueryInferencer.java b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/CustomGraphQueryInferencer.java index b2db704360b..79100c230b7 100644 --- a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/CustomGraphQueryInferencer.java +++ b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/CustomGraphQueryInferencer.java @@ -272,7 +272,7 @@ private void buildDeltaSets(Collection forRemoval, Collection statements) throws SailException, RDFHandlerException, QueryEvaluationException { - try (CloseableIteration bindingsIter = getWrappedConnection() + try (CloseableIteration bindingsIter = getWrappedConnection() .evaluate(query.getTupleExpr(), null, EmptyBindingSet.getInstance(), true)) { ValueFactory factory = getValueFactory(); while (bindingsIter.hasNext()) { diff --git a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/DirectTypeHierarchyInferencer.java b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/DirectTypeHierarchyInferencer.java index 380a78b033f..1eb92214ac9 100644 --- a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/DirectTypeHierarchyInferencer.java +++ b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/DirectTypeHierarchyInferencer.java @@ -261,7 +261,7 @@ public void flushUpdates() throws SailException { private void evaluateIntoStatements(ParsedGraphQuery query, Collection statements) throws SailException, RDFHandlerException, QueryEvaluationException { - try (CloseableIteration bindingsIter = getWrappedConnection() + try (CloseableIteration bindingsIter = getWrappedConnection() .evaluate(query.getTupleExpr(), null, EmptyBindingSet.getInstance(), true)) { ValueFactory vf = getValueFactory(); diff --git a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/ForwardChainingRDFSInferencerConnection.java b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/ForwardChainingRDFSInferencerConnection.java index 522c3a75961..3f393a10d7e 100644 --- a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/ForwardChainingRDFSInferencerConnection.java +++ b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/ForwardChainingRDFSInferencerConnection.java @@ -336,7 +336,7 @@ private int applyRuleRdfs2_1() throws SailException { Resource xxx = nt.getSubject(); IRI aaa = nt.getPredicate(); - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(aaa, RDFS.DOMAIN, null, true); while (t1Iter.hasNext()) { @@ -367,7 +367,7 @@ private int applyRuleRdfs2_2() throws SailException { Value zzz = nt.getObject(); if (aaa instanceof IRI && zzz instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(null, (IRI) aaa, null, true); while (t1Iter.hasNext()) { @@ -397,7 +397,7 @@ private int applyRuleRdfs3_1() throws SailException { Value uuu = nt.getObject(); if (uuu instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(aaa, RDFS.RANGE, null, true); while (t1Iter.hasNext()) { @@ -428,7 +428,7 @@ private int applyRuleRdfs3_2() throws SailException { Value zzz = nt.getObject(); if (aaa instanceof IRI && zzz instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(null, (IRI) aaa, null, true); while (t1Iter.hasNext()) { @@ -497,7 +497,7 @@ private int applyRuleRdfs5_1() throws SailException { Value bbb = nt.getObject(); if (bbb instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements((Resource) bbb, RDFS.SUBPROPERTYOF, null, true); while (t1Iter.hasNext()) { @@ -531,7 +531,7 @@ private int applyRuleRdfs5_2() throws SailException { Value ccc = nt.getObject(); if (ccc instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(null, RDFS.SUBPROPERTYOF, bbb, true); while (t1Iter.hasNext()) { @@ -578,7 +578,7 @@ private int applyRuleRdfs7_1() throws SailException { IRI aaa = nt.getPredicate(); Value yyy = nt.getObject(); - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(aaa, RDFS.SUBPROPERTYOF, null, true); while (t1Iter.hasNext()) { @@ -609,7 +609,7 @@ private int applyRuleRdfs7_2() throws SailException { Value bbb = nt.getObject(); if (aaa instanceof IRI && bbb instanceof IRI) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(null, (IRI) aaa, null, true); while (t1Iter.hasNext()) { @@ -659,7 +659,7 @@ private int applyRuleRdfs9_1() throws SailException { Value yyy = nt.getObject(); if (yyy instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(null, RDF.TYPE, xxx, true); while (t1Iter.hasNext()) { @@ -690,7 +690,7 @@ private int applyRuleRdfs9_2() throws SailException { Value xxx = nt.getObject(); if (xxx instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements((Resource) xxx, RDFS.SUBCLASSOF, null, true); while (t1Iter.hasNext()) { @@ -742,7 +742,7 @@ private int applyRuleRdfs11_1() throws SailException { Value yyy = nt.getObject(); if (yyy instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements((Resource) yyy, RDFS.SUBCLASSOF, null, true); while (t1Iter.hasNext()) { @@ -776,7 +776,7 @@ private int applyRuleRdfs11_2() throws SailException { Value zzz = nt.getObject(); if (zzz instanceof Resource) { - CloseableIteration t1Iter; + CloseableIteration t1Iter; t1Iter = getWrappedConnection().getStatements(null, RDFS.SUBCLASSOF, yyy, true); while (t1Iter.hasNext()) { diff --git a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerConnection.java b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerConnection.java index b09ce2027ea..95b1df1e955 100644 --- a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerConnection.java +++ b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerConnection.java @@ -162,7 +162,7 @@ void doInferencing() throws SailException { logger.debug("Forward chain all explicit statements"); long count = 0; - try (CloseableIteration statements = connection.getStatements(null, null, + try (CloseableIteration statements = connection.getStatements(null, null, null, false)) { while (statements.hasNext()) { Statement next = statements.next(); @@ -187,7 +187,7 @@ private void regenerateCacheAndInferenceMaps(boolean addInferredStatements) { addAxiomStatements(); } - try (CloseableIteration statements = connection.getStatements(null, null, + try (CloseableIteration statements = connection.getStatements(null, null, null, sail.useInferredToCreateSchema)) { while (statements.hasNext()) { Statement next = statements.next(); diff --git a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/config/CustomGraphQueryInferencerConfig.java b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/config/CustomGraphQueryInferencerConfig.java index 9294cf13ab0..52f5b20c3e7 100644 --- a/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/config/CustomGraphQueryInferencerConfig.java +++ b/core/sail/inferencer/src/main/java/org/eclipse/rdf4j/sail/inferencer/fc/config/CustomGraphQueryInferencerConfig.java @@ -46,9 +46,6 @@ */ public final class CustomGraphQueryInferencerConfig extends AbstractDelegatingSailImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - public static final Pattern SPARQL_PATTERN; static { @@ -164,23 +161,10 @@ public void validate() throws SailConfigException { public Resource export(Model m) { Resource implNode = super.export(m); if (null != language) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Cgqi.queryLanguage, literal(language.getName())); - } else { - m.add(implNode, QUERY_LANGUAGE, literal(language.getName())); - } - } - if (USE_CONFIG) { - addQueryNode(m, implNode, CONFIG.Cgqi.ruleQuery, ruleQuery); - } else { - addQueryNode(m, implNode, RULE_QUERY, ruleQuery); - } - - if (USE_CONFIG) { - addQueryNode(m, implNode, CONFIG.Cgqi.matcherQuery, matcherQuery); - } else { - addQueryNode(m, implNode, MATCHER_QUERY, matcherQuery); + m.add(implNode, CONFIG.Cgqi.queryLanguage, literal(language.getName())); } + addQueryNode(m, implNode, CONFIG.Cgqi.ruleQuery, ruleQuery); + addQueryNode(m, implNode, CONFIG.Cgqi.matcherQuery, matcherQuery); return implNode; } diff --git a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/CustomGraphQueryInferencerTest.java b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/CustomGraphQueryInferencerTest.java index b9ebf843ea8..23987d0d8b9 100644 --- a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/CustomGraphQueryInferencerTest.java +++ b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/CustomGraphQueryInferencerTest.java @@ -43,12 +43,12 @@ public abstract class CustomGraphQueryInferencerTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterAll - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } diff --git a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/InferredContextTest.java b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/InferredContextTest.java index 3a954953df7..7a33dd58941 100644 --- a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/InferredContextTest.java +++ b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/InferredContextTest.java @@ -20,7 +20,6 @@ import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.RDFS; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStore; import org.junit.jupiter.api.Test; @@ -61,7 +60,7 @@ public void testInferrecContextNoNull() { assertTrue(connection.hasStatement(bNode, RDF.TYPE, RDFS.RESOURCE, true, context)); - try (CloseableIteration statements = connection.getStatements(bNode, + try (CloseableIteration statements = connection.getStatements(bNode, RDF.TYPE, RDFS.RESOURCE, true)) { while (statements.hasNext()) { Statement next = statements.next(); diff --git a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/MemInferencingTest.java b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/MemInferencingTest.java index 157195202bf..23affa1bc1a 100644 --- a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/MemInferencingTest.java +++ b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/MemInferencingTest.java @@ -14,7 +14,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; -import java.lang.reflect.InvocationTargetException; import org.assertj.core.util.Files; import org.eclipse.rdf4j.model.BNode; @@ -93,7 +92,7 @@ public void testBlankNodePredicateInference() { } @Test - public void testRollback() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + public void testRollback() { Repository sailRepository = new SailRepository(createSail()); ValueFactory vf = sailRepository.getValueFactory(); @@ -140,7 +139,7 @@ public void testRollback() throws NoSuchMethodException, InvocationTargetExcepti } @Test - public void testFastInstantiate() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + public void testFastInstantiate() { Repository sailRepository = new SailRepository(createSail()); ValueFactory vf = sailRepository.getValueFactory(); diff --git a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/RDFSchemaNativeRepositoryConnectionTest.java b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/RDFSchemaNativeRepositoryConnectionTest.java index 1080fbb54c8..25af8feb882 100644 --- a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/RDFSchemaNativeRepositoryConnectionTest.java +++ b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/RDFSchemaNativeRepositoryConnectionTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.inferencer.fc; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -20,7 +19,7 @@ public class RDFSchemaNativeRepositoryConnectionTest extends RDFSchemaRepositoryConnectionTest { @Override - protected Repository createRepository(File dataDir) throws IOException { + protected Repository createRepository(File dataDir) { return new SailRepository(new ForwardChainingRDFSInferencer(new NativeStore(dataDir, "spoc"))); } } diff --git a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerIsolationLevelTest.java b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerIsolationLevelTest.java index f3d815def35..f5692082b14 100644 --- a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerIsolationLevelTest.java +++ b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerIsolationLevelTest.java @@ -32,7 +32,7 @@ protected Sail createSail() throws SailException { } @Override - public void testLargeTransaction(IsolationLevel isolationLevel, int count) throws InterruptedException { + public void testLargeTransaction(IsolationLevel isolationLevel, int count) { // See: https://github.com/eclipse/rdf4j/issues/1795 } } diff --git a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerNativeIsolationLevelTest.java b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerNativeIsolationLevelTest.java index a49d1aa5373..003da3de707 100644 --- a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerNativeIsolationLevelTest.java +++ b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerNativeIsolationLevelTest.java @@ -40,12 +40,12 @@ protected NotifyingSail createSail() throws SailException { } @Override - public void testLargeTransactionSerializable() throws InterruptedException { + public void testLargeTransactionSerializable() { // ignored since test is slow } @Override - public void testSnapshot() throws Exception { + public void testSnapshot() { // see: https://github.com/eclipse/rdf4j/issues/1794 } } diff --git a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerNativeRepositoryConnectionTest.java b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerNativeRepositoryConnectionTest.java index 93ea3106bb6..e8db7d7c66f 100644 --- a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerNativeRepositoryConnectionTest.java +++ b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerNativeRepositoryConnectionTest.java @@ -13,7 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.io.IOException; import java.util.stream.Stream; import org.eclipse.rdf4j.common.transaction.IsolationLevel; @@ -31,7 +30,7 @@ public class SchemaCachingRDFSInferencerNativeRepositoryConnectionTest extends RDFSchemaRepositoryConnectionTest { @Override - protected Repository createRepository(File dataDir) throws IOException { + protected Repository createRepository(File dataDir) { SchemaCachingRDFSInferencer sail = new SchemaCachingRDFSInferencer(new NativeStore(dataDir, "spoc"), true); sail.setAddInferredStatementsToDefaultContext(false); @@ -42,7 +41,7 @@ protected Repository createRepository(File dataDir) throws IOException { @ParameterizedTest @MethodSource("parameters") @Disabled - public void testQueryDefaultGraph(IsolationLevel level) throws Exception { + public void testQueryDefaultGraph(IsolationLevel level) { // ignore } @@ -50,7 +49,7 @@ public void testQueryDefaultGraph(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Disabled - public void testDeleteDefaultGraph(IsolationLevel level) throws Exception { + public void testDeleteDefaultGraph(IsolationLevel level) { // ignore } @@ -58,7 +57,7 @@ public void testDeleteDefaultGraph(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Disabled - public void testContextStatementsNotDuplicated(IsolationLevel level) throws Exception { + public void testContextStatementsNotDuplicated(IsolationLevel level) { // ignore } @@ -66,7 +65,7 @@ public void testContextStatementsNotDuplicated(IsolationLevel level) throws Exce @ParameterizedTest @MethodSource("parameters") @Disabled - public void testContextStatementsNotDuplicated2(IsolationLevel level) throws Exception { + public void testContextStatementsNotDuplicated2(IsolationLevel level) { // ignore } diff --git a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerRDFSchemaMemoryRepositoryConnectionTest.java b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerRDFSchemaMemoryRepositoryConnectionTest.java index fc43cf8dc65..0953544016e 100644 --- a/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerRDFSchemaMemoryRepositoryConnectionTest.java +++ b/core/sail/inferencer/src/test/java/org/eclipse/rdf4j/sail/inferencer/fc/SchemaCachingRDFSInferencerRDFSchemaMemoryRepositoryConnectionTest.java @@ -46,7 +46,7 @@ protected Repository createRepository(File dataDir) { @ParameterizedTest @MethodSource("parameters") @Disabled - public void testQueryDefaultGraph(IsolationLevel level) throws Exception { + public void testQueryDefaultGraph(IsolationLevel level) { // ignore } @@ -54,7 +54,7 @@ public void testQueryDefaultGraph(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Disabled - public void testDeleteDefaultGraph(IsolationLevel level) throws Exception { + public void testDeleteDefaultGraph(IsolationLevel level) { // ignore } @@ -62,7 +62,7 @@ public void testDeleteDefaultGraph(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") @Disabled - public void testContextStatementsNotDuplicated(IsolationLevel level) throws Exception { + public void testContextStatementsNotDuplicated(IsolationLevel level) { // ignore } @@ -70,7 +70,7 @@ public void testContextStatementsNotDuplicated(IsolationLevel level) throws Exce @ParameterizedTest @MethodSource("parameters") @Disabled - public void testContextStatementsNotDuplicated2(IsolationLevel level) throws Exception { + public void testContextStatementsNotDuplicated2(IsolationLevel level) { // ignore } diff --git a/core/sail/lmdb/pom.xml b/core/sail/lmdb/pom.xml index 2575b95b099..833cef8bedb 100644 --- a/core/sail/lmdb/pom.xml +++ b/core/sail/lmdb/pom.xml @@ -196,10 +196,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ContextStore.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ContextStore.java index dd5563e836d..5fc40b45807 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ContextStore.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ContextStore.java @@ -32,7 +32,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.sail.SailException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -176,7 +175,7 @@ private void writeContextsToFile() throws IOException { private void initializeContextCache() throws IOException { logger.debug("initializing context cache"); - try (CloseableIteration contextIter = store.getContexts()) { + try (CloseableIteration contextIter = store.getContexts()) { while (contextIter.hasNext()) { increment(contextIter.next()); } diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbRecordIterator.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbRecordIterator.java index bcdd074cb07..de8be81884b 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbRecordIterator.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbRecordIterator.java @@ -119,7 +119,7 @@ class LmdbRecordIterator implements RecordIterator { } @Override - public long[] next() throws IOException { + public long[] next() { long stamp = txnLock.readLock(); try { if (txnRefVersion != txnRef.version()) { @@ -185,7 +185,7 @@ public long[] next() throws IOException { } @Override - public void close() throws IOException { + public void close() { if (!closed) { try { mdb_cursor_close(cursor); diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbSailStore.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbSailStore.java index ad1e48e997c..a6dc372ff7f 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbSailStore.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbSailStore.java @@ -12,17 +12,22 @@ import java.io.File; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; +import org.eclipse.rdf4j.collection.factory.mapdb.MapDbCollectionFactory; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.CloseableIteratorIteration; import org.eclipse.rdf4j.common.iteration.ConvertingIteration; @@ -70,6 +75,8 @@ class LmdbSailStore implements SailStore { private final boolean enableMultiThreading = true; + private final Set unusedIds; + /** * A fast non-blocking circular buffer backed by an array. * @@ -135,6 +142,13 @@ class AddQuadOperation implements Operation { @Override public void execute() throws IOException { + if (!unusedIds.isEmpty()) { + // these ids are used again + unusedIds.remove(s); + unusedIds.remove(p); + unusedIds.remove(o); + unusedIds.remove(c); + } boolean wasNew = tripleStore.storeTriple(s, p, o, c, explicit); if (wasNew && context != null) { contextStore.increment(context); @@ -169,6 +183,19 @@ abstract static class StatefulOperation implements Operation { * Creates a new {@link LmdbSailStore}. */ public LmdbSailStore(File dataDir, LmdbStoreConfig config) throws IOException, SailException { + this.unusedIds = new PersistentSet<>(dataDir) { + @Override + protected byte[] write(Long element) { + ByteBuffer bb = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.BIG_ENDIAN); + bb.putLong(element); + return bb.array(); + } + + @Override + protected Long read(ByteBuffer buffer) { + return buffer.order(ByteOrder.BIG_ENDIAN).getLong(); + } + }; boolean initialized = false; try { namespaceStore = new NamespaceStore(dataDir); @@ -280,10 +307,10 @@ public SailSource getInferredSailSource() { return new LmdbSailSource(false); } - CloseableIteration getContexts() throws IOException { + CloseableIteration getContexts() throws IOException { Txn txn = tripleStore.getTxnManager().createReadTxn(); RecordIterator records = tripleStore.getAllTriplesSortedByContext(txn); - CloseableIteration stIter1; + CloseableIteration stIter1; if (records == null) { // Iterator over all statements stIter1 = createStatementIterator(txn, null, null, null, true); @@ -291,7 +318,7 @@ CloseableIteration getContexts() throws IOException { stIter1 = new LmdbStatementIterator(records, valueStore); } - FilterIteration stIter2 = new FilterIteration<>( + FilterIteration stIter2 = new FilterIteration<>( stIter1) { @Override protected boolean accept(Statement st) { @@ -324,7 +351,7 @@ protected void handleClose() throws SailException { * no contexts are supplied the method operates on the entire repository. * @return A StatementIterator that can be used to iterate over the statements that match the specified pattern. */ - CloseableIteration createStatementIterator( + CloseableIteration createStatementIterator( Txn txn, Resource subj, IRI pred, Value obj, boolean explicit, Resource... contexts) throws IOException { long subjID = LmdbValue.UNKNOWN_ID; if (subj != null) { @@ -425,6 +452,19 @@ public void prepare() throws SailException { // serializable is not supported at this level } + protected void filterUsedIdsInTripleStore() throws IOException { + if (!unusedIds.isEmpty()) { + tripleStore.filterUsedIds(unusedIds); + } + } + + protected void handleRemovedIdsInValueStore() throws IOException { + if (!unusedIds.isEmpty()) { + valueStore.gcIds(unusedIds); + unusedIds.clear(); + } + } + @Override public void flush() throws SailException { sinkStoreAccessLock.lock(); @@ -456,6 +496,10 @@ public void flush() throws SailException { contextStore.sync(); } finally { if (activeTxn) { + if (!multiThreadingActive) { + filterUsedIdsInTripleStore(); + } + handleRemovedIdsInValueStore(); valueStore.commit(); if (!multiThreadingActive) { tripleStore.commit(); @@ -558,6 +602,8 @@ private void startTransaction(boolean preferThreading) throws SailException { Operation op = opQueue.remove(); if (op != null) { if (op == COMMIT_TRANSACTION) { + filterUsedIdsInTripleStore(); + tripleStore.commit(); nextTransactionAsync = false; asyncTransactionFinished = true; @@ -666,9 +712,17 @@ private long removeStatements(long subj, long pred, long obj, boolean explicit, throws IOException { long removeCount = 0; for (long contextId : contexts) { - Map result = tripleStore.removeTriplesByContext(subj, pred, obj, contextId, explicit); + final Map perContextCounts = new HashMap<>(); + tripleStore.removeTriplesByContext(subj, pred, obj, contextId, explicit, quad -> { + perContextCounts.merge(quad[3], 1L, (c, one) -> c + one); + for (long id : quad) { + if (id != 0L) { + unusedIds.add(id); + } + } + }); - for (Entry entry : result.entrySet()) { + for (Entry entry : perContextCounts.entrySet()) { Long entryContextId = entry.getKey(); if (entryContextId > 0) { Resource modifiedContext = (Resource) valueStore.getValue(entryContextId); @@ -814,17 +868,17 @@ public String getNamespace(String prefix) throws SailException { } @Override - public CloseableIteration getNamespaces() { - return new CloseableIteratorIteration(namespaceStore.iterator()); + public CloseableIteration getNamespaces() { + return new CloseableIteratorIteration(namespaceStore.iterator()); } @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { return new CloseableIteratorIteration<>(contextStore.iterator()); } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { try { return createStatementIterator(txn, subj, pred, obj, explicit, contexts); @@ -833,5 +887,4 @@ public CloseableIteration getStatements(Reso } } } - -} +} \ No newline at end of file diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStatementIterator.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStatementIterator.java index ad6ee3fbb21..dd49c90d5a6 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStatementIterator.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStatementIterator.java @@ -23,7 +23,7 @@ * A statement iterator that wraps a RecordIterator containing statement records and translates these records to * {@link Statement} objects. */ -class LmdbStatementIterator extends LookAheadIteration { +class LmdbStatementIterator extends LookAheadIteration { /*-----------* * Variables * @@ -40,7 +40,7 @@ class LmdbStatementIterator extends LookAheadIteration /** * Creates a new LmdbStatementIterator. */ - public LmdbStatementIterator(RecordIterator recordIt, ValueStore valueStore) throws IOException { + public LmdbStatementIterator(RecordIterator recordIt, ValueStore valueStore) { this.recordIt = recordIt; this.valueStore = valueStore; } @@ -83,11 +83,7 @@ protected void handleClose() throws SailException { try { super.handleClose(); } finally { - try { - recordIt.close(); - } catch (IOException e) { - throw causeIOException(e); - } + recordIt.close(); } } diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStore.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStore.java index 953e9678953..21186e79fe0 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStore.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStore.java @@ -335,11 +335,7 @@ public boolean isWritable() { @Override protected NotifyingSailConnection getConnectionInternal() throws SailException { - try { - return new LmdbStoreConnection(this); - } catch (IOException e) { - throw new SailException(e); - } + return new LmdbStoreConnection(this); } @Override @@ -397,7 +393,7 @@ LmdbSailStore getBackingStore() { return backingStore; } - private boolean upgradeStore(File dataDir, String version) throws IOException, SailException { + private boolean upgradeStore(File dataDir, String version) throws SailException { // nothing to do, just update version number return true; } diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreConnection.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreConnection.java index 07584e61616..8dc3c7019ed 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreConnection.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreConnection.java @@ -10,16 +10,22 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.lmdb; -import java.io.IOException; - import org.eclipse.rdf4j.common.concurrent.locks.Lock; +import org.eclipse.rdf4j.common.iteration.CloseableIteration; +import org.eclipse.rdf4j.common.iteration.IterationWrapper; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.Dataset; +import org.eclipse.rdf4j.query.QueryEvaluationException; +import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.SailReadOnlyException; import org.eclipse.rdf4j.sail.base.SailSourceConnection; import org.eclipse.rdf4j.sail.helpers.DefaultSailChangedEvent; +import org.eclipse.rdf4j.sail.lmdb.model.LmdbValue; /** * Connection to an {@link LmdbStore}. @@ -47,11 +53,10 @@ public class LmdbStoreConnection extends SailSourceConnection { * Constructors * *--------------*/ - protected LmdbStoreConnection(LmdbStore sail) throws IOException { + protected LmdbStoreConnection(LmdbStore sail) { super(sail, sail.getSailStore(), sail.getEvaluationStrategyFactory()); this.lmdbStore = sail; sailChangedEvent = new DefaultSailChangedEvent(sail); - useConnectionLock = false; } /*---------* @@ -123,6 +128,52 @@ public boolean addInferredStatement(Resource subj, IRI pred, Value obj, Resource return ret; } + @Override + protected CloseableIteration evaluateInternal(TupleExpr tupleExpr, + Dataset dataset, + BindingSet bindings, boolean includeInferred) throws SailException { + // ensure that all elements of the binding set are initialized (lazy values are resolved) + return new IterationWrapper( + super.evaluateInternal(tupleExpr, dataset, bindings, includeInferred)) { + @Override + public BindingSet next() throws QueryEvaluationException { + BindingSet bs = super.next(); + bs.forEach(b -> initValue(b.getValue())); + return bs; + } + }; + } + + @Override + protected CloseableIteration getStatementsInternal(Resource subj, IRI pred, + Value obj, + boolean includeInferred, Resource... contexts) throws SailException { + return new IterationWrapper( + super.getStatementsInternal(subj, pred, obj, includeInferred, contexts)) { + @Override + public Statement next() throws SailException { + // ensure that all elements of the statement are initialized (lazy values are resolved) + Statement stmt = super.next(); + initValue(stmt.getSubject()); + initValue(stmt.getPredicate()); + initValue(stmt.getObject()); + initValue(stmt.getContext()); + return stmt; + } + }; + } + + /** + * Ensures that all components of the value are initialized from the underlying database. + * + * @param value The value that should be initialized + */ + protected void initValue(Value value) { + if (value instanceof LmdbValue) { + ((LmdbValue) value).init(); + } + } + @Override protected void removeStatementsInternal(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbUtil.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbUtil.java index 336c1ad45c2..6f9603a6dac 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbUtil.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/LmdbUtil.java @@ -48,11 +48,6 @@ final class LmdbUtil { */ static final long MIN_FREE_SPACE = 524_288; // 512 KiB - /** - * Minimum size an LMDB db is automatically grown. - */ - static final long MIN_AUTOGROW_SIZE = 1_048_576; // 1024 KiB - private LmdbUtil() { } @@ -160,7 +155,7 @@ private static long mdbTxnMtNextPgno(long txn) { */ static boolean requiresResize(long mapSize, long pageSize, long txn, long requiredSize) { long nextPageNo = mdbTxnMtNextPgno(txn); - return mapSize - nextPageNo * pageSize < Math.max(requiredSize, LmdbUtil.MIN_FREE_SPACE); + return mapSize - nextPageNo * pageSize < Math.max(requiredSize, MIN_FREE_SPACE); } /** @@ -172,7 +167,7 @@ static boolean requiresResize(long mapSize, long pageSize, long txn, long requir * @return the new map size */ static long autoGrowMapSize(long mapSize, long pageSize, long requiredSize) { - mapSize = Math.max(mapSize * 2, Math.max(requiredSize, MIN_AUTOGROW_SIZE)); + mapSize = Math.max(mapSize * 2, Math.max(requiredSize, MIN_FREE_SPACE)); // align map size to page size return mapSize % pageSize == 0 ? mapSize : mapSize + (mapSize / pageSize + 1) * pageSize; } diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/PersistentSet.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/PersistentSet.java new file mode 100644 index 00000000000..401bae9424f --- /dev/null +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/PersistentSet.java @@ -0,0 +1,390 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.sail.lmdb; + +import static org.eclipse.rdf4j.sail.lmdb.LmdbUtil.E; +import static org.eclipse.rdf4j.sail.lmdb.LmdbUtil.openDatabase; +import static org.eclipse.rdf4j.sail.lmdb.LmdbUtil.readTransaction; +import static org.lwjgl.system.MemoryStack.stackPush; +import static org.lwjgl.system.MemoryUtil.NULL; +import static org.lwjgl.util.lmdb.LMDB.MDB_CREATE; +import static org.lwjgl.util.lmdb.LMDB.MDB_NEXT; +import static org.lwjgl.util.lmdb.LMDB.MDB_NOMETASYNC; +import static org.lwjgl.util.lmdb.LMDB.MDB_NOOVERWRITE; +import static org.lwjgl.util.lmdb.LMDB.MDB_NOSYNC; +import static org.lwjgl.util.lmdb.LMDB.MDB_NOTLS; +import static org.lwjgl.util.lmdb.LMDB.MDB_RDONLY; +import static org.lwjgl.util.lmdb.LMDB.MDB_SET; +import static org.lwjgl.util.lmdb.LMDB.MDB_SET_RANGE; +import static org.lwjgl.util.lmdb.LMDB.MDB_SUCCESS; +import static org.lwjgl.util.lmdb.LMDB.mdb_cursor_close; +import static org.lwjgl.util.lmdb.LMDB.mdb_cursor_get; +import static org.lwjgl.util.lmdb.LMDB.mdb_cursor_open; +import static org.lwjgl.util.lmdb.LMDB.mdb_cursor_renew; +import static org.lwjgl.util.lmdb.LMDB.mdb_del; +import static org.lwjgl.util.lmdb.LMDB.mdb_drop; +import static org.lwjgl.util.lmdb.LMDB.mdb_env_close; +import static org.lwjgl.util.lmdb.LMDB.mdb_env_create; +import static org.lwjgl.util.lmdb.LMDB.mdb_env_open; +import static org.lwjgl.util.lmdb.LMDB.mdb_env_set_mapsize; +import static org.lwjgl.util.lmdb.LMDB.mdb_env_set_maxdbs; +import static org.lwjgl.util.lmdb.LMDB.mdb_get; +import static org.lwjgl.util.lmdb.LMDB.mdb_put; +import static org.lwjgl.util.lmdb.LMDB.mdb_stat; +import static org.lwjgl.util.lmdb.LMDB.mdb_txn_abort; +import static org.lwjgl.util.lmdb.LMDB.mdb_txn_begin; +import static org.lwjgl.util.lmdb.LMDB.mdb_txn_commit; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.AbstractSet; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.concurrent.locks.StampedLock; + +import javax.swing.text.ElementIterator; + +import org.apache.commons.io.FileUtils; +import org.eclipse.rdf4j.sail.lmdb.TxnManager.Mode; +import org.eclipse.rdf4j.sail.lmdb.TxnManager.Txn; +import org.eclipse.rdf4j.sail.lmdb.TxnRecordCache.Record; +import org.eclipse.rdf4j.sail.lmdb.TxnRecordCache.RecordCacheIterator; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.util.lmdb.MDBStat; +import org.lwjgl.util.lmdb.MDBVal; + +import com.fasterxml.jackson.databind.util.ByteBufferBackedInputStream; + +/** + * A LMDB-based persistent set. + */ +class PersistentSet extends AbstractSet { + + private final Path dbDir; + private final long env; + private final int dbi; + private TxnManager txnManager; + private long writeTxn; + private PointerBuffer writeTxnPp = PointerBuffer.allocateDirect(1); + private long mapSize = 1048576; // 1 MiB + private long pageSize; + + private int size; + + public PersistentSet(File cacheDir) throws IOException { + try (MemoryStack stack = stackPush()) { + PointerBuffer pp = stack.mallocPointer(1); + E(mdb_env_create(pp)); + env = pp.get(0); + + txnManager = new TxnManager(env, Mode.ABORT); + + E(mdb_env_set_maxdbs(env, 2)); + E(mdb_env_set_mapsize(env, mapSize)); + + int flags = MDB_NOTLS | MDB_NOSYNC | MDB_NOMETASYNC; + + dbDir = Files.createTempDirectory(cacheDir.toPath(), "set"); + E(mdb_env_open(env, dbDir.toAbsolutePath().toString(), flags, 0664)); + dbi = openDatabase(env, "elements", MDB_CREATE, null); + + MDBStat stat = MDBStat.malloc(stack); + readTransaction(env, (stack2, txn) -> { + E(mdb_stat(txn, dbi, stat)); + pageSize = stat.ms_psize(); + return null; + }); + } + } + + public synchronized void close() throws IOException { + if (writeTxn != 0) { + mdb_txn_abort(writeTxn); + writeTxn = 0; + } + writeTxnPp.free(); + mdb_env_close(env); + FileUtils.deleteDirectory(dbDir.toFile()); + } + + protected synchronized void commit() throws IOException { + if (writeTxn != 0) { + E(mdb_txn_commit(writeTxn)); + writeTxn = 0; + } + } + + public synchronized void clear() { + if (writeTxn != 0) { + mdb_txn_abort(writeTxn); + writeTxn = 0; + } + try { + // start a write transaction + E(mdb_txn_begin(env, NULL, 0, writeTxnPp)); + writeTxn = writeTxnPp.get(0); + mdb_drop(writeTxn, dbi, false); + commit(); + } catch (Exception e) { + throw new RuntimeException(e); + } + size = 0; + } + + @Override + public Iterator iterator() { + try { + commit(); + } catch (Exception e) { + throw new RuntimeException(e); + } + return new ElementIterator(dbi); + } + + @Override + public int size() { + return size; + } + + public boolean add(T element) { + try { + return update(element, true); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public boolean remove(Object element) { + try { + return update(element, false); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + protected synchronized boolean update(Object element, boolean add) throws IOException { + try (MemoryStack stack = MemoryStack.stackPush()) { + if (writeTxn == 0) { + // start a write transaction + E(mdb_txn_begin(env, NULL, 0, writeTxnPp)); + writeTxn = writeTxnPp.get(0); + } + if (LmdbUtil.requiresResize(mapSize, pageSize, writeTxn, 0)) { + StampedLock lock = txnManager.lock(); + long stamp = lock.writeLock(); + try { + txnManager.deactivate(); + + // resize map + E(mdb_txn_commit(writeTxn)); + mapSize = LmdbUtil.autoGrowMapSize(mapSize, pageSize, 0); + E(mdb_env_set_mapsize(env, mapSize)); + + E(mdb_txn_begin(env, NULL, 0, writeTxnPp)); + writeTxn = writeTxnPp.get(0); + } finally { + try { + txnManager.activate(); + } finally { + lock.unlockWrite(stamp); + } + } + } + + MDBVal keyVal = MDBVal.malloc(stack); + // use calloc to get an empty data value + MDBVal dataVal = MDBVal.calloc(stack); + + byte[] data = write((T) element); + ByteBuffer keyBuf = stack.malloc(data.length); + keyBuf.put(data); + keyBuf.flip(); + keyVal.mv_data(keyBuf); + + if (add) { + if (mdb_put(writeTxn, dbi, keyVal, dataVal, MDB_NOOVERWRITE) == MDB_SUCCESS) { + size++; + return true; + } + } else { + // delete element + if (mdb_del(writeTxn, dbi, keyVal, dataVal) == MDB_SUCCESS) { + size--; + return true; + } + } + return false; + } + } + + protected byte[] write(T element) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(baos); + out.writeObject(element); + out.close(); + return baos.toByteArray(); + } + + protected T read(ByteBuffer buffer) throws IOException { + try { + return (T) new ObjectInputStream(new ByteBufferBackedInputStream(buffer)).readObject(); + } catch (ClassNotFoundException cnfe) { + throw new IOException(cnfe); + } + } + + protected class ElementIterator implements Iterator { + + private final MDBVal keyData = MDBVal.malloc(); + private final MDBVal valueData = MDBVal.malloc(); + private final long cursor; + + private final StampedLock txnLock; + private Txn txnRef; + private long txnRefVersion; + + private T next; + private T current; + + protected ElementIterator(int dbi) { + try { + this.txnRef = txnManager.createReadTxn(); + this.txnLock = txnRef.lock(); + + long stamp = txnLock.readLock(); + try { + this.txnRefVersion = txnRef.version(); + + try (MemoryStack stack = MemoryStack.stackPush()) { + PointerBuffer pp = stack.mallocPointer(1); + E(mdb_cursor_open(txnRef.get(), dbi, pp)); + cursor = pp.get(0); + } + } finally { + txnLock.unlockRead(stamp); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean hasNext() { + if (next == null && txnRef != null) { + try { + next = computeNext(); + } catch (Exception e) { + next = null; + } + if (next == null) { + close(); + } + } + return next != null; + } + + @Override + public T next() { + if (next == null) { + throw new NoSuchElementException(); + } + current = next; + next = null; + return current; + } + + public T computeNext() throws IOException { + long stamp = txnLock.readLock(); + try { + if (txnRefVersion != txnRef.version()) { + // cursor must be renewed + mdb_cursor_renew(txnRef.get(), cursor); + + try (MemoryStack stack = MemoryStack.stackPush()) { + keyData.mv_data(stack.bytes(write(current))); + if (mdb_cursor_get(cursor, keyData, valueData, MDB_SET) != 0) { + // use MDB_SET_RANGE if key was deleted + if (mdb_cursor_get(cursor, keyData, valueData, MDB_SET_RANGE) == 0) { + return read(keyData.mv_data()); + } + } + } + } + + if (mdb_cursor_get(cursor, keyData, valueData, MDB_NEXT) == 0) { + return read(keyData.mv_data()); + } + close(); + return null; + } finally { + txnLock.unlockRead(stamp); + } + } + + public void close() { + if (txnRef != null) { + keyData.close(); + valueData.close(); + long stamp = txnLock.readLock(); + try { + mdb_cursor_close(cursor); + txnRef.close(); + txnRef = null; + } finally { + txnLock.unlockRead(stamp); + } + } + } + + @Override + public void remove() { + PersistentSet.this.remove(current); + } + } + + public class ByteBufferBackedInputStream extends InputStream { + + final ByteBuffer buf; + + public ByteBufferBackedInputStream(ByteBuffer buf) { + this.buf = buf; + } + + public int read() throws IOException { + if (!buf.hasRemaining()) { + return -1; + } + return buf.get() & 0xFF; + } + + public int read(byte[] bytes, int off, int len) + throws IOException { + if (!buf.hasRemaining()) { + return -1; + } + + len = Math.min(len, buf.remaining()); + buf.get(bytes, off, len); + return len; + } + } +} diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/RecordIterator.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/RecordIterator.java index 067f0999825..c0a89c0628c 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/RecordIterator.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/RecordIterator.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.Closeable; -import java.io.IOException; /** * An iterator that iterates over records, for example those in a key-value database. @@ -22,16 +21,14 @@ interface RecordIterator extends Closeable { * Returns the next record. * * @return A record that or null if all records have been returned. - * @throws IOException In case an I/O error occurred. */ - long[] next() throws IOException; + long[] next(); /** * Closes the iterator, freeing any resources that it uses. Once closed, the iterator will not return any more * records. * - * @throws IOException In case an I/O error occurred. */ @Override - void close() throws IOException; + void close(); } diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/SailSourceModel.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/SailSourceModel.java index dbe42069c1a..913fefd6ae2 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/SailSourceModel.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/SailSourceModel.java @@ -47,11 +47,11 @@ class SailSourceModel extends AbstractModel { private final class StatementIterator implements Iterator { - final CloseableIteration stmts; + final CloseableIteration stmts; Statement last; - StatementIterator(CloseableIteration closeableIteration) { + StatementIterator(CloseableIteration closeableIteration) { this.stmts = closeableIteration; } @@ -149,7 +149,7 @@ public String toString() { public synchronized int size() { if (size < 0) { try { - CloseableIteration iter; + CloseableIteration iter; iter = dataset().getStatements(null, null, null); try { while (iter.hasNext()) { @@ -174,7 +174,7 @@ public synchronized int size() { public Set getNamespaces() { Set set = new LinkedHashSet<>(); try { - CloseableIteration spaces; + CloseableIteration spaces; spaces = dataset().getNamespaces(); try { while (spaces.hasNext()) { @@ -282,7 +282,7 @@ public synchronized boolean remove(Resource subj, IRI pred, Value obj, Resource. try { if (contains(subj, pred, obj, contexts)) { size = -1; - CloseableIteration stmts; + CloseableIteration stmts; stmts = dataset().getStatements(subj, pred, obj, contexts); try { while (stmts.hasNext()) { @@ -320,7 +320,7 @@ public Model filter(final Resource subj, final IRI pred, final Value obj, final public int size() { if (subj == null && pred == null && obj == null) { try { - CloseableIteration iter; + CloseableIteration iter; iter = dataset().getStatements(null, null, null); try { long size = 0; @@ -362,7 +362,7 @@ protected void removeFilteredTermIteration(Iterator iter, Resource su public synchronized void removeTermIteration(Iterator iter, Resource subj, IRI pred, Value obj, Resource... contexts) { try { - CloseableIteration stmts; + CloseableIteration stmts; stmts = dataset().getStatements(subj, pred, obj, contexts); try { while (stmts.hasNext()) { @@ -409,7 +409,7 @@ private boolean contains(SailDataset dataset, Resource subj, IRI pred, Value obj if (dataset == null) { return false; } - CloseableIteration stmts; + CloseableIteration stmts; stmts = dataset.getStatements(subj, pred, obj, contexts); try { return stmts.hasNext(); diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TripleStore.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TripleStore.java index 86c54b5c6b7..5aa88a1df60 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TripleStore.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TripleStore.java @@ -19,6 +19,7 @@ import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.system.MemoryUtil.NULL; import static org.lwjgl.util.lmdb.LMDB.MDB_CREATE; +import static org.lwjgl.util.lmdb.LMDB.MDB_FIRST; import static org.lwjgl.util.lmdb.LMDB.MDB_LAST; import static org.lwjgl.util.lmdb.LMDB.MDB_NEXT; import static org.lwjgl.util.lmdb.LMDB.MDB_NOMETASYNC; @@ -39,13 +40,13 @@ import static org.lwjgl.util.lmdb.LMDB.mdb_env_open; import static org.lwjgl.util.lmdb.LMDB.mdb_env_set_mapsize; import static org.lwjgl.util.lmdb.LMDB.mdb_env_set_maxdbs; +import static org.lwjgl.util.lmdb.LMDB.mdb_env_set_maxreaders; import static org.lwjgl.util.lmdb.LMDB.mdb_get; import static org.lwjgl.util.lmdb.LMDB.mdb_put; import static org.lwjgl.util.lmdb.LMDB.mdb_stat; import static org.lwjgl.util.lmdb.LMDB.mdb_txn_abort; import static org.lwjgl.util.lmdb.LMDB.mdb_txn_begin; import static org.lwjgl.util.lmdb.LMDB.mdb_txn_commit; -import static org.lwjgl.util.lmdb.LMDB.nmdb_env_set_maxreaders; import java.io.Closeable; import java.io.File; @@ -57,15 +58,18 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.locks.StampedLock; +import java.util.function.Consumer; import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.lmdb.TxnManager.Mode; @@ -126,12 +130,10 @@ class TripleStore implements Closeable { * */ private static final int SCHEME_VERSION = 1; - /*-----------* * Variables * *-----------*/ private static final Logger logger = LoggerFactory.getLogger(TripleStore.class); - /** * The directory that is used to store the index files. */ @@ -191,8 +193,8 @@ public int compareRegion(ByteBuffer array1, int startIdx1, ByteBuffer array2, in env = pp.get(0); } - mdb_env_set_maxdbs(env, 12); - nmdb_env_set_maxreaders(env, 256); + E(mdb_env_set_maxdbs(env, 12)); + E(mdb_env_set_maxreaders(env, 256)); // Open environment int flags = MDB_NOTLS; @@ -504,6 +506,111 @@ protected void bucketStart(double fraction, long[] lowerValues, long[] upperValu } } + /** + * Checks if any of ids is used and removes it from the collection. + * + * @param ids Collection with possibly removed IDs + * @throws IOException + */ + protected void filterUsedIds(Collection ids) throws IOException { + try (MemoryStack stack = stackPush()) { + MDBVal maxKey = MDBVal.malloc(stack); + ByteBuffer maxKeyBuf = stack.malloc(TripleStore.MAX_KEY_LENGTH); + MDBVal keyData = MDBVal.malloc(stack); + ByteBuffer keyBuf = stack.malloc(TripleStore.MAX_KEY_LENGTH); + + MDBVal valueData = MDBVal.mallocStack(stack); + + PointerBuffer pp = stack.mallocPointer(1); + + // TODO currently this does not test for contexts (component == 3) + // because in most cases context indexes do not exist + for (int component = 0; component <= 2; component++) { + int c = component; + + TripleIndex index = getBestIndex(component == 0 ? 1 : -1, component == 1 ? 1 : -1, + component == 2 ? 1 : -1, component == 3 ? 1 : -1); + + boolean fullScan = index.getPatternScore(component == 0 ? 1 : -1, component == 1 ? 1 : -1, + component == 2 ? 1 : -1, component == 3 ? 1 : -1) == 0; + + for (boolean explicit : new boolean[] { true, false }) { + int dbi = index.getDB(explicit); + + long cursor = 0; + try { + E(mdb_cursor_open(writeTxn, dbi, pp)); + cursor = pp.get(0); + + if (fullScan) { + long[] quad = new long[4]; + int rc = mdb_cursor_get(cursor, keyData, valueData, MDB_FIRST); + while (rc == 0 && !ids.isEmpty()) { + index.keyToQuad(keyData.mv_data(), quad); + ids.remove(quad[0]); + ids.remove(quad[1]); + ids.remove(quad[2]); + ids.remove(quad[3]); + + rc = mdb_cursor_get(cursor, keyData, valueData, MDB_NEXT); + } + } else { + for (Iterator it = ids.iterator(); it.hasNext();) { + long id = it.next(); + if (id < 0) { + it.remove(); + continue; + } + if (component != 2 && (id & 1) == 1) { + // id is a literal and can only appear in object position + continue; + } + + long subj = c == 0 ? id : -1, pred = c == 1 ? id : -1, + obj = c == 2 ? id : -1, context = c == 3 ? id : -1; + + GroupMatcher matcher = index.createMatcher(subj, pred, obj, context); + + maxKeyBuf.clear(); + index.getMaxKey(maxKeyBuf, subj, pred, obj, context); + maxKeyBuf.flip(); + maxKey.mv_data(maxKeyBuf); + + keyBuf.clear(); + index.getMinKey(keyBuf, subj, pred, obj, context); + keyBuf.flip(); + + // set cursor to min key + keyData.mv_data(keyBuf); + int rc = mdb_cursor_get(cursor, keyData, valueData, MDB_SET_RANGE); + boolean exists = false; + while (!exists && rc == 0) { + if (mdb_cmp(writeTxn, dbi, keyData, maxKey) > 0) { + // id was not found + break; + } else if (!matcher.matches(keyData.mv_data())) { + // value doesn't match search key/mask, fetch next value + rc = mdb_cursor_get(cursor, keyData, valueData, MDB_NEXT); + } else { + exists = true; + } + } + + if (exists) { + it.remove(); + } + } + } + } finally { + if (cursor != 0) { + mdb_cursor_close(cursor); + } + } + } + } + } + } + protected double cardinality(long subj, long pred, long obj, long context) throws IOException { TripleIndex index = getBestIndex(subj, pred, obj, context); @@ -712,6 +819,7 @@ public boolean storeTriple(long subj, long pred, long obj, long context, boolean if (requiresResize()) { // map is full, resize required recordCache = new TxnRecordCache(dir); + logger.debug("resize of map size {} required while adding - initialize record cache", mapSize); } } if (recordCache != null) { @@ -757,28 +865,28 @@ public boolean storeTriple(long subj, long pred, long obj, long context, boolean * @param explicit Flag indicating whether explicit or inferred statements should be removed; true removes * explicit statements that match the pattern, false removes inferred statements that match * the pattern. - * @return A mapping of each modified context to the number of statements removed in that context. + * @param handler Function that gets notified about each deleted quad * @throws IOException */ - public Map removeTriplesByContext(long subj, long pred, long obj, long context, - boolean explicit) throws IOException { + public void removeTriplesByContext(long subj, long pred, long obj, long context, + boolean explicit, Consumer handler) throws IOException { RecordIterator records = getTriples(txnManager.createTxn(writeTxn), subj, pred, obj, context, explicit); - return removeTriples(records, explicit); + removeTriples(records, explicit, handler); } - private Map removeTriples(RecordIterator iter, boolean explicit) throws IOException { - final Map perContextCounts = new HashMap<>(); - - try (iter; MemoryStack stack = MemoryStack.stackPush()) { + public void removeTriples(RecordIterator it, boolean explicit, Consumer handler) throws IOException { + try (MemoryStack stack = MemoryStack.stackPush()) { MDBVal keyValue = MDBVal.callocStack(stack); ByteBuffer keyBuf = stack.malloc(MAX_KEY_LENGTH); long[] quad; - while ((quad = iter.next()) != null) { + while ((quad = it.next()) != null) { if (recordCache == null) { if (requiresResize()) { // map is full, resize required recordCache = new TxnRecordCache(dir); + logger.debug("resize of map size {} required while removing - initialize record cache", + mapSize); } } if (recordCache != null) { @@ -796,11 +904,11 @@ private Map removeTriples(RecordIterator iter, boolean explicit) thr E(mdb_del(writeTxn, index.getDB(explicit), keyValue, null)); } - perContextCounts.merge(quad[CONTEXT_IDX], 1L, Long::sum); + handler.accept(quad); } + } finally { + it.close(); } - - return perContextCounts; } protected void updateFromCache() throws IOException { @@ -821,6 +929,7 @@ protected void updateFromCache() throws IOException { E(mdb_txn_commit(writeTxn)); mapSize = LmdbUtil.autoGrowMapSize(mapSize, pageSize, 0); E(mdb_env_set_mapsize(env, mapSize)); + logger.debug("resized map to {}", mapSize); E(mdb_txn_begin(env, NULL, 0, pp)); writeTxn = pp.get(0); } @@ -859,41 +968,59 @@ public void startTransaction() throws IOException { */ void endTransaction(boolean commit) throws IOException { if (writeTxn != 0) { - if (commit) { - E(mdb_txn_commit(writeTxn)); - if (recordCache != null) { - StampedLock lock = txnManager.lock(); - long stamp = lock.writeLock(); + try { + if (commit) { try { - txnManager.deactivate(); - mapSize = LmdbUtil.autoGrowMapSize(mapSize, pageSize, 0); - E(mdb_env_set_mapsize(env, mapSize)); - // restart write transaction - try (MemoryStack stack = stackPush()) { - PointerBuffer pp = stack.mallocPointer(1); - mdb_txn_begin(env, NULL, 0, pp); - writeTxn = pp.get(0); - } - updateFromCache(); - // finally, commit write transaction E(mdb_txn_commit(writeTxn)); - } finally { - recordCache = null; - try { - txnManager.activate(); - } finally { - lock.unlockWrite(stamp); + if (recordCache != null) { + StampedLock lock = txnManager.lock(); + long stamp = lock.writeLock(); + try { + txnManager.deactivate(); + mapSize = LmdbUtil.autoGrowMapSize(mapSize, pageSize, 0); + E(mdb_env_set_mapsize(env, mapSize)); + logger.debug("resized map to {}", mapSize); + // restart write transaction + try (MemoryStack stack = stackPush()) { + PointerBuffer pp = stack.mallocPointer(1); + mdb_txn_begin(env, NULL, 0, pp); + writeTxn = pp.get(0); + } + updateFromCache(); + // finally, commit write transaction + E(mdb_txn_commit(writeTxn)); + } finally { + recordCache = null; + try { + txnManager.activate(); + } finally { + lock.unlockWrite(stamp); + } + } + } else { + // invalidate open read transaction so that they are not re-used + // otherwise iterators won't see the updated data + txnManager.reset(); } + } catch (IOException e) { + // abort transaction if exception occurred while committing + mdb_txn_abort(writeTxn); + throw e; } } else { - // invalidate open read transaction so that they are not re-used - // otherwise iterators won't see the updated data - txnManager.reset(); + mdb_txn_abort(writeTxn); + } + } finally { + writeTxn = 0; + // ensure that record cache is always reset + if (recordCache != null) { + try { + recordCache.close(); + } finally { + recordCache = null; + } } - } else { - mdb_txn_abort(writeTxn); } - writeTxn = 0; } } @@ -1093,12 +1220,12 @@ void close() { pool.close(); } - void clear(long txn) throws IOException { + void clear(long txn) { mdb_drop(txn, dbiExplicit, false); mdb_drop(txn, dbiInferred, false); } - void destroy(long txn) throws IOException { + void destroy(long txn) { mdb_drop(txn, dbiExplicit, true); mdb_drop(txn, dbiInferred, true); } diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TxnManager.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TxnManager.java index 433bb3e5212..35288a80d72 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TxnManager.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TxnManager.java @@ -162,7 +162,6 @@ enum Mode { class Txn implements Closeable, AutoCloseable { private long txn; - private List staleTxns; private long version; Txn(long txn) { @@ -209,26 +208,19 @@ public void close() { active.remove(this); } free(txn); - if (staleTxns != null) { - for (long staleTxn : staleTxns) { - free(staleTxn); - } - } } /** - * Marks current transaction as stale as it points to "old" data. + * Resets current transaction as it points to "old" data. */ void reset() throws IOException { - if (staleTxns == null) { - staleTxns = new ArrayList<>(5); - } - staleTxns.add(txn); - txn = createReadTxnInternal(); + mdb_txn_reset(txn); + E(mdb_txn_renew(txn)); + version++; } /** - * Triggers active state of current and stale transactions. + * Triggers active state of current transaction. */ void setActive(boolean active) throws IOException { if (active) { @@ -237,15 +229,6 @@ void setActive(boolean active) throws IOException { } else { mdb_txn_reset(txn); } - if (staleTxns != null) { - for (Long staleTxn : staleTxns) { - if (active) { - E(mdb_txn_renew(staleTxn)); - } else { - mdb_txn_reset(staleTxn); - } - } - } } long version() { diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TxnRecordCache.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TxnRecordCache.java index d9c1e1b489e..12121294071 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TxnRecordCache.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/TxnRecordCache.java @@ -193,7 +193,7 @@ protected RecordCacheIterator(int dbi) throws IOException { } } - public Record next() throws IOException { + public Record next() { if (mdb_cursor_get(cursor, keyData, valueData, MDB_NEXT) == 0) { Varint.readListUnsigned(keyData.mv_data(), quad); byte op = valueData.mv_data().get(0); diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ValueStore.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ValueStore.java index d2157135eb2..9c974e2b373 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ValueStore.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ValueStore.java @@ -15,6 +15,7 @@ import static org.lwjgl.system.MemoryStack.stackPush; import static org.lwjgl.system.MemoryUtil.NULL; import static org.lwjgl.util.lmdb.LMDB.MDB_CREATE; +import static org.lwjgl.util.lmdb.LMDB.MDB_FIRST; import static org.lwjgl.util.lmdb.LMDB.MDB_NEXT; import static org.lwjgl.util.lmdb.LMDB.MDB_NOMETASYNC; import static org.lwjgl.util.lmdb.LMDB.MDB_NOSYNC; @@ -23,13 +24,17 @@ import static org.lwjgl.util.lmdb.LMDB.MDB_RESERVE; import static org.lwjgl.util.lmdb.LMDB.MDB_SET_RANGE; import static org.lwjgl.util.lmdb.LMDB.mdb_cursor_close; +import static org.lwjgl.util.lmdb.LMDB.mdb_cursor_del; import static org.lwjgl.util.lmdb.LMDB.mdb_cursor_get; import static org.lwjgl.util.lmdb.LMDB.mdb_cursor_open; +import static org.lwjgl.util.lmdb.LMDB.mdb_del; import static org.lwjgl.util.lmdb.LMDB.mdb_env_close; import static org.lwjgl.util.lmdb.LMDB.mdb_env_create; import static org.lwjgl.util.lmdb.LMDB.mdb_env_info; import static org.lwjgl.util.lmdb.LMDB.mdb_env_open; import static org.lwjgl.util.lmdb.LMDB.mdb_env_set_mapsize; +import static org.lwjgl.util.lmdb.LMDB.mdb_env_set_maxdbs; +import static org.lwjgl.util.lmdb.LMDB.mdb_env_set_maxreaders; import static org.lwjgl.util.lmdb.LMDB.mdb_get; import static org.lwjgl.util.lmdb.LMDB.mdb_put; import static org.lwjgl.util.lmdb.LMDB.mdb_stat; @@ -44,11 +49,17 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; import java.util.Optional; +import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.concurrent.locks.StampedLock; import java.util.zip.CRC32; +import org.eclipse.rdf4j.common.concurrent.locks.diagnostics.ConcurrentCleaner; import org.eclipse.rdf4j.common.io.ByteArrayUtil; import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.IRI; @@ -76,6 +87,8 @@ */ class ValueStore extends AbstractValueFactory { + private static final long VALUE_EVICTION_INTERVAL = 60000; // 60 seconds + private static final byte URI_VALUE = 0x0; // 00 private static final byte LITERAL_VALUE = 0x1; // 01 @@ -98,6 +111,10 @@ class ValueStore extends AbstractValueFactory { * Used to do the actual storage of values, once they're translated to byte arrays. */ private final File dir; + /** + * Lock for clearing caches when values are removed. + */ + private final StampedLock revisionLock = new StampedLock(); /** * A simple cache containing the [VALUE_CACHE_SIZE] most-recently used values stored by their ID. */ @@ -121,10 +138,16 @@ class ValueStore extends AbstractValueFactory { private long env; private int pageSize; private long mapSize; + // main database private int dbi; + // database with unused IDs + private int unusedDbi; + // database with free IDs + private int freeDbi; private long writeTxn; private final boolean forceSync; private final boolean autoGrow; + private boolean invalidateRevisionOnCommit = false; /** * This lock is required to block transactions while auto-growing the map size. */ @@ -135,10 +158,24 @@ class ValueStore extends AbstractValueFactory { * valid. In order to be valid, the ValueStoreRevision object of a LmdbValue needs to be equal to this object. */ private volatile ValueStoreRevision revision; + /** + * A wrapper object for the revision of the value store, which is used within lazy (uninitialized values). If this + * object is GCed then it is safe to finally remove the ID-value associations and to reuse IDs. + */ + private volatile ValueStoreRevision.Lazy lazyRevision; + /** * The next ID that is associated with a stored value */ private long nextId; + private boolean freeIdsAvailable; + + private volatile long nextValueEvictionTime = 0; + + // package-protected for testing + final Set unusedRevisionIds = new HashSet<>(); + + private final ConcurrentCleaner cleaner = new ConcurrentCleaner(); ValueStore(File dir, LmdbStoreConfig config) throws IOException { this.dir = dir; @@ -192,6 +229,9 @@ private void open() throws IOException { env = pp.get(0); } + E(mdb_env_set_maxdbs(env, 6)); + E(mdb_env_set_maxreaders(env, 256)); + // Open environment int flags = MDB_NOTLS; if (!forceSync) { @@ -199,7 +239,7 @@ private void open() throws IOException { } E(mdb_env_open(env, dir.getAbsolutePath(), flags, 0664)); - // Open database + // open main database dbi = openDatabase(env, null, MDB_CREATE, null); // initialize page size and set map size for env @@ -225,9 +265,66 @@ private void open() throws IOException { } return null; }); + + // open unused IDs database + unusedDbi = openDatabase(env, "unused_ids", MDB_CREATE, null); + // open free IDs database + freeDbi = openDatabase(env, "free_ids", MDB_CREATE, null); + + // check if free IDs are available + readTransaction(env, (stack, txn) -> { + MDBStat stat = MDBStat.malloc(stack); + mdb_stat(txn, freeDbi, stat); + freeIdsAvailable = stat.ms_entries() > 0; + + mdb_stat(txn, unusedDbi, stat); + if (stat.ms_entries() > 0) { + // free unused IDs + resizeMap(txn, stat.ms_entries() * (2 + Long.BYTES)); + + writeTransaction((stack2, txn2) -> { + freeUnusedIdsAndValues(stack2, txn2, null); + return null; + }); + } + return null; + }); } private long nextId(byte type) throws IOException { + if (freeIdsAvailable) { + // next id from store + Long reusedId = writeTransaction((stack, txn) -> { + long cursor = 0; + try { + PointerBuffer pp = stack.mallocPointer(1); + E(mdb_cursor_open(txn, freeDbi, pp)); + cursor = pp.get(0); + + MDBVal keyData = MDBVal.calloc(stack); + MDBVal valueData = MDBVal.calloc(stack); + if (mdb_cursor_get(cursor, keyData, valueData, MDB_FIRST) == 0) { + // remove lower 2 type bits + long value = data2id(keyData.mv_data()) >> 2; + // delete entry + E(mdb_cursor_del(cursor, 0)); + return value; + } + freeIdsAvailable = mdb_cursor_get(cursor, keyData, valueData, MDB_NEXT) == 0; + return null; + } finally { + if (cursor != 0) { + mdb_cursor_close(cursor); + } + } + }); + if (reusedId != null) { + long result = reusedId; + // encode type in lower 2 bits of id + result = (result << 2) | type; + return result; + } + } long result = nextId; nextId++; // encode type in lower 2 bits of id @@ -256,10 +353,11 @@ protected long data2id(ByteBuffer bb) { * created by this value store. */ private void setNewRevision() { - revision = new ValueStoreRevision(this); + revision = new ValueStoreRevision.Default(this); + lazyRevision = new ValueStoreRevision.Lazy(revision); } - public ValueStoreRevision getRevision() { + ValueStoreRevision getRevision() { return revision; } @@ -314,29 +412,34 @@ void cacheValue(long id, LmdbValue value) { * @throws IOException If an I/O error occurred. */ public LmdbValue getLazyValue(long id) throws IOException { - // Check value cache - Long cacheID = id; - LmdbValue resultValue = cachedValue(cacheID); - - if (resultValue == null) { - switch ((byte) (id & 0x3)) { - case URI_VALUE: - resultValue = new LmdbIRI(revision, id); - break; - case LITERAL_VALUE: - resultValue = new LmdbLiteral(revision, id); - break; - case BNODE_VALUE: - resultValue = new LmdbBNode(revision, id); - break; - default: - throw new IOException("Unsupported value with type id " + (id & 0x3)); + long stamp = revisionLock.readLock(); + try { + // Check value cache + Long cacheID = id; + LmdbValue resultValue = cachedValue(cacheID); + + if (resultValue == null) { + switch ((byte) (id & 0x3)) { + case URI_VALUE: + resultValue = new LmdbIRI(lazyRevision, id); + break; + case LITERAL_VALUE: + resultValue = new LmdbLiteral(lazyRevision, id); + break; + case BNODE_VALUE: + resultValue = new LmdbBNode(lazyRevision, id); + break; + default: + throw new IOException("Unsupported value with type id " + (id & 0x3)); + } + // Store value in cache + cacheValue(cacheID, resultValue); } - // Store value in cache - cacheValue(cacheID, resultValue); - } - return resultValue; + return resultValue; + } finally { + revisionLock.unlockRead(stamp); + } } /** @@ -347,22 +450,27 @@ public LmdbValue getLazyValue(long id) throws IOException { * @throws IOException If an I/O error occurred. */ public LmdbValue getValue(long id) throws IOException { - // Check value cache - Long cacheID = id; - LmdbValue resultValue = cachedValue(cacheID); - - if (resultValue == null) { - // Value not in cache, fetch it from file - byte[] data = getData(id); - - if (data != null) { - resultValue = data2value(id, data, null); - // Store value in cache - cacheValue(cacheID, resultValue); + long stamp = revisionLock.readLock(); + try { + // Check value cache + Long cacheID = id; + LmdbValue resultValue = cachedValue(cacheID); + + if (resultValue == null) { + // Value not in cache, fetch it from file + byte[] data = getData(id); + + if (data != null) { + resultValue = data2value(id, data, null); + // Store value in cache + cacheValue(cacheID, resultValue); + } } - } - return resultValue; + return resultValue; + } finally { + revisionLock.unlockRead(stamp); + } } /** @@ -385,7 +493,7 @@ public boolean resolveValue(long id, LmdbValue value) { return false; } - private void resizeMap(long txn, int requiredSize) throws IOException { + private void resizeMap(long txn, long requiredSize) throws IOException { if (autoGrow) { if (LmdbUtil.requiresResize(mapSize, pageSize, txn, requiredSize)) { // map is full, resize @@ -418,7 +526,7 @@ private void resizeMap(long txn, int requiredSize) throws IOException { private long findId(byte[] data, boolean create) throws IOException { Long id = readTransaction(env, (stack, txn) -> { - if (data.length < MAX_KEY_SIZE) { + if (data.length <= MAX_KEY_SIZE) { MDBVal dataVal = MDBVal.calloc(stack); dataVal.mv_data(stack.bytes(data)); MDBVal idVal = MDBVal.calloc(stack); @@ -507,8 +615,7 @@ private long findId(byte[] data, boolean create) throws IOException { ByteBuffer hashIdBb = hashVal.mv_data(); hashIdBb.position(hashLength); idVal.mv_data(hashIdBb); - if (mdb_get(txn, dbi, idVal, dataVal) == 0 && - dataVal.mv_data().compareTo(dataBb) == 0) { + if (mdb_get(txn, dbi, idVal, dataVal) == 0 && dataVal.mv_data().compareTo(dataBb) == 0) { // id was found if stored value is equal to requested value return data2id(hashIdBb); } @@ -618,47 +725,217 @@ public long getId(Value value, boolean create) throws IOException { } } - // Check cache - Long cachedID = valueIDCache.get(value); + long stamp = revisionLock.readLock(); + try { + // Check cache + Long cachedID = valueIDCache.get(value); + + if (cachedID != null) { + long id = cachedID; + + if (isOwnValue) { + // Store id in value for fast access in any consecutive calls + ((LmdbValue) value).setInternalID(id, revision); + } - if (cachedID != null) { - long id = cachedID; + return id; + } - if (isOwnValue) { - // Store id in value for fast access in any consecutive calls - ((LmdbValue) value).setInternalID(id, revision); + // ID not cached, search in file + byte[] data = value2data(value, create); + if (data == null && value instanceof Literal) { + data = literal2legacy((Literal) value); } - return id; + if (data != null) { + long id = findId(data, create); + + if (id != LmdbValue.UNKNOWN_ID) { + if (isOwnValue) { + // Store id in value for fast access in any consecutive calls + ((LmdbValue) value).setInternalID(id, revision); + // Store id in cache + valueIDCache.put((LmdbValue) value, id); + } else { + // Store id in cache + LmdbValue nv = getLmdbValue(value); + nv.setInternalID(id, revision); + valueIDCache.put(nv, id); + } + } + + return id; + } + } finally { + revisionLock.unlockRead(stamp); } - // ID not cached, search in file - byte[] data = value2data(value, create); - if (data == null && value instanceof Literal) { - data = literal2legacy((Literal) value); + return LmdbValue.UNKNOWN_ID; + } + + public void gcIds(Collection ids) throws IOException { + if (!ids.isEmpty()) { + resizeMap(writeTxn, 2 * ids.size() * (1 + Long.BYTES + 2 + Long.BYTES)); + + writeTransaction((stack, writeTxn) -> { + MDBVal revIdVal = MDBVal.calloc(stack); + MDBVal dataVal = MDBVal.calloc(stack); + + ByteBuffer revIdBb = stack.malloc(1 + Long.BYTES + 2 + Long.BYTES); + Varint.writeUnsigned(revIdBb, revision.getRevisionId()); + int revLength = revIdBb.position(); + for (Long id : ids) { + revIdBb.position(revLength).limit(revIdBb.capacity()); + revIdVal.mv_data(id2data(revIdBb, id).flip()); + E(mdb_put(writeTxn, unusedDbi, revIdVal, dataVal, 0)); + } + + deleteValueToIdMappings(stack, writeTxn, ids); + + invalidateRevisionOnCommit = true; + if (nextValueEvictionTime < 0) { + nextValueEvictionTime = System.currentTimeMillis() + VALUE_EVICTION_INTERVAL; + } + return null; + }); } + } - if (data != null) { - long id = findId(data, create); + protected void deleteValueToIdMappings(MemoryStack stack, long txn, Collection ids) throws IOException { + int maxHashKeyLength = 2 + 2 * Long.BYTES + 2; + ByteBuffer hashBb = stack.malloc(maxHashKeyLength); + MDBVal idVal = MDBVal.calloc(stack); + ByteBuffer idBb = idBuffer(stack); + MDBVal hashVal = MDBVal.calloc(stack); + MDBVal dataVal = MDBVal.calloc(stack); - if (id != LmdbValue.UNKNOWN_ID) { - if (isOwnValue) { - // Store id in value for fast access in any consecutive calls - ((LmdbValue) value).setInternalID(id, revision); - // Store id in cache - valueIDCache.put((LmdbValue) value, id); - } else { - // Store id in cache - LmdbValue nv = getLmdbValue(value); - nv.setInternalID(id, revision); - valueIDCache.put(nv, id); + long valuesCursor = 0; + try { + for (Long id : ids) { + idVal.mv_data(id2data(idBb.clear(), id).flip()); + if (mdb_get(txn, dbi, idVal, dataVal) == 0) { + ByteBuffer dataBuffer = dataVal.mv_data(); + int dataLength = dataVal.mv_data().remaining(); + if (dataLength > MAX_KEY_SIZE) { + byte[] data = new byte[dataLength]; + dataVal.mv_data().get(data); + long dataHash = hash(data); + + hashBb.clear(); + hashBb.put(HASH_KEY); + Varint.writeUnsigned(hashBb, dataHash); + int hashLength = hashBb.position(); + hashBb.flip(); + + hashVal.mv_data(hashBb); + + // delete HASH -> ID association + if (mdb_del(txn, dbi, hashVal, dataVal) == 0) { + // was first entry, find a possible next entry and make it the first + hashBb.put(0, HASHID_KEY); + hashBb.rewind(); + hashVal.mv_data(hashBb); + + if (valuesCursor == 0) { + // initialize cursor + PointerBuffer pp = stack.mallocPointer(1); + E(mdb_cursor_open(txn, dbi, pp)); + valuesCursor = pp.get(0); + } + + if (mdb_cursor_get(valuesCursor, hashVal, dataVal, MDB_SET_RANGE) == 0) { + if (compareRegion(hashVal.mv_data(), 0, hashBb, 0, hashLength) == 0) { + ByteBuffer idBuffer2 = hashVal.mv_data(); + idBuffer2.position(hashLength); + idVal.mv_data(idBuffer2); + + hashVal.mv_data(hashBb); + + // HASH -> ID + E(mdb_put(txn, dbi, hashVal, idVal, 0)); + // delete existing mapping + E(mdb_cursor_del(valuesCursor, 0)); + } + } + } else { + // was not the first entry, delete HASH+ID association + hashBb.put(0, HASHID_KEY); + hashBb.limit(hashLength + idVal.mv_data().remaining()); + hashBb.position(hashLength); + hashBb.put(idVal.mv_data()); + hashBb.flip(); + + hashVal.mv_data(hashBb); + // delete HASH+ID -> [] association + mdb_del(txn, dbi, hashVal, null); + } + } else { + // delete value -> ID association + dataVal.mv_data(dataBuffer); + mdb_del(txn, dbi, dataVal, null); + } + + // does not delete ID -> value association } } - - return id; + } finally { + if (valuesCursor != 0) { + mdb_cursor_close(valuesCursor); + } } + } - return LmdbValue.UNKNOWN_ID; + protected void freeUnusedIdsAndValues(MemoryStack stack, long txn, Set revisionIds) throws IOException { + MDBVal idVal = MDBVal.calloc(stack); + MDBVal revIdVal = MDBVal.calloc(stack); + MDBVal dataVal = MDBVal.calloc(stack); + MDBVal emptyVal = MDBVal.calloc(stack); + + ByteBuffer revIdBb = stack.malloc(1 + Long.BYTES + 2 + Long.BYTES); + + boolean freeIds = false; + long unusedIdsCursor = 0; + try { + PointerBuffer pp = stack.mallocPointer(1); + E(mdb_cursor_open(txn, unusedDbi, pp)); + unusedIdsCursor = pp.get(0); + + if (revisionIds == null) { + // marker to delete all IDs + revisionIds = Collections.singleton(0L); + } + for (Long revisionId : revisionIds) { + // iterate all unused IDs for revision + revIdBb.clear(); + Varint.writeUnsigned(revIdBb, revisionId); + revIdVal.mv_data(revIdBb.flip()); + if (mdb_cursor_get(unusedIdsCursor, revIdVal, dataVal, MDB_SET_RANGE) == 0) { + do { + ByteBuffer keyBb = revIdVal.mv_data(); + long revisionOfId = Varint.readUnsigned(keyBb); + if (revisionId == 0L || revisionOfId == revisionId) { + idVal.mv_data(keyBb); + + // add id to free list + E(mdb_put(txn, freeDbi, idVal, emptyVal, 0)); + // delete id -> value association + E(mdb_del(txn, dbi, idVal, null)); + // delete id and value from unused list + E(mdb_cursor_del(unusedIdsCursor, 0)); + + freeIds = true; + } else { + break; + } + } while (mdb_cursor_get(unusedIdsCursor, revIdVal, dataVal, MDB_NEXT) == 0); + } + } + } finally { + if (unusedIdsCursor != 0) { + mdb_cursor_close(unusedIdsCursor); + } + } + this.freeIdsAvailable |= freeIds; } public void startTransaction() throws IOException { @@ -667,6 +944,21 @@ public void startTransaction() throws IOException { E(mdb_txn_begin(env, NULL, 0, pp)); writeTxn = pp.get(0); + + // delete unused IDs if required on a regular basis + // this is also run after opening the database + if (nextValueEvictionTime >= 0 && System.currentTimeMillis() >= nextValueEvictionTime) { + synchronized (unusedRevisionIds) { + MDBStat stat = MDBStat.malloc(stack); + mdb_stat(writeTxn, unusedDbi, stat); + + resizeMap(writeTxn, stat.ms_entries() * (2 + Long.BYTES)); + + freeUnusedIdsAndValues(stack, writeTxn, unusedRevisionIds); + unusedRevisionIds.clear(); + } + nextValueEvictionTime = -1; + } } } @@ -676,11 +968,32 @@ public void startTransaction() throws IOException { void endTransaction(boolean commit) throws IOException { if (writeTxn != 0) { if (commit) { - E(mdb_txn_commit(writeTxn)); + if (invalidateRevisionOnCommit) { + long stamp = revisionLock.writeLock(); + try { + E(mdb_txn_commit(writeTxn)); + long revisionId = lazyRevision.getRevisionId(); + cleaner.register(lazyRevision, () -> { + synchronized (unusedRevisionIds) { + unusedRevisionIds.add(revisionId); + } + if (nextValueEvictionTime < 0) { + nextValueEvictionTime = System.currentTimeMillis() + VALUE_EVICTION_INTERVAL; + } + }); + setNewRevision(); + clearCaches(); + } finally { + revisionLock.unlockWrite(stamp); + } + } else { + E(mdb_txn_commit(writeTxn)); + } } else { mdb_txn_abort(writeTxn); } writeTxn = 0; + invalidateRevisionOnCommit = false; } } @@ -727,14 +1040,16 @@ public void clear() throws IOException { new File(dir, "data.mdb").delete(); new File(dir, "lock.mdb").delete(); + clearCaches(); + open(); + setNewRevision(); + } + + protected void clearCaches() { Arrays.fill(valueCache, null); valueIDCache.clear(); namespaceCache.clear(); namespaceIDCache.clear(); - - open(); - - setNewRevision(); } /** @@ -797,7 +1112,7 @@ private byte[] uri2data(IRI uri, boolean create) throws IOException { return uriData; } - private byte[] bnode2data(BNode bNode, boolean create) throws IOException { + private byte[] bnode2data(BNode bNode, boolean create) { byte[] idData = bNode.getID().getBytes(StandardCharsets.UTF_8); byte[] bNodeData = new byte[1 + idData.length]; @@ -893,7 +1208,7 @@ private LmdbIRI data2uri(long id, byte[] data, LmdbIRI value) throws IOException } } - private LmdbBNode data2bnode(long id, byte[] data, LmdbBNode value) throws IOException { + private LmdbBNode data2bnode(long id, byte[] data, LmdbBNode value) { String nodeID = new String(data, 1, data.length - 1, StandardCharsets.UTF_8); if (value == null) { return new LmdbBNode(revision, nodeID, id); @@ -1096,4 +1411,8 @@ public LmdbLiteral getLmdbLiteral(Literal l) { return new LmdbLiteral(revision, l.getLabel(), datatype, l.getCoreDatatype()); } } -} + + public void forceEvictionOfValues() { + nextValueEvictionTime = 0L; + } +} \ No newline at end of file diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ValueStoreRevision.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ValueStoreRevision.java index f64eeadbfa0..55703efd865 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ValueStoreRevision.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/ValueStoreRevision.java @@ -11,6 +11,7 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.Serializable; +import java.util.Objects; import org.eclipse.rdf4j.sail.lmdb.model.LmdbValue; @@ -19,37 +20,85 @@ * LmdbValue to be valid, the revision object needs to be equal to the concerning ValueStore's revision object. The * ValueStore's revision object is changed whenever values are removed from it or IDs are changed. */ -public class ValueStoreRevision implements Serializable { +public interface ValueStoreRevision { + abstract class Base implements ValueStoreRevision { + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof ValueStoreRevision)) { + return false; + } + ValueStoreRevision other = (ValueStoreRevision) o; + return getRevisionId() == other.getRevisionId() && Objects.equals(getValueStore(), other.getValueStore()); + } - /*-----------* - * Constants * - *-----------*/ + @Override + public int hashCode() { + return Objects.hash(getValueStore(), getRevisionId()); + } + } - private static final long serialVersionUID = -2434063125560285009L; + class Default extends Base implements Serializable { + private static final long serialVersionUID = -2434063125560285009L; - /*-----------* - * Variables * - *-----------*/ + private static volatile long revisionIdCounter = 0; - transient private final ValueStore valueStore; + transient private final ValueStore valueStore; - /*--------------* - * Constructors * - *--------------*/ + private final long revisionId = ++revisionIdCounter; - public ValueStoreRevision(ValueStore valueStore) { - this.valueStore = valueStore; - } + public Default(ValueStore valueStore) { + this.valueStore = valueStore; + } + + public long getRevisionId() { + return revisionId; + } - /*---------* - * Methods * - *---------*/ + public ValueStore getValueStore() { + return valueStore; + } - public ValueStore getValueStore() { - return valueStore; + public boolean resolveValue(long id, LmdbValue value) { + return valueStore.resolveValue(id, value); + } } - public boolean resolveValue(long id, LmdbValue value) { - return valueStore.resolveValue(id, value); + class Lazy extends Base implements Serializable { + private static final long serialVersionUID = -2434063125560285009L; + + private final ValueStoreRevision revision; + + public Lazy(ValueStoreRevision revision) { + this.revision = revision; + } + + @Override + public long getRevisionId() { + return revision.getRevisionId(); + } + + @Override + public ValueStore getValueStore() { + return revision.getValueStore(); + } + + @Override + public boolean resolveValue(long id, LmdbValue value) { + if (revision.resolveValue(id, value)) { + // set unwrapped version of revision + value.setInternalID(id, revision); + return true; + } + return false; + } } + + long getRevisionId(); + + ValueStore getValueStore(); + + boolean resolveValue(long id, LmdbValue value); } diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbBNode.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbBNode.java index 6d764e94c2c..eeab5e74797 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbBNode.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbBNode.java @@ -83,7 +83,7 @@ public String getID() { return super.getID(); } - protected void init() { + public void init() { if (!initialized) { synchronized (this) { if (!initialized) { diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbIRI.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbIRI.java index 0c4806be299..8bc261d44d0 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbIRI.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbIRI.java @@ -99,7 +99,7 @@ public String stringValue() { return super.stringValue(); } - protected void init() { + public void init() { if (!initialized) { synchronized (this) { if (!initialized) { diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbLiteral.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbLiteral.java index 06f3be84c6f..d6efea7435d 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbLiteral.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbLiteral.java @@ -192,7 +192,7 @@ public void setLanguage(String language) { this.language = language; } - protected void init() { + public void init() { if (!initialized) { synchronized (this) { if (!initialized) { diff --git a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbValue.java b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbValue.java index e617e9b66db..27cfe423baa 100644 --- a/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbValue.java +++ b/core/sail/lmdb/src/main/java/org/eclipse/rdf4j/sail/lmdb/model/LmdbValue.java @@ -29,6 +29,11 @@ public interface LmdbValue extends Value { */ long getInternalID(); + /** + * Initializes this value if it was a lazy value (ID-only value) before. + */ + void init(); + /** * Gets the revision of the value store that created this value. The value's internal ID is only valid when it's * value store revision is equal to the value store's current revision. diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/CardinalityTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/CardinalityTest.java index bf4083803ee..1b4aebe72fd 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/CardinalityTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/CardinalityTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.File; -import java.io.IOException; import java.util.Random; import org.eclipse.rdf4j.sail.lmdb.TxnManager.Txn; @@ -42,7 +41,7 @@ public void before() throws Exception { tripleStore = new TripleStore(dataDir, new LmdbStoreConfig("spoc,posc")); } - int count(RecordIterator it) throws IOException { + int count(RecordIterator it) { int count = 0; while (it.next() != null) { count++; diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/ContextStoreTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/ContextStoreTest.java index 277f51b06fa..48a801c5dbe 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/ContextStoreTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/ContextStoreTest.java @@ -53,26 +53,26 @@ public void setUp(@TempDir File tmpDir) throws Exception { } @Test - public void testIncrementNew() throws Exception { + public void testIncrementNew() { subject.increment(g1); assertThat(countContexts(subject)).isEqualTo(1); } @Test - public void testIncrementNewBNode() throws Exception { + public void testIncrementNewBNode() { subject.increment(g2); assertThat(countContexts(subject)).isEqualTo(1); } @Test - public void testIncrementExisting() throws Exception { + public void testIncrementExisting() { subject.increment(g1); subject.increment(g1); assertThat(countContexts(subject)).isEqualTo(1); } @Test - public void testDecrementExisting() throws Exception { + public void testDecrementExisting() { subject.increment(g1); subject.increment(g1); @@ -84,7 +84,7 @@ public void testDecrementExisting() throws Exception { } @Test - public void testDecrementExistingBySeveral() throws Exception { + public void testDecrementExistingBySeveral() { subject.increment(g1); subject.increment(g1); @@ -93,7 +93,7 @@ public void testDecrementExistingBySeveral() throws Exception { } @Test - public void testDecrementExistingBNode() throws Exception { + public void testDecrementExistingBNode() { subject.increment(g2); subject.increment(g2); @@ -105,7 +105,7 @@ public void testDecrementExistingBNode() throws Exception { } @Test - public void testDecrementNonExisting() throws Exception { + public void testDecrementNonExisting() { subject.decrementBy(g1, 1); assertThat(countContexts(subject)).isEqualTo(0); } diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbCascadeValueExceptionTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbCascadeValueExceptionTest.java index 4e1908488a0..b5dfeca9cbb 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbCascadeValueExceptionTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbCascadeValueExceptionTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -24,7 +23,7 @@ public class LmdbCascadeValueExceptionTest extends CascadeValueExceptionTest { File dataDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new LmdbStore(dataDir, new LmdbStoreConfig("spoc"))); } } diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbGraphQueryResultTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbGraphQueryResultTest.java index 35c85d71693..2154068d474 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbGraphQueryResultTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbGraphQueryResultTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -24,7 +23,7 @@ public class LmdbGraphQueryResultTest extends GraphQueryResultTest { File dataDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new LmdbStore(dataDir, new LmdbStoreConfig("spoc"))); } } diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSailStoreTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSailStoreTest.java index 5365fb38693..2e416067a18 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSailStoreTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSailStoreTest.java @@ -55,7 +55,7 @@ public class LmdbSailStoreTest { F.createLiteral("two")); @BeforeEach - public void before(@TempDir File dataDir) throws Exception { + public void before(@TempDir File dataDir) { repo = new SailRepository(new LmdbStore(dataDir, new LmdbStoreConfig("spoc,posc"))); repo.init(); @@ -194,7 +194,7 @@ public void testPassConnectionBetweenThreadsWithTx() throws InterruptedException } @AfterEach - public void after() throws Exception { + public void after() { repo.shutDown(); } } diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSparqlOrderByTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSparqlOrderByTest.java index 944cf4c127b..8ef93023fc1 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSparqlOrderByTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSparqlOrderByTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -25,7 +24,7 @@ public class LmdbSparqlOrderByTest extends SparqlOrderByTest { File dataDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new LmdbStore(dataDir, new LmdbStoreConfig("spoc"))); } } diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSparqlRegexTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSparqlRegexTest.java index 391590c5f78..216f8a323e1 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSparqlRegexTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSparqlRegexTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -24,7 +23,7 @@ public class LmdbSparqlRegexTest extends SparqlRegexTest { File dataDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new LmdbStore(dataDir, new LmdbStoreConfig("spoc"))); } } diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreConnectionTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreConnectionTest.java index 8767ed227ec..c6785e1ba60 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreConnectionTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreConnectionTest.java @@ -13,7 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.common.transaction.IsolationLevel; @@ -28,13 +27,13 @@ public class LmdbStoreConnectionTest extends RepositoryConnectionTest { @Override - protected Repository createRepository(File dataDir) throws IOException { + protected Repository createRepository(File dataDir) { return new SailRepository(new LmdbStore(dataDir, new LmdbStoreConfig("spoc"))); } @ParameterizedTest @MethodSource("parameters") - public void testSES715(IsolationLevel level) throws Exception { + public void testSES715(IsolationLevel level) { setupTest(level); // load 1000 triples in two different contexts diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreDirLockTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreDirLockTest.java index 00595b8df51..6070df83179 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreDirLockTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreDirLockTest.java @@ -23,7 +23,7 @@ public class LmdbStoreDirLockTest { @Test - public void testLocking(@TempDir File dataDir) throws Exception { + public void testLocking(@TempDir File dataDir) { LmdbStore sail = new LmdbStore(dataDir, new LmdbStoreConfig("spoc,posc")); sail.init(); diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreErrorHandlingTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreErrorHandlingTest.java index 30769788436..2b22f2d9cf4 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreErrorHandlingTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreErrorHandlingTest.java @@ -29,7 +29,7 @@ public class LmdbStoreErrorHandlingTest { @Test - public void testMapFullError(@TempDir File dataDir) throws Exception { + public void testMapFullError(@TempDir File dataDir) { LmdbStoreConfig config = new LmdbStoreConfig("spoc,psoc"); // set small db size config.setValueDBSize(50000); diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreRepositoryTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreRepositoryTest.java index 3b72cf4e747..25a9cb69577 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreRepositoryTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreRepositoryTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -24,7 +23,7 @@ public class LmdbStoreRepositoryTest extends RepositoryTest { public File dataDir; @Override - protected Repository createRepository() throws IOException { + protected Repository createRepository() { return new SailRepository(new LmdbStore(dataDir, new LmdbStoreConfig("spoc"))); } } diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreTest.java index db3b1420b40..c752a56d66f 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreTest.java @@ -51,7 +51,7 @@ protected NotifyingSail createSail() throws SailException { // Test for SES-542 @Test - public void testGetNamespacePersistence() throws Exception { + public void testGetNamespacePersistence() { con.begin(); con.setNamespace("rdf", RDF.NAMESPACE); con.commit(); @@ -66,7 +66,7 @@ public void testGetNamespacePersistence() throws Exception { } @Test - public void testContextCacheReconstruction() throws Exception { + public void testContextCacheReconstruction() { con.begin(); con.addStatement(RDF.TYPE, RDF.TYPE, RDF.TYPE, RDF.ALT); con.commit(); diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreTmpDatadirTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreTmpDatadirTest.java index 90034460bd5..b13bc24ec88 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreTmpDatadirTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbStoreTmpDatadirTest.java @@ -14,7 +14,6 @@ import static org.junit.Assert.assertTrue; import java.io.File; -import java.io.IOException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -22,7 +21,7 @@ public class LmdbStoreTmpDatadirTest { @Test - public void testNoTmpDatadir(@TempDir File dataDir) throws IOException { + public void testNoTmpDatadir(@TempDir File dataDir) { LmdbStore store = new LmdbStore(dataDir); store.init(); @@ -33,7 +32,7 @@ public void testNoTmpDatadir(@TempDir File dataDir) throws IOException { } @Test - public void testTmpDatadir() throws IOException { + public void testTmpDatadir() { LmdbStore store = new LmdbStore(); store.init(); File dataDir = store.getDataDir(); @@ -44,7 +43,7 @@ public void testTmpDatadir() throws IOException { } @Test - public void testTmpDatadirReinit() throws IOException { + public void testTmpDatadirReinit() { LmdbStore store = new LmdbStore(); store.init(); File dataDir1 = store.getDataDir(); @@ -57,7 +56,7 @@ public void testTmpDatadirReinit() throws IOException { } @Test - public void testDatadirMix(@TempDir File dataDir) throws IOException { + public void testDatadirMix(@TempDir File dataDir) { LmdbStore store = new LmdbStore(dataDir); store.init(); diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbTupleQueryResultTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbTupleQueryResultTest.java index d731aef1b9e..424f3532924 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbTupleQueryResultTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbTupleQueryResultTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.lmdb; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -25,7 +24,7 @@ public class LmdbTupleQueryResultTest extends TupleQueryResultTest { File tempDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new LmdbStore(tempDir, new LmdbStoreConfig("spoc"))); } } diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/QueryBenchmarkTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/QueryBenchmarkTest.java index 9cd9e1063fe..8f830d72c26 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/QueryBenchmarkTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/QueryBenchmarkTest.java @@ -85,7 +85,7 @@ private static InputStream getResourceAsStream(String name) { } @AfterAll - public static void afterClass() throws IOException { + public static void afterClass() { tempDir.delete(); repository.shutDown(); tempDir = null; diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TestLmdbStoreMemoryOverflow.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TestLmdbStoreMemoryOverflow.java index c8e397b43da..e6d79818d22 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TestLmdbStoreMemoryOverflow.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TestLmdbStoreMemoryOverflow.java @@ -13,7 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.Iterations; @@ -43,7 +42,7 @@ public class TestLmdbStoreMemoryOverflow { private RepositoryConnection testCon2; @BeforeEach - public void setUp(@TempDir File dataDir) throws Exception { + public void setUp(@TempDir File dataDir) { testRepository = createRepository(dataDir); testRepository.init(); } @@ -58,12 +57,12 @@ private void setupConnections(IsolationLevel level) { testCon2.setIsolationLevel(level); } - private Repository createRepository(File dataDir) throws IOException { + private Repository createRepository(File dataDir) { return new SailRepository(new LmdbStore(dataDir, new LmdbStoreConfig("spoc"))); } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { testCon2.close(); testCon.close(); testRepository.shutDown(); @@ -71,7 +70,7 @@ public void tearDown() throws Exception { @ParameterizedTest @EnumSource(IsolationLevels.class) - public void test(IsolationLevel level) throws Exception { + public void test(IsolationLevel level) { setupConnections(level); int size = 10000; // this should really be bigger @@ -96,7 +95,7 @@ public void test(IsolationLevel level) throws Exception { testCon.close(); } - private static final class DynamicIteration implements CloseableIteration { + private static final class DynamicIteration implements CloseableIteration { private final int size; diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TestLmdbStoreUpgrade.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TestLmdbStoreUpgrade.java index d3b1e3a96a0..33de4e82687 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TestLmdbStoreUpgrade.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TestLmdbStoreUpgrade.java @@ -13,7 +13,6 @@ import static org.junit.Assert.assertTrue; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.Statement; @@ -31,7 +30,7 @@ public class TestLmdbStoreUpgrade { @Test - public void testDevel(@TempDir File dataDir) throws IOException, SailException { + public void testDevel(@TempDir File dataDir) throws SailException { LmdbStore store = new LmdbStore(dataDir); try { store.init(); @@ -55,7 +54,7 @@ public void assertValue(File dataDir) throws SailException { store.init(); try (NotifyingSailConnection con = store.getConnection()) { ValueFactory vf = store.getValueFactory(); - CloseableIteration iter; + CloseableIteration iter; iter = con.getStatements(RDF.VALUE, RDFS.LABEL, vf.createLiteral("value"), false); try { assertTrue(iter.hasNext()); diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TripleStoreAutoGrowTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TripleStoreAutoGrowTest.java new file mode 100644 index 00000000000..04c25dee20e --- /dev/null +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TripleStoreAutoGrowTest.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.sail.lmdb; + +import java.io.File; +import java.util.Random; + +import org.eclipse.rdf4j.sail.lmdb.TxnManager.Txn; +import org.eclipse.rdf4j.sail.lmdb.config.LmdbStoreConfig; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Logger; + +/** + * Low-level tests for {@link TripleStore}. + */ +public class TripleStoreAutoGrowTest { + + protected TripleStore tripleStore; + + @BeforeEach + public void before(@TempDir File dataDir) throws Exception { + var config = new LmdbStoreConfig("spoc,posc"); + config.setTripleDBSize(4096 * 10); + tripleStore = new TripleStore(dataDir, config); + ((Logger) LoggerFactory + .getLogger(TripleStore.class.getName())) + .setLevel(ch.qos.logback.classic.Level.DEBUG); + } + + @Test + public void testAutoGrowLargeCommits() throws Exception { + Random rnd = new Random(1337); + + Txn[] readTxns = new Txn[20]; + for (int i = 0; i < readTxns.length; i++) { + readTxns[i] = tripleStore.getTxnManager().createReadTxn(); + } + for (int subj = 1; subj < 50; subj++) { + tripleStore.startTransaction(); + for (int pred = 1; pred < 100; pred++) { + for (int obj = 1; obj < 100; obj++) { + tripleStore.storeTriple(1 + rnd.nextInt(1000), 1 + rnd.nextInt(1000), + 1 + rnd.nextInt(1000), 3, true); + } + } + tripleStore.commit(); + } + for (int i = 0; i < readTxns.length; i++) { + readTxns[i].close(); + } + } + + @Test + public void testAutoGrowSmallCommits() throws Exception { + Random rnd = new Random(1337); + + Txn[] readTxns = new Txn[20]; + for (int i = 0; i < readTxns.length; i++) { + readTxns[i] = tripleStore.getTxnManager().createReadTxn(); + } + for (int subj = 1; subj < 50; subj++) { + for (int pred = 1; pred < 100; pred++) { + tripleStore.startTransaction(); + for (int obj = 1; obj < 100; obj++) { + tripleStore.storeTriple(1 + rnd.nextInt(1000), 1 + rnd.nextInt(1000), + 1 + rnd.nextInt(1000), 3, true); + } + tripleStore.commit(); + } + } + for (int i = 0; i < readTxns.length; i++) { + readTxns[i].close(); + } + } + + @AfterEach + public void after() throws Exception { + tripleStore.close(); + } +} diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TripleStoreTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TripleStoreTest.java index 1d707ee9a35..6a159eecd5e 100644 --- a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TripleStoreTest.java +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/TripleStoreTest.java @@ -13,7 +13,6 @@ import static org.junit.Assert.assertEquals; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.sail.lmdb.TxnManager.Txn; import org.eclipse.rdf4j.sail.lmdb.config.LmdbStoreConfig; @@ -33,7 +32,7 @@ public void before(@TempDir File dataDir) throws Exception { tripleStore = new TripleStore(dataDir, new LmdbStoreConfig("spoc,posc")); } - int count(RecordIterator it) throws IOException { + int count(RecordIterator it) { int count = 0; while (it.next() != null) { count++; diff --git a/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/ValueStoreTest.java b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/ValueStoreTest.java new file mode 100644 index 00000000000..0a4c9d3c866 --- /dev/null +++ b/core/sail/lmdb/src/test/java/org/eclipse/rdf4j/sail/lmdb/ValueStoreTest.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.sail.lmdb; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Random; +import java.util.Set; + +import org.eclipse.rdf4j.sail.lmdb.config.LmdbStoreConfig; +import org.eclipse.rdf4j.sail.lmdb.model.LmdbValue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Low-level tests for {@link ValueStore}. + */ +public class ValueStoreTest { + + private ValueStore valueStore; + private File dataDir; + + @BeforeEach + public void before(@TempDir File dataDir) throws Exception { + this.dataDir = dataDir; + this.valueStore = createValueStore(); + } + + private ValueStore createValueStore() throws IOException { + return new ValueStore(new File(dataDir, "values"), new LmdbStoreConfig()); + } + + @Test + public void testGcValues() throws Exception { + Random random = new Random(1337); + LmdbValue values[] = new LmdbValue[1000]; + valueStore.startTransaction(); + for (int i = 0; i < values.length; i++) { + values[i] = valueStore.createLiteral("This is a random literal:" + random.nextLong()); + valueStore.storeValue(values[i]); + } + valueStore.commit(); + + ValueStoreRevision revBefore = valueStore.getRevision(); + + valueStore.startTransaction(); + Set ids = new HashSet<>(); + for (int i = 0; i < 30; i++) { + ids.add(values[i].getInternalID()); + } + valueStore.gcIds(ids); + valueStore.commit(); + + ValueStoreRevision revAfter = valueStore.getRevision(); + + assertNotEquals("revisions must change after gc of IDs", revBefore, revAfter); + + Arrays.fill(values, null); + // GC would collect revision at some point in time + // just add revision ID to free list for this test as forcing GC is not possible + valueStore.unusedRevisionIds.add(revBefore.getRevisionId()); + + valueStore.forceEvictionOfValues(); + valueStore.startTransaction(); + valueStore.commit(); + + valueStore.startTransaction(); + for (int i = 0; i < 30; i++) { + LmdbValue value = valueStore.createLiteral("This is a random literal:" + random.nextLong()); + values[i] = value; + valueStore.storeValue(value); + // this ID should have been reused + ids.remove(value.getInternalID()); + } + valueStore.commit(); + + assertEquals("IDs should have been reused", Collections.emptySet(), ids); + } + + @Test + public void testGcValuesAfterRestart() throws Exception { + Random random = new Random(1337); + LmdbValue values[] = new LmdbValue[1000]; + valueStore.startTransaction(); + for (int i = 0; i < values.length; i++) { + values[i] = valueStore.createLiteral("This is a random literal:" + random.nextLong()); + valueStore.storeValue(values[i]); + } + valueStore.commit(); + + valueStore.startTransaction(); + Set ids = new HashSet<>(); + for (int i = 0; i < 30; i++) { + ids.add(values[i].getInternalID()); + } + valueStore.gcIds(ids); + valueStore.commit(); + + // close and recreate store + valueStore.close(); + valueStore = createValueStore(); + + valueStore.startTransaction(); + for (int i = 0; i < 30; i++) { + LmdbValue value = valueStore.createLiteral("This is a random literal:" + random.nextLong()); + values[i] = value; + valueStore.storeValue(value); + // this ID should have been reused + ids.remove(value.getInternalID()); + } + valueStore.commit(); + + assertEquals("IDs should have been reused", Collections.emptySet(), ids); + } + + @AfterEach + public void after() throws Exception { + valueStore.close(); + } +} diff --git a/core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/LuceneSailConnection.java b/core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/LuceneSailConnection.java index 32356f8aea7..db3f3f7ff33 100644 --- a/core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/LuceneSailConnection.java +++ b/core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/LuceneSailConnection.java @@ -307,7 +307,7 @@ private void completeAddRemoveOperationWithType(AddRemoveOperation op) throws Sa // not inside the update statement, searching with the connection for (IRI predicate : mapping.keySet()) { Set objects = mapping.get(predicate); - try (CloseableIteration statements = getStatements( + try (CloseableIteration statements = getStatements( stmt.getSubject(), predicate, null, @@ -337,7 +337,7 @@ private void completeAddRemoveOperationWithType(AddRemoveOperation op) throws Sa for (Map.Entry e : typeAdd.entrySet()) { if (e.getValue()) { Resource subject = e.getKey(); - try (CloseableIteration statements = getStatements( + try (CloseableIteration statements = getStatements( subject, null, null, false )) { while (statements.hasNext()) { @@ -359,7 +359,7 @@ private void completeAddRemoveOperationWithType(AddRemoveOperation op) throws Sa // backtrace previous insert of property and delete them from the index if (backtraceMode.shouldBackTraceDelete()) { for (Resource subject : typeRemove) { - try (CloseableIteration statements = getStatements( + try (CloseableIteration statements = getStatements( subject, null, null, false )) { while (statements.hasNext()) { @@ -395,12 +395,12 @@ private void clearContexts(Resource... contexts) throws IOException { // //////////////////////////////// Methods related to querying @Override - public synchronized CloseableIteration evaluate(TupleExpr tupleExpr, + public synchronized CloseableIteration evaluate(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { QueryContext qctx = new QueryContext(); SearchIndexQueryContextInitializer.init(qctx, luceneIndex); - final CloseableIteration iter; + final CloseableIteration iter; qctx.begin(); try { iter = evaluateInternal(tupleExpr, dataset, bindings, includeInferred); @@ -413,7 +413,7 @@ public synchronized CloseableIteration evaluateInternal(TupleExpr tupleExpr, + private CloseableIteration evaluateInternal(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { // Don't modify the original tuple expression tupleExpr = tupleExpr.clone(); diff --git a/core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/config/AbstractLuceneSailConfig.java b/core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/config/AbstractLuceneSailConfig.java index 256061741da..0fb6d69e546 100644 --- a/core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/config/AbstractLuceneSailConfig.java +++ b/core/sail/lucene-api/src/main/java/org/eclipse/rdf4j/sail/lucene/config/AbstractLuceneSailConfig.java @@ -29,9 +29,6 @@ public abstract class AbstractLuceneSailConfig extends AbstractDelegatingSailImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private static final String PARAMETER_PREFIX = "lucene."; private String indexDir; @@ -85,19 +82,11 @@ public Resource export(Model m) { m.setNamespace(CONFIG.NS); if (indexDir != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Lucene.indexDir, literal(indexDir)); - } else { - m.add(implNode, INDEX_DIR, literal(indexDir)); - } + m.add(implNode, CONFIG.Lucene.indexDir, literal(indexDir)); } for (String key : getParameterNames()) { - if (USE_CONFIG) { - m.add(implNode, iri(CONFIG.NAMESPACE, PARAMETER_PREFIX + key), literal(getParameter(key))); - } else { - m.add(implNode, iri(LuceneSailConfigSchema.NAMESPACE, key), literal(getParameter(key))); - } + m.add(implNode, iri(CONFIG.NAMESPACE, PARAMETER_PREFIX + key), literal(getParameter(key))); } return implNode; diff --git a/core/sail/lucene-api/src/test/java/org/eclipse/rdf4j/sail/lucene/QuerySpecBuilderTest.java b/core/sail/lucene-api/src/test/java/org/eclipse/rdf4j/sail/lucene/QuerySpecBuilderTest.java index 489ca4be1ae..89c474e0d44 100644 --- a/core/sail/lucene-api/src/test/java/org/eclipse/rdf4j/sail/lucene/QuerySpecBuilderTest.java +++ b/core/sail/lucene-api/src/test/java/org/eclipse/rdf4j/sail/lucene/QuerySpecBuilderTest.java @@ -43,7 +43,7 @@ public class QuerySpecBuilderTest { private SPARQLParser parser; @BeforeEach - public void setUp() throws Exception { + public void setUp() { interpreter = new QuerySpecBuilder(true); parser = new SPARQLParser(); } @@ -295,10 +295,9 @@ public void testQueryInterpretationMulti() { /** * Incomplete queries should fail, if configured * - * @throws Exception */ @Test - public void testIncompleteFail() throws Exception { + public void testIncompleteFail() { // default works String queryString = "SELECT ?sub1 ?score1 ?snippet1 WHERE " + "{ ?sub1 <" + MATCHES + "> [ " + "<" + TYPE + "> <" + LUCENE_QUERY + ">; " + "<" + QUERY + "> \"my Lucene query\"; " + "<" + SCORE @@ -351,7 +350,7 @@ public void testIncompleteFail() throws Exception { * * @param queryString */ - private void checkQuery(String queryString) throws Exception { + private void checkQuery(String queryString) { ParsedQuery query = parser.parseQuery(queryString, null); TupleExpr tupleExpr = query.getTupleExpr(); Collection queries = process(interpreter, tupleExpr); diff --git a/core/sail/lucene-api/src/test/java/org/eclipse/rdf4j/sail/lucene/SearchQueryEvaluatorTest.java b/core/sail/lucene-api/src/test/java/org/eclipse/rdf4j/sail/lucene/SearchQueryEvaluatorTest.java index 8d42792c3f5..541e99a6af1 100644 --- a/core/sail/lucene-api/src/test/java/org/eclipse/rdf4j/sail/lucene/SearchQueryEvaluatorTest.java +++ b/core/sail/lucene-api/src/test/java/org/eclipse/rdf4j/sail/lucene/SearchQueryEvaluatorTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.lucene; -import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -45,7 +44,7 @@ protected class SearchIndexImpl implements SearchIndex { protected Set wktFields = Collections.singleton(SearchFields.getPropertyField(GEO.AS_WKT)); @Override - public void initialize(Properties parameters) throws Exception { + public void initialize(Properties parameters) { } @Override @@ -54,7 +53,7 @@ public Collection evaluate(SearchQueryEvaluator query) throws SailEx } @Override - public void shutDown() throws IOException { + public void shutDown() { } @Override @@ -88,39 +87,39 @@ public Map> getIndexedTypeMapping() { } @Override - public void begin() throws IOException { + public void begin() { } @Override - public void commit() throws IOException { + public void commit() { } @Override - public void rollback() throws IOException { + public void rollback() { } @Override - public void addStatement(Statement statement) throws IOException { + public void addStatement(Statement statement) { } @Override - public void removeStatement(Statement statement) throws IOException { + public void removeStatement(Statement statement) { } @Override - public void addRemoveStatements(Collection added, Collection removed) throws IOException { + public void addRemoveStatements(Collection added, Collection removed) { } @Override - public void clearContexts(Resource... contexts) throws IOException { + public void clearContexts(Resource... contexts) { } @Override - public void addDocuments(Resource subject, List statements) throws IOException { + public void addDocuments(Resource subject, List statements) { } @Override - public void clear() throws IOException { + public void clear() { } } } diff --git a/core/sail/lucene/src/main/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneDocument.java b/core/sail/lucene/src/main/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneDocument.java index f034d429ab7..0cedceaf2e3 100644 --- a/core/sail/lucene/src/main/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneDocument.java +++ b/core/sail/lucene/src/main/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneDocument.java @@ -46,14 +46,6 @@ public class LuceneDocument implements SearchDocument { private final Function geoStrategyMapper; - /** - * To be removed, no longer used. - */ - @Deprecated(forRemoval = true) - public LuceneDocument() { - this(null); - } - public LuceneDocument(Function geoStrategyMapper) { this(new Document(), geoStrategyMapper); } diff --git a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneFuzzinessPrefixTest.java b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneFuzzinessPrefixTest.java index 4a0c53d7475..753c8e73d32 100644 --- a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneFuzzinessPrefixTest.java +++ b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneFuzzinessPrefixTest.java @@ -15,7 +15,6 @@ import static org.eclipse.rdf4j.sail.lucene.LuceneSail.FUZZY_PREFIX_LENGTH_KEY; import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -56,7 +55,7 @@ private static String joinLines(String... lines) { private File dataDir; @BeforeEach - public void setup() throws IOException { + public void setup() { memoryStore = new MemoryStore(); sail = new LuceneSail(); sail.setParameter(LuceneSail.LUCENE_DIR_KEY, "lucene-index"); diff --git a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneIndexIdFilteringTest.java b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneIndexIdFilteringTest.java index c406d3faa6b..ce8a2d5bc0e 100644 --- a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneIndexIdFilteringTest.java +++ b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/LuceneIndexIdFilteringTest.java @@ -15,7 +15,6 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -62,7 +61,7 @@ private static String joinLines(String... lines) { SailRepository repository; @BeforeEach - public void setup(@TempDir File dataDir) throws IOException { + public void setup(@TempDir File dataDir) { // sails schema // sailType1(LuceneSail) -> sailType2(LuceneSail) -> sailType3(LuceneSail) -> memoryStore(MemoryStore) diff --git a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/TypeSpecTest.java b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/TypeSpecTest.java index 97546c861ae..bf1f6328516 100644 --- a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/TypeSpecTest.java +++ b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/TypeSpecTest.java @@ -13,7 +13,6 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.File; -import java.io.IOException; import java.util.Set; import org.eclipse.rdf4j.model.Statement; @@ -74,7 +73,7 @@ private static Statement literal(String subject, String value) { File dataDir; @BeforeEach - public void setup() throws IOException { + public void setup() { memoryStore = new MemoryStore(); // enable lock tracking sail = new LuceneSail(); diff --git a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/impl/AbstractGenericLuceneTest.java b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/impl/AbstractGenericLuceneTest.java index 6aa8edd5169..1e09c30169e 100644 --- a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/impl/AbstractGenericLuceneTest.java +++ b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/impl/AbstractGenericLuceneTest.java @@ -151,7 +151,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws IOException, RepositoryException { + public void tearDown() throws RepositoryException { try { if (connection != null) { connection.close(); @@ -459,7 +459,7 @@ public void testSnippetLimitedToPredicate() } @Test - public void testCharlyTerm() throws Exception { + public void testCharlyTerm() { try (RepositoryConnection localConnection = repository.getConnection()) { localConnection.begin(); @@ -617,10 +617,9 @@ public void testUnionQuery() throws RepositoryException, MalformedQueryException /** * Tests adding data to two contexts (graphs). * - * @throws Exception */ @Test - public void testContextHandling() throws Exception { + public void testContextHandling() { connection.add(SUBJECT_4, PREDICATE_1, vf.createLiteral("sfourponecone"), CONTEXT_1); connection.add(SUBJECT_4, PREDICATE_2, vf.createLiteral("sfourptwocone"), CONTEXT_1); connection.add(SUBJECT_5, PREDICATE_1, vf.createLiteral("sfiveponecone"), CONTEXT_1); @@ -651,10 +650,9 @@ public void testContextHandling() throws Exception { /** * we experienced problems with the NULL context and lucenesail in August 2008 * - * @throws Exception */ @Test - public void testNullContextHandling() throws Exception { + public void testNullContextHandling() { connection.add(SUBJECT_4, PREDICATE_1, vf.createLiteral("sfourponecone")); connection.add(SUBJECT_4, PREDICATE_2, vf.createLiteral("sfourptwocone")); connection.add(SUBJECT_5, PREDICATE_1, vf.createLiteral("sfiveponecone")); @@ -727,10 +725,9 @@ public void testFuzzyQuery() throws MalformedQueryException, RepositoryException /** * Checks if reindexing does not corrupt the new index and if complex query still is evaluated properly. * - * @throws Exception */ @Test - public void testReindexing() throws Exception { + public void testReindexing() { sail.reindex(); testComplexQueryTwo(); } @@ -805,7 +802,7 @@ public void run() { } @Test - public void testIndexWriterState() throws Exception { + public void testIndexWriterState() { final String brokenTrig = "{ broken }"; RepositoryConnection conn = repository.getConnection(); try (StringReader sr = new StringReader(brokenTrig)) { @@ -821,7 +818,7 @@ public void testIndexWriterState() throws Exception { conn.close(); } - protected void assertQueryResult(String literal, IRI predicate, Resource resultUri) throws Exception { + protected void assertQueryResult(String literal, IRI predicate, Resource resultUri) { // fire a query for all subjects with a given term String queryString = "SELECT ?Resource " + "WHERE { ?Resource <" + MATCHES + "> [ " + " <" + QUERY + "> \"" + literal + "\" ]. } "; @@ -837,7 +834,7 @@ protected void assertQueryResult(String literal, IRI predicate, Resource resultU } } - protected void assertNoQueryResult(String literal) throws Exception { + protected void assertNoQueryResult(String literal) { // fire a query for all subjects with a given term String queryString = "SELECT ?Resource " + "WHERE { ?Resource <" + MATCHES + "> [ " + " <" + QUERY + "> \"" + literal + "\" ]. } "; diff --git a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneIndexLocationTest.java b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneIndexLocationTest.java index a21adea06ae..46fa5974035 100644 --- a/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneIndexLocationTest.java +++ b/core/sail/lucene/src/test/java/org/eclipse/rdf4j/sail/lucene/impl/LuceneIndexLocationTest.java @@ -14,7 +14,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; -import java.io.IOException; import java.nio.file.Path; import java.util.stream.IntStream; @@ -56,10 +55,9 @@ public class LuceneIndexLocationTest { /** * Set up memory storage located within temporary folder * - * @throws Exception */ @BeforeEach - public void setUp(@TempDir File dataDir) throws Exception { + public void setUp(@TempDir File dataDir) { sail = new MemoryStore(); LuceneSail lucene = new LuceneSail(); @@ -83,7 +81,7 @@ public void setUp(@TempDir File dataDir) throws Exception { } @AfterEach - public void tearDown() throws IOException, RepositoryException { + public void tearDown() throws RepositoryException { try { if (connection != null) { connection.close(); @@ -98,10 +96,9 @@ public void tearDown() throws IOException, RepositoryException { /** * Check Lucene index location * - * @throws Exception */ @Test - public void IndexLocationTest() throws Exception { + public void IndexLocationTest() { File dataDir = repository.getDataDir(); Path lucenePath = repository.getDataDir().toPath().resolve(luceneIndexPath); diff --git a/core/sail/memory/pom.xml b/core/sail/memory/pom.xml index 818c38c4a0c..40795682b14 100644 --- a/core/sail/memory/pom.xml +++ b/core/sail/memory/pom.xml @@ -87,10 +87,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/FileIO.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/FileIO.java index 8bd76bdcb82..156fb2dbcb3 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/FileIO.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/FileIO.java @@ -200,7 +200,7 @@ public synchronized void read(File dataFile, SailSink explicit, SailSink inferre } private void writeNamespaces(SailDataset store, DataOutputStream dataOut) throws IOException, SailException { - try (CloseableIteration iter = store.getNamespaces()) { + try (CloseableIteration iter = store.getNamespaces()) { while (iter.hasNext()) { Namespace ns = iter.next(); dataOut.writeByte(NAMESPACE_MARKER); @@ -230,7 +230,7 @@ private void writeStatements(final SailDataset explicit, SailDataset inferred, D writeStatement(inferred.getStatements(null, null, null), INF_TRIPLE_MARKER, INF_QUAD_MARKER, dataOut); } - public void writeStatement(CloseableIteration stIter, int tripleMarker, + public void writeStatement(CloseableIteration stIter, int tripleMarker, int quadMarker, DataOutputStream dataOut) throws IOException, SailException { try (stIter) { while (stIter.hasNext()) { diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/MemorySailStore.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/MemorySailStore.java index 59aca80393d..abea50b07d6 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/MemorySailStore.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/MemorySailStore.java @@ -87,8 +87,8 @@ class MemorySailStore implements SailStore { // we prioritise cleanup if there is less than 128 MB of free memory. private static final double CLEANUP_MINIMUM_FREE_MEMORY_RATIO = 1.0 / 8; - public static final EmptyIteration EMPTY_ITERATION = new EmptyIteration<>(); - public static final EmptyIteration EMPTY_TRIPLE_ITERATION = new EmptyIteration<>(); + public static final EmptyIteration EMPTY_ITERATION = new EmptyIteration<>(); + public static final EmptyIteration EMPTY_TRIPLE_ITERATION = new EmptyIteration<>(); public static final MemResource[] EMPTY_CONTEXT = {}; public static final MemResource[] NULL_CONTEXT = { null }; @@ -195,7 +195,7 @@ public SailSource getInferredSailSource() { * Statements from the null context are excluded when namedContextsOnly is set to true. The * returned StatementIterator will assume the specified read mode. */ - private CloseableIteration createStatementIterator(Resource subj, IRI pred, Value obj, + private CloseableIteration createStatementIterator(Resource subj, IRI pred, Value obj, Boolean explicit, int snapshot, Resource... contexts) throws InterruptedException { // Perform look-ups for value-equivalents of the specified values @@ -269,7 +269,7 @@ private CloseableIteration createStatementIterator( return getMemStatementIterator(memSubj, memPred, memObj, explicit, snapshot, memContexts, smallestList); } - private CloseableIteration getMemStatementIterator(MemResource subj, MemIRI pred, + private CloseableIteration getMemStatementIterator(MemResource subj, MemIRI pred, MemValue obj, Boolean explicit, int snapshot, MemResource[] memContexts, MemStatementList statementList) throws InterruptedException { @@ -334,7 +334,7 @@ private MemStatementList getSmallestStatementList(MemResource subj, MemIRI pred, * Creates a TripleIterator that contains the triples matching the specified pattern of subject, predicate, object, * context. */ - private CloseableIteration createTripleIterator(Resource subj, IRI pred, Value obj, + private CloseableIteration createTripleIterator(Resource subj, IRI pred, Value obj, int snapshot) throws InterruptedException { // Perform look-ups for value-equivalents of the specified values @@ -615,7 +615,7 @@ public synchronized void prepare() throws SailException { } else { contexts = new Resource[] { (Resource) ctxVar.getValue() }; } - try (CloseableIteration iter = createStatementIterator(subj, pred, obj, + try (CloseableIteration iter = createStatementIterator(subj, pred, obj, null, -1, contexts)) { while (iter.hasNext()) { MemStatement st = iter.next(); @@ -725,7 +725,7 @@ public synchronized void clear(Resource... contexts) { acquireExclusiveTransactionLock(); invalidateCache(); requireCleanup = true; - try (CloseableIteration iter = createStatementIterator(null, null, null, + try (CloseableIteration iter = createStatementIterator(null, null, null, explicit, nextSnapshot, contexts)) { while (iter.hasNext()) { MemStatement st = iter.next(); @@ -802,7 +802,7 @@ private void innerDeprecate(Statement statement, int nextSnapshot) { toDeprecate.setTillSnapshot(nextSnapshot); } } else { - try (CloseableIteration iter = createStatementIterator( + try (CloseableIteration iter = createStatementIterator( statement.getSubject(), statement.getPredicate(), statement.getObject(), explicit, nextSnapshot, statement.getContext())) { while (iter.hasNext()) { @@ -917,7 +917,7 @@ public boolean deprecateByQuery(Resource subj, IRI pred, Value obj, Resource[] c requireCleanup = true; invalidateCache(); - try (CloseableIteration iter = createStatementIterator(subj, pred, obj, + try (CloseableIteration iter = createStatementIterator(subj, pred, obj, explicit, nextSnapshot, contexts)) { while (iter.hasNext()) { deprecated = true; @@ -991,12 +991,12 @@ public String getNamespace(String prefix) throws SailException { } @Override - public CloseableIteration getNamespaces() { + public CloseableIteration getNamespaces() { return new CloseableIteratorIteration<>(namespaceStore.iterator()); } @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { // Note: we can't do this in a streaming fashion due to concurrency // issues; iterating over the set of IRIs or bnodes while another // thread @@ -1036,7 +1036,7 @@ public CloseableIteration getContextIDs() thr } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { try { return createStatementIterator(subj, pred, obj, explicit, getCurrentSnapshot(), contexts); @@ -1046,7 +1046,7 @@ public CloseableIteration getStatements(Resource su } @Override - public CloseableIteration getTriples(Resource subj, IRI pred, Value obj) + public CloseableIteration getTriples(Resource subj, IRI pred, Value obj) throws SailException { try { return createTripleIterator(subj, pred, obj, getCurrentSnapshot()); diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/MemoryStoreConnection.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/MemoryStoreConnection.java index 9da3a84e855..c4123966a44 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/MemoryStoreConnection.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/MemoryStoreConnection.java @@ -45,7 +45,6 @@ protected MemoryStoreConnection(MemoryStore sail) { super(sail, sail.getSailStore(), sail.getEvaluationStrategyFactory()); this.sail = sail; sailChangedEvent = new DefaultSailChangedEvent(sail); - useConnectionLock = false; } /*---------* diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/config/MemoryStoreConfig.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/config/MemoryStoreConfig.java index 4889de81b30..e39bf75a1f7 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/config/MemoryStoreConfig.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/config/MemoryStoreConfig.java @@ -28,9 +28,6 @@ */ public class MemoryStoreConfig extends BaseSailConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private boolean persist = false; private long syncDelay = 0L; @@ -67,23 +64,34 @@ public void setSyncDelay(long syncDelay) { @Override public Resource export(Model m) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(m); + } + Resource implNode = super.export(m); m.setNamespace(CONFIG.NS); if (persist) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Mem.persist, BooleanLiteral.TRUE); - } else { - m.add(implNode, PERSIST, BooleanLiteral.TRUE); - } + m.add(implNode, CONFIG.Mem.persist, BooleanLiteral.TRUE); + } + + if (syncDelay != 0) { + m.add(implNode, CONFIG.Mem.syncDelay, literal(syncDelay)); + } + + return implNode; + } + + private Resource exportLegacy(Model m) { + Resource implNode = super.export(m); + m.setNamespace("ms", MemoryStoreSchema.NAMESPACE); + + if (persist) { + m.add(implNode, PERSIST, BooleanLiteral.TRUE); } if (syncDelay != 0) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Mem.syncDelay, literal(syncDelay)); - } else { - m.add(implNode, SYNC_DELAY, literal(syncDelay)); - } + m.add(implNode, SYNC_DELAY, literal(syncDelay)); } return implNode; diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/BooleanMemLiteral.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/BooleanMemLiteral.java index f63bf89c967..76c90908ab1 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/BooleanMemLiteral.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/BooleanMemLiteral.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.memory.model; -import org.eclipse.rdf4j.model.vocabulary.XSD; +import org.eclipse.rdf4j.model.base.CoreDatatype; /** * An extension of MemLiteral that stores a boolean value to avoid parsing. @@ -37,7 +37,7 @@ public BooleanMemLiteral(Object creator, boolean b) { } public BooleanMemLiteral(Object creator, String label, boolean b) { - super(creator, label, XSD.BOOLEAN); + super(creator, label, CoreDatatype.XSD.BOOLEAN); this.b = b; } diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/DecimalMemLiteral.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/DecimalMemLiteral.java index 6c1cdb2fc37..b69103d0048 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/DecimalMemLiteral.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/DecimalMemLiteral.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.base.CoreDatatype; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * An extension of MemLiteral that stores a decimal value to avoid parsing. @@ -37,18 +36,13 @@ public class DecimalMemLiteral extends MemLiteral { *--------------*/ public DecimalMemLiteral(Object creator, BigDecimal value) { - this(creator, value, XSD.DECIMAL); + this(creator, value, CoreDatatype.XSD.DECIMAL); } - public DecimalMemLiteral(Object creator, BigDecimal value, IRI datatype) { + public DecimalMemLiteral(Object creator, BigDecimal value, CoreDatatype datatype) { this(creator, value.toPlainString(), value, datatype); } - public DecimalMemLiteral(Object creator, String label, BigDecimal value, IRI datatype) { - super(creator, label, datatype); - this.value = value; - } - public DecimalMemLiteral(Object creator, String label, BigDecimal value, CoreDatatype datatype) { super(creator, label, datatype); this.value = value; diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemLiteral.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemLiteral.java index b21fa3b82a6..c45353d8a35 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemLiteral.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemLiteral.java @@ -13,7 +13,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.impl.SimpleLiteral; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * A MemoryStore-specific extension of Literal giving it node properties. @@ -49,7 +48,7 @@ public class MemLiteral extends SimpleLiteral implements MemValue { * @param label The label for this literal. */ public MemLiteral(Object creator, String label) { - super(label, XSD.STRING); + super(label, CoreDatatype.XSD.STRING); this.creator = creator; } diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatement.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatement.java index ed6ead85f14..8b148944cd5 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatement.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatement.java @@ -101,22 +101,6 @@ public boolean isInSnapshot(int snapshot) { return snapshot >= sinceSnapshot && snapshot < ((int) TILL_SNAPSHOT.getAcquire(this)); } - @Deprecated(since = "4.0.0", forRemoval = true) - public void setExplicit(boolean explicit) { - logger.warn( - "The explicit field has been set to final for improved performance. Java reflection will be used " + - "to modify it. Take note that the MemorySailStore will not detect this change and may " + - "assume that it doesn't have any inferred statements!"); - - try { - Field explicitField = MemStatement.class.getDeclaredField("explicit"); - explicitField.setAccessible(true); - explicitField.set(this, explicit); - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException(e); - } - } - public boolean isExplicit() { return explicit; } diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatementIterator.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatementIterator.java index 18ddceb6904..044ec2c10c4 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatementIterator.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatementIterator.java @@ -14,14 +14,13 @@ import java.util.NoSuchElementException; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; /** * A StatementIterator that can iterate over a list of Statement objects. This iterator compares Resource and Literal * objects using the '==' operator, which is possible thanks to the extensive sharing of these objects in the * MemoryStore. */ -public class MemStatementIterator implements CloseableIteration { +public class MemStatementIterator implements CloseableIteration { public static final int MIN_SIZE_TO_CONSIDER_FOR_CACHE = 1000; /*-----------* @@ -127,7 +126,7 @@ public MemStatementIterator(MemStatementList statementList, MemResource subject, this.statementIndex = 0; } - public static CloseableIteration cacheAwareInstance(MemStatementList smallestList, + public static CloseableIteration cacheAwareInstance(MemStatementList smallestList, MemResource subj, MemIRI pred, MemValue obj, Boolean explicit, int snapshot, MemResource[] memContexts, MemStatementIteratorCache iteratorCache) throws InterruptedException { diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatementIteratorCache.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatementIteratorCache.java index e8d751f23c8..52376e81726 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatementIteratorCache.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemStatementIteratorCache.java @@ -105,7 +105,7 @@ CachedIteration getCachedIterator(MemStatementIterator iterator) { return new CachedIteration(cached.iterator()); } - private static class CachedIteration implements CloseableIteration { + private static class CachedIteration implements CloseableIteration { private Iterator iter; diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemTripleIterator.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemTripleIterator.java index f4793fbe65d..76b3dbbaf08 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemTripleIterator.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemTripleIterator.java @@ -18,7 +18,7 @@ * * @author Jeen Broekstra */ -public class MemTripleIterator extends LookAheadIteration { +public class MemTripleIterator extends LookAheadIteration { /*-----------* * Variables * diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemValueFactory.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemValueFactory.java index e2a12b6577a..c9a482f7750 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemValueFactory.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/MemValueFactory.java @@ -202,45 +202,6 @@ private boolean isOwnMemIRI(IRI value) { return value instanceof MemIRI && ((MemIRI) value).getCreator() == this; } - /** - * Gets all URIs that are managed by this value factory. - *

- * Warning: This method is not synchronized. - * - * @return An unmodifiable Set of MemURI objects. - * @deprecated Use getMemIRIsIterator() instead. - */ - @Deprecated(forRemoval = true, since = "4.0.0") - public Set getMemURIs() { - return Collections.unmodifiableSet(iriRegistry); - } - - /** - * Gets all bnodes that are managed by this value factory. - *

- * Warning: This method is not synchronized. - * - * @return An unmodifiable Set of MemBNode objects. - * @deprecated Use getMemBNodesIterator() instead. - */ - @Deprecated(forRemoval = true, since = "4.0.0") - public Set getMemBNodes() { - return Collections.unmodifiableSet(bnodeRegistry); - } - - /** - * Gets all literals that are managed by this value factory. - *

- * Warning: This method is not synchronized. - * - * @return An unmodifiable Set of MemURI objects. - * @deprecated Use getMemLiteralsIterator() instead. - */ - @Deprecated(forRemoval = true, since = "4.0.0") - public Set getMemLiterals() { - return Collections.unmodifiableSet(literalRegistry); - } - /** * Gets all URIs that are managed by this value factory. * diff --git a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/NumericMemLiteral.java b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/NumericMemLiteral.java index 86c49bedb76..1b42d36aaa0 100644 --- a/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/NumericMemLiteral.java +++ b/core/sail/memory/src/main/java/org/eclipse/rdf4j/sail/memory/model/NumericMemLiteral.java @@ -13,7 +13,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.datatypes.XMLDatatypeUtil; -import org.eclipse.rdf4j.model.vocabulary.XSD; /** * An extension of MemLiteral that stores a numeric value to avoid parsing. @@ -35,42 +34,37 @@ public class NumericMemLiteral extends MemLiteral { * Constructors * *--------------*/ - public NumericMemLiteral(Object creator, String label, Number number, IRI datatype) { - super(creator, label, datatype); - this.number = number; - } - public NumericMemLiteral(Object creator, String label, Number number, CoreDatatype datatype) { super(creator, label, datatype); this.number = number; } - public NumericMemLiteral(Object creator, Number number, IRI datatype) { + public NumericMemLiteral(Object creator, Number number, CoreDatatype datatype) { this(creator, XMLDatatypeUtil.toString(number), number, datatype); } public NumericMemLiteral(Object creator, byte number) { - this(creator, number, XSD.BYTE); + this(creator, number, CoreDatatype.XSD.BYTE); } public NumericMemLiteral(Object creator, short number) { - this(creator, number, XSD.SHORT); + this(creator, number, CoreDatatype.XSD.SHORT); } public NumericMemLiteral(Object creator, int number) { - this(creator, number, XSD.INT); + this(creator, number, CoreDatatype.XSD.INT); } public NumericMemLiteral(Object creator, long n) { - this(creator, n, XSD.LONG); + this(creator, n, CoreDatatype.XSD.LONG); } public NumericMemLiteral(Object creator, float n) { - this(creator, n, XSD.FLOAT); + this(creator, n, CoreDatatype.XSD.FLOAT); } public NumericMemLiteral(Object creator, double n) { - this(creator, n, XSD.DOUBLE); + this(creator, n, CoreDatatype.XSD.DOUBLE); } /*---------* diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/InferredMemStatementTest.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/InferredMemStatementTest.java deleted file mode 100644 index d64744c5d22..00000000000 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/InferredMemStatementTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.sail.memory; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Optional; -import java.util.stream.Stream; - -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.eclipse.rdf4j.sail.memory.model.MemStatement; -import org.junit.Test; - -/** - * This test class should be removed when we remove - * {@link org.eclipse.rdf4j.sail.memory.model.MemStatement#setExplicit(boolean)} - */ -@Deprecated(since = "4.0.0", forRemoval = true) -public class InferredMemStatementTest { - - @Test - public void testChangingInferredStatement() { - MemoryStore memoryStore = new MemoryStore(); - - // add our explicit statement - try (MemoryStoreConnection connection = (MemoryStoreConnection) memoryStore.getConnection()) { - connection.begin(); - connection.addStatement(RDF.TYPE, RDF.TYPE, RDF.TYPE); - connection.commit(); - } - - // make the statement inferred - try (MemoryStoreConnection connection = (MemoryStoreConnection) memoryStore.getConnection()) { - connection.begin(); - try (Stream stream = connection.getStatements(RDF.TYPE, RDF.TYPE, RDF.TYPE, true) - .stream()) { - MemStatement statement = stream - .map(s -> (MemStatement) s) - .findAny() - .get(); - - assertThat(statement.isExplicit()).isTrue(); - statement.setExplicit(false); - assertThat(statement.isExplicit()).isFalse(); - - connection.commit(); - } - - } - - // we need to add an inferred statement so that the MemorySailStore doesn't assume that the inferred branch is - // empty - try (MemoryStoreConnection connection = (MemoryStoreConnection) memoryStore.getConnection()) { - connection.begin(); - connection.addInferredStatement(RDF.SUBJECT, RDF.PREDICATE, RDF.OBJECT); - connection.commit(); - } - - // check the statement is still set as inferred - try (MemoryStoreConnection connection = (MemoryStoreConnection) memoryStore.getConnection()) { - connection.begin(); - - Optional statement = connection.getStatements(RDF.TYPE, RDF.TYPE, RDF.TYPE, true) - .stream() - .map(s -> (MemStatement) s) - .findAny(); - - assertThat(statement).isPresent(); - assertThat(statement.get().isExplicit()).isFalse(); - - connection.commit(); - } - - } - -} diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemTripleSourceTest.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemTripleSourceTest.java index 84127a21a23..df49b0c5df2 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemTripleSourceTest.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemTripleSourceTest.java @@ -68,10 +68,9 @@ public class MemTripleSourceTest { private SailSource source; /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { store = new MemoryStore(); store.init(); f = store.getValueFactory(); @@ -82,10 +81,9 @@ public void setUp() throws Exception { } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { if (snapshot != null) { snapshot.close(); } @@ -105,7 +103,7 @@ public final void testGetStatementsNoContextsAllNull() throws Exception { loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, null, null)) { List list = Iterations.asList(statements); @@ -123,7 +121,7 @@ public final void testGetStatementsOneContextAllNull() throws Exception { loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, null, null)) { List list = Iterations.asList(statements); @@ -141,7 +139,7 @@ public final void testGetStatementsTwoContextsAllNull() throws Exception { loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, null, null)) { List list = Iterations.asList(statements); @@ -159,7 +157,7 @@ public final void testGetStatementsNoContextsOnePredicate() throws Exception { loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null)) { List list = Iterations.asList(statements); @@ -177,7 +175,7 @@ public final void testGetStatementsOneContextOnePredicate() throws Exception { loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null)) { List list = Iterations.asList(statements); @@ -195,7 +193,7 @@ public final void testGetStatementsTwoContextsOnePredicate() throws Exception { loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null)) { List list = Iterations.asList(statements); @@ -213,7 +211,7 @@ public final void testGetStatementsNoContextsOnePredicateOneContext() throws Exc loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null, this.alice)) { List list = Iterations.asList(statements); @@ -231,7 +229,7 @@ public final void testGetStatementsOneContextOnePredicateOneContext() throws Exc loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null, this.alice)) { List list = Iterations.asList(statements); @@ -249,7 +247,7 @@ public final void testGetStatementsTwoContextsOnePredicateOneContext() throws Ex loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null, this.alice)) { List list = Iterations.asList(statements); @@ -267,7 +265,7 @@ public final void testGetStatementsNoContextsOnePredicateTwoContexts() throws Ex loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -285,7 +283,7 @@ public final void testGetStatementsOneContextOnePredicateTwoContexts() throws Ex loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -303,7 +301,7 @@ public final void testGetStatementsTwoContextsOnePredicateTwoContexts() throws E loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, null, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -321,7 +319,7 @@ public final void testGetStatementsNoContextsPredicateOwlThingTwoContexts() thro loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, OWL.THING, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -339,7 +337,7 @@ public final void testGetStatementsOneContextPredicateOwlThingTwoContexts() thro loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, OWL.THING, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -357,7 +355,7 @@ public final void testGetStatementsTwoContextsPredicateOwlThingTwoContexts() thr loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, OWL.THING, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -375,7 +373,7 @@ public final void testGetStatementsNoContextsPredicateOwlClassTwoContexts() thro loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDF.TYPE, OWL.CLASS, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -393,7 +391,7 @@ public final void testGetStatementsOneContextPredicateOwlClassTwoContexts() thro loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDF.TYPE, OWL.CLASS, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -411,7 +409,7 @@ public final void testGetStatementsTwoContextsPredicateOwlClassTwoContexts() thr loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDF.TYPE, OWL.CLASS, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -429,7 +427,7 @@ public final void testGetStatementsNoContextsPredicateOwlClassNoContexts() throw loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDF.TYPE, OWL.CLASS)) { List list = Iterations.asList(statements); @@ -447,7 +445,7 @@ public final void testGetStatementsOneContextPredicateOwlClassNoContexts() throw loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDF.TYPE, OWL.CLASS)) { List list = Iterations.asList(statements); @@ -465,7 +463,7 @@ public final void testGetStatementsTwoContextsPredicateOwlClassNoContexts() thro loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDF.TYPE, OWL.CLASS)) { List list = Iterations.asList(statements); @@ -483,7 +481,7 @@ public final void testGetStatementsNoContextsPredicateExClassNoContexts() throws loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"))) { List list = Iterations.asList(statements); @@ -501,7 +499,7 @@ public final void testGetStatementsOneContextPredicateExClassNoContexts() throws loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"))) { List list = Iterations.asList(statements); @@ -519,7 +517,7 @@ public final void testGetStatementsTwoContextsPredicateExClassNoContexts() throw loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"))) { List list = Iterations.asList(statements); @@ -537,7 +535,7 @@ public final void testGetStatementsNoContextsPredicateExClassOneContext() throws loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"), this.alice)) { List list = Iterations.asList(statements); @@ -555,7 +553,7 @@ public final void testGetStatementsOneContextPredicateExClassOneContext() throws loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"), this.alice)) { List list = Iterations.asList(statements); @@ -573,7 +571,7 @@ public final void testGetStatementsTwoContextsPredicateExClassOneContext() throw loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"), this.alice)) { List list = Iterations.asList(statements); @@ -591,7 +589,7 @@ public final void testGetStatementsNoContextsPredicateExClassTwoContexts() throw loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"), this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -609,7 +607,7 @@ public final void testGetStatementsOneContextPredicateExClassTwoContexts() throw loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"), this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -627,7 +625,7 @@ public final void testGetStatementsTwoContextsPredicateExClassTwoContexts() thro loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, RDFS.SUBCLASSOF, f.createIRI(EX_NS, "A"), this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -645,7 +643,7 @@ public final void testGetStatementsNoContextsExClassPredicateTwoContexts() throw loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source + try (CloseableIteration statements = source .getStatements(f.createIRI(EX_NS, "C"), RDFS.SUBCLASSOF, null, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -663,7 +661,7 @@ public final void testGetStatementsOneContextExClassPredicateTwoContexts() throw loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source + try (CloseableIteration statements = source .getStatements(f.createIRI(EX_NS, "C"), RDFS.SUBCLASSOF, null, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -681,7 +679,7 @@ public final void testGetStatementsTwoContextsExClassPredicateTwoContexts() thro loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source + try (CloseableIteration statements = source .getStatements(f.createIRI(EX_NS, "C"), RDFS.SUBCLASSOF, null, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -699,7 +697,7 @@ public final void testGetStatementsNoContextsExClassPredicateNoContexts() throws loadTestData("/alp-testdata.ttl"); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source + try (CloseableIteration statements = source .getStatements(f.createIRI(EX_NS, "C"), RDFS.SUBCLASSOF, null)) { List list = Iterations.asList(statements); @@ -717,7 +715,7 @@ public final void testGetStatementsOneContextExClassPredicateNoContexts() throws loadTestData("/alp-testdata.ttl", this.alice); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source + try (CloseableIteration statements = source .getStatements(f.createIRI(EX_NS, "C"), RDFS.SUBCLASSOF, null)) { List list = Iterations.asList(statements); @@ -735,7 +733,7 @@ public final void testGetStatementsTwoContextsExClassPredicateNoContexts() throw loadTestData("/alp-testdata.ttl", this.alice, this.bob); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source + try (CloseableIteration statements = source .getStatements(f.createIRI(EX_NS, "C"), RDFS.SUBCLASSOF, null)) { List list = Iterations.asList(statements); @@ -753,7 +751,7 @@ public final void testGetStatementsThreeContextsAllNull() throws Exception { loadTestData("/alp-testdata.ttl", this.alice, this.bob, this.mary); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, null, null)) { List list = Iterations.asList(statements); @@ -771,7 +769,7 @@ public final void testGetStatementsThreeContextsOneContext() throws Exception { loadTestData("/alp-testdata.ttl", this.alice, this.bob, this.mary); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, null, null, this.alice)) { List list = Iterations.asList(statements); @@ -789,7 +787,7 @@ public final void testGetStatementsThreeContextsTwoContexts() throws Exception { loadTestData("/alp-testdata.ttl", this.alice, this.bob, this.mary); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, null, null, this.alice, this.bob)) { List list = Iterations.asList(statements); @@ -807,7 +805,7 @@ public final void testGetStatementsThreeContextsThreeContexts() throws Exception loadTestData("/alp-testdata.ttl", this.alice, this.bob, this.mary); TripleSource source = getTripleSourceCommitted(); - try (CloseableIteration statements = source.getStatements(null, + try (CloseableIteration statements = source.getStatements(null, null, null, this.alice, this.bob, this.mary)) { List list = Iterations.asList(statements); @@ -847,14 +845,14 @@ private TripleSource getTripleSourceCommitted() throws SailException { return new TripleSource() { @Override - public CloseableIteration getStatements(Resource subj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { try { return new ExceptionConvertingIteration( snapshot.getStatements(subj, pred, obj, contexts)) { @Override - protected QueryEvaluationException convert(Exception e) { + protected QueryEvaluationException convert(RuntimeException e) { return new QueryEvaluationException(e); } }; diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySparqlAggregatesTest.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySparqlAggregatesTest.java index a025bc1fb87..e243c30974a 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySparqlAggregatesTest.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySparqlAggregatesTest.java @@ -19,12 +19,12 @@ public class MemorySparqlAggregatesTest extends SparqlAggregatesTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemoryStoreTest.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemoryStoreTest.java index d540cbadeb1..bde0277d663 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemoryStoreTest.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/MemoryStoreTest.java @@ -18,7 +18,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.impl.EmptyBindingSet; import org.eclipse.rdf4j.query.parser.ParsedTupleQuery; @@ -46,17 +45,16 @@ protected NotifyingSail createSail() throws SailException { /** * reproduces GH-3053 * - * @throws Exception */ @Test - public void testZeroOrOnePropPathNonExisting() throws Exception { + public void testZeroOrOnePropPathNonExisting() { ParsedTupleQuery tupleQuery = (ParsedTupleQuery) QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, "SELECT ?resource WHERE {\n" + " (^()*) / ? ?resource\n" + "}", "http://example.org/"); - CloseableIteration res = con.evaluate(tupleQuery.getTupleExpr(), + CloseableIteration res = con.evaluate(tupleQuery.getTupleExpr(), null, EmptyBindingSet.getInstance(), false); assertTrue(res.hasNext(), "expect a result"); int count = 0; diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/SnapshotMonitorTest.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/SnapshotMonitorTest.java index 947912def06..822319765c5 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/SnapshotMonitorTest.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/SnapshotMonitorTest.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.transaction.IsolationLevels; import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.base.SailDataset; import org.eclipse.rdf4j.sail.base.SailSink; import org.eclipse.rdf4j.sail.base.SailSource; @@ -225,7 +224,7 @@ public void testOverlappingReservations() { private void getAndAbandonDataset(SailSource explicitSailSource, MemorySailStore.SnapshotMonitor snapshotMonitor) { SailDataset dataset = explicitSailSource.dataset(IsolationLevels.SNAPSHOT); - CloseableIteration contextIDs = dataset.getContextIDs(); + CloseableIteration contextIDs = dataset.getContextIDs(); contextIDs.close(); Assertions.assertNotEquals(100, snapshotMonitor.getFirstUnusedOrElse(100)); } diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/StoreSerializationTest.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/StoreSerializationTest.java index 713d5c0df9a..dcda42b74bf 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/StoreSerializationTest.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/StoreSerializationTest.java @@ -24,14 +24,12 @@ import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.query.impl.EmptyBindingSet; import org.eclipse.rdf4j.query.parser.ParsedTupleQuery; import org.eclipse.rdf4j.query.parser.QueryParserUtil; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -73,7 +71,7 @@ public void testShortLiterals() { con = store.getConnection(); - CloseableIteration iter = con.getStatements(foo, RDF.VALUE, null, false); + CloseableIteration iter = con.getStatements(foo, RDF.VALUE, null, false); assertTrue(iter.hasNext()); iter.next(); iter.close(); @@ -101,7 +99,7 @@ public void testSerialization() { null); TupleExpr tupleExpr = query.getTupleExpr(); - CloseableIteration iter = con.evaluate(tupleExpr, null, + CloseableIteration iter = con.evaluate(tupleExpr, null, EmptyBindingSet.getInstance(), false); BindingSet bindingSet = iter.next(); @@ -163,7 +161,7 @@ public void testLongLiterals() { con = store.getConnection(); - CloseableIteration iter = con.getStatements(foo, RDF.VALUE, null, false); + CloseableIteration iter = con.getStatements(foo, RDF.VALUE, null, false); assertTrue(iter.hasNext()); iter.next(); iter.close(); diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/LoadingBenchmark.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/LoadingBenchmark.java index 6f878f5a1b5..6f3b919790c 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/LoadingBenchmark.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/LoadingBenchmark.java @@ -34,7 +34,6 @@ import org.eclipse.rdf4j.rio.Rio; import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStore; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; @@ -273,7 +272,7 @@ public long loadSyntheticWithDuplicatesAndNewStatementsGetFirst() { long counter = 0; for (int i = 0; i < 10; i++) { - try (CloseableIteration statements = connection.getStatements(null, + try (CloseableIteration statements = connection.getStatements(null, null, null, false)) { counter += statements.next().toString().length(); } @@ -299,7 +298,7 @@ public long loadSyntheticSingleTransactionGetFirstStatement() { long count = 0; for (int i = 0; i < 10; i++) { - try (CloseableIteration statements = connection.getStatements(null, + try (CloseableIteration statements = connection.getStatements(null, null, null, false)) { count += statements.next().toString().length(); } diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/OOMBenchmark.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/OOMBenchmark.java index 26e905c8478..93a98a522b9 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/OOMBenchmark.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/OOMBenchmark.java @@ -91,7 +91,7 @@ public static void main(String[] args) throws RunnerException { } @Setup(Level.Trial) - public void setup() throws IOException, InterruptedException { + public void setup() throws IOException { repository = new SailRepository(new MemoryStore()); diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/QueryBenchmark.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/QueryBenchmark.java index ffe308f391d..82d90ab8eb8 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/QueryBenchmark.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/QueryBenchmark.java @@ -34,7 +34,6 @@ import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.runner.RunnerException; /** * @author Håvard Ottestad @@ -99,7 +98,7 @@ public class QueryBenchmark { } } - public static void main(String[] args) throws RunnerException, IOException, InterruptedException { + public static void main(String[] args) throws IOException { // Options opt = new OptionsBuilder() // .include("QueryBenchmark") // adapt to run other benchmark tests // // .addProfiler("stack", "lines=20;period=1;top=20") @@ -126,7 +125,7 @@ public static void main(String[] args) throws RunnerException, IOException, Inte } @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() throws IOException { repository = new SailRepository(new MemoryStore()); try (SailRepositoryConnection connection = repository.getConnection()) { diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/QueryWriteBenchmark.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/QueryWriteBenchmark.java index 53909f5a726..629603d64b9 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/QueryWriteBenchmark.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/QueryWriteBenchmark.java @@ -94,7 +94,7 @@ public static void main(String[] args) throws RunnerException { } @Setup(Level.Invocation) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() { repository = new SailRepository(new MemoryStore()); try (SailRepositoryConnection connection = repository.getConnection()) { diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/SortBenchmark.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/SortBenchmark.java index 8b932a0418a..f26f5b7b8eb 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/SortBenchmark.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/SortBenchmark.java @@ -76,7 +76,7 @@ public class SortBenchmark { List valuesList; - public static void main(String[] args) throws RunnerException, IOException, InterruptedException { + public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include("SortBenchmark.*") // adapt to run other benchmark tests .forks(1) @@ -86,7 +86,7 @@ public static void main(String[] args) throws RunnerException, IOException, Inte } @Setup(Level.Trial) - public void setup() throws IOException, InterruptedException { + public void setup() throws IOException { repository = new SailRepository(new MemoryStore()); diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/SparqlOverheadBenchmark.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/SparqlOverheadBenchmark.java index ec160e7a56d..30b057baa6a 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/SparqlOverheadBenchmark.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/benchmark/SparqlOverheadBenchmark.java @@ -80,7 +80,7 @@ public static void main(String[] args) throws RunnerException { } @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() throws IOException { repository = new SailRepository(new MemoryStore()); diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/model/MemTripleTest.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/model/MemTripleTest.java index c403a8abb1c..714f570005b 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/model/MemTripleTest.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/model/MemTripleTest.java @@ -32,7 +32,7 @@ public class MemTripleTest { private IRI s1, p1, o1; @BeforeEach - public void setUp() throws Exception { + public void setUp() { SimpleValueFactory svf = SimpleValueFactory.getInstance(); diff --git a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/model/MemURITest.java b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/model/MemURITest.java index 4d834140f0e..3add2796aef 100644 --- a/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/model/MemURITest.java +++ b/core/sail/memory/src/test/java/org/eclipse/rdf4j/sail/memory/model/MemURITest.java @@ -27,7 +27,7 @@ public class MemURITest { * Verifies that MemURI's hash code is the same as the hash code of an equivalent URIImpl. */ @Test - public void testEqualsAndHash() throws Exception { + public void testEqualsAndHash() { compareURIs(RDF.NAMESPACE); compareURIs(RDF.TYPE.toString()); compareURIs("foo:bar"); @@ -35,7 +35,7 @@ public void testEqualsAndHash() throws Exception { compareURIs("http://www.example.org/foo#bar"); } - private void compareURIs(String uri) throws Exception { + private void compareURIs(String uri) { IRI uriImpl = SimpleValueFactory.getInstance().createIRI(uri); MemIRI memURI = new MemIRI(this, uriImpl.getNamespace(), uriImpl.getLocalName()); diff --git a/core/sail/model/pom.xml b/core/sail/model/pom.xml index 75029a92156..1b6705b9a54 100644 --- a/core/sail/model/pom.xml +++ b/core/sail/model/pom.xml @@ -37,12 +37,4 @@ test - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - - diff --git a/core/sail/model/src/main/java/org/eclipse/rdf4j/sail/model/NonSerializables.java b/core/sail/model/src/main/java/org/eclipse/rdf4j/sail/model/NonSerializables.java deleted file mode 100644 index 648cc75a902..00000000000 --- a/core/sail/model/src/main/java/org/eclipse/rdf4j/sail/model/NonSerializables.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.sail.model; - -import java.util.Map; -import java.util.UUID; - -import org.eclipse.rdf4j.common.annotation.InternalUseOnly; -import org.eclipse.rdf4j.util.UUIDable; - -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; - -/** - * A registry to support (de)serialization of objects (over the lifetime of the VM). It uses weak references to allow - * entries to be garbage-collected when no longer used. - * - * @author Mark - * @apiNote this feature is for internal use only: its existence, signature or behavior may change without warning from - * one release to the next. - */ -@InternalUseOnly -public class NonSerializables { - - private static final Cache registry = CacheBuilder.newBuilder().weakValues().build(); - - /** - * Retrieve the object registered with the supplied key. - * - * @param key the key. - * @return the registered object, or null if no matching EvaluationStrategy can be found. - */ - public static Object get(UUID key) { - return registry.getIfPresent(key); - } - - /** - * Retrieves the registry key for the given object. - * - * @param obj the object for which to retrieve the registry key. - * @return the registry key with which the supplied object can be retrieved, or null if the supplied - * object is not in the registry. - */ - public static UUID getKey(Object obj) { - Map map = registry.asMap(); - - // we could make this lookup more efficient with a WeakHashMap-based - // reverse index, but we currently prefer this slower but more robust - // approach (less chance of accidental lingering references that prevent - // GC) - for (UUID key : map.keySet()) { - // we use identity comparison in line with how guava caches behave - // when softValues are used. - if (obj == map.get(key)) { - return key; - } - } - return null; - } - - /** - * Add an object to the registry and returns the registry key. If the object is already present, the operation - * simply returns the key with which it is currently registered. - * - * @param obj the object to register - * @return the key with which the object is registered. - */ - public static UUID register(Object obj) { - UUID key; - if (obj instanceof UUIDable) { - key = ((UUIDable) obj).getUUID(); - if (get(key) == null) { - registry.put(key, obj); - } - } else { - key = getKey(obj); - if (key == null) { - key = UUID.randomUUID(); - registry.put(key, obj); - } - } - return key; - } - - /** - * Prevent instantiation: util class - */ - private NonSerializables() { - } -} diff --git a/core/sail/model/src/main/java/org/eclipse/rdf4j/sail/model/SailModel.java b/core/sail/model/src/main/java/org/eclipse/rdf4j/sail/model/SailModel.java index 300968308c2..79f2d37a882 100644 --- a/core/sail/model/src/main/java/org/eclipse/rdf4j/sail/model/SailModel.java +++ b/core/sail/model/src/main/java/org/eclipse/rdf4j/sail/model/SailModel.java @@ -70,7 +70,7 @@ public void setConnection(SailConnection conn) { public Set getNamespaces() { Set namespaces; try { - try (CloseableIteration iter = conn.getNamespaces()) { + try (CloseableIteration iter = conn.getNamespaces()) { namespaces = Iterations.asSet(conn.getNamespaces()); } } catch (SailException e) { @@ -211,7 +211,7 @@ public Iterator iterator() { private Iterator iterator(Resource subj, IRI pred, Value obj, Resource... contexts) { try { - CloseableIteration iter = conn.getStatements(subj, pred, obj, includeInferred, + CloseableIteration iter = conn.getStatements(subj, pred, obj, includeInferred, contexts); return new CloseableIterationIterator<>( new ExceptionConvertingIteration(iter) { @@ -234,7 +234,7 @@ public void remove() { } @Override - protected ModelException convert(Exception e) { + protected ModelException convert(RuntimeException e) { throw new ModelException(e); } }); @@ -280,13 +280,4 @@ public int size() { return (lsize < Integer.MAX_VALUE) ? (int) lsize : Integer.MAX_VALUE; } - private void writeObject(ObjectOutputStream out) throws IOException { - this.connKey = NonSerializables.register(this.conn); - out.defaultWriteObject(); - } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - this.conn = SailConnection.class.cast(NonSerializables.get(this.connKey)); - } } diff --git a/core/sail/nativerdf/pom.xml b/core/sail/nativerdf/pom.xml index aa6eb61d177..36b15963277 100644 --- a/core/sail/nativerdf/pom.xml +++ b/core/sail/nativerdf/pom.xml @@ -102,10 +102,6 @@ maven-assembly-plugin - - com.github.siom79.japicmp - japicmp-maven-plugin - diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/AbstractRecordCache.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/AbstractRecordCache.java index 15b079eefe5..fed6dee5a5d 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/AbstractRecordCache.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/AbstractRecordCache.java @@ -118,10 +118,9 @@ public final void clear() throws IOException { * longer {@link #isValid() valid}. * * @return An iterator over all records. - * @throws IllegalStateException If the cache is not/no longer {@link #isValid() valid}. */ @Override - public final RecordIterator getRecords() throws IOException { + public final RecordIterator getRecords() { if (isValid()) { return getRecordsInternal(); } @@ -129,7 +128,7 @@ public final RecordIterator getRecords() throws IOException { throw new IllegalStateException(); } - protected abstract RecordIterator getRecordsInternal() throws IOException; + protected abstract RecordIterator getRecordsInternal(); /** * Checks whether the cache is still valid. Caches are valid if the number of stored records is smaller than or diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/ContextStore.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/ContextStore.java index 34678cd5bf9..e7de3a15a7b 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/ContextStore.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/ContextStore.java @@ -32,7 +32,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.sail.SailException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -178,7 +177,7 @@ private void writeContextsToFile() throws IOException { private void initializeContextCache() throws IOException { logger.debug("initializing context cache"); - try (CloseableIteration contextIter = store.getContexts()) { + try (CloseableIteration contextIter = store.getContexts()) { while (contextIter.hasNext()) { increment(contextIter.next()); } diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/InMemRecordCache.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/InMemRecordCache.java index eaa84ba18bc..33f9d9084d7 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/InMemRecordCache.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/InMemRecordCache.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.nativerdf; -import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -35,29 +34,29 @@ public long getRecordCount() { } @Override - public void storeRecord(byte[] data) throws IOException { + public void storeRecord(byte[] data) { records.add(data); } @Override - public void storeRecords(RecordCache otherCache) throws IOException { + public void storeRecords(RecordCache otherCache) { throw new UnsupportedOperationException(); } @Override - public void clear() throws IOException { + public void clear() { records = new ArrayList<>(1); } @Override - public RecordIterator getRecords() throws IOException { + public RecordIterator getRecords() { return new RecordIterator() { private int index = 0; @Override - public byte[] next() throws IOException { + public byte[] next() { if (index < records.size()) { return records.get(index++); } @@ -65,12 +64,12 @@ public byte[] next() throws IOException { } @Override - public void set(byte[] record) throws IOException { + public void set(byte[] record) { records.set(index - 1, record); } @Override - public void close() throws IOException { + public void close() { } }; @@ -82,7 +81,7 @@ public boolean isValid() { } @Override - public void discard() throws IOException { + public void discard() { } } diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStore.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStore.java deleted file mode 100644 index 2942fb60b26..00000000000 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStore.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.sail.nativerdf; - -import java.io.File; -import java.io.IOException; - -import org.eclipse.rdf4j.sail.NotifyingSailConnection; -import org.eclipse.rdf4j.sail.SailException; - -/** - * @author Jerven Bolleman, SIB Swiss Institute of Bioinformatics - * - * @deprecated since 4.2.4. See https://github.com/eclipse/rdf4j/issues/3983 - */ -@Deprecated(since = "4.2.4", forRemoval = true) -public class LimitedSizeNativeStore extends NativeStore { - - /** - * @param dataDir - * @param string - */ - public LimitedSizeNativeStore(File dataDir, String string) { - super(dataDir, string); - } - - public LimitedSizeNativeStore() { - super(); - } - - public LimitedSizeNativeStore(File dataDir) { - super(dataDir); - } - - @Override - protected NotifyingSailConnection getConnectionInternal() throws SailException { - try { - return new LimitedSizeNativeStoreConnection(this); - } catch (IOException e) { - throw new SailException(e); - } - } -} diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStoreConnection.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStoreConnection.java deleted file mode 100644 index 6655cfeb791..00000000000 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStoreConnection.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.sail.nativerdf; - -import java.io.IOException; - -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; -import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource; -import org.eclipse.rdf4j.query.algebra.evaluation.limited.LimitedSizeEvaluationStrategy; - -/** - * @author Jerven Bolleman, SIB Swiss Institute of Bioinformatics - * - * @deprecated since 4.2.4. See https://github.com/eclipse/rdf4j/issues/3983 - */ -@Deprecated(since = "4.2.4", forRemoval = true) -public class LimitedSizeNativeStoreConnection extends NativeStoreConnection { - - private int maxCollectionsSize = Integer.MAX_VALUE; - - /** - * @param nativeStore - * @throws IOException - */ - protected LimitedSizeNativeStoreConnection(NativeStore nativeStore) throws IOException { - super(nativeStore); - } - - public int getMaxCollectionsSize() { - return maxCollectionsSize; - } - - public void setMaxCollectionsSize(int maxCollectionsSize) { - this.maxCollectionsSize = maxCollectionsSize; - } - - @Override - protected EvaluationStrategy getEvaluationStrategy(Dataset dataset, TripleSource tripleSource) { - return new LimitedSizeEvaluationStrategy(tripleSource, dataset, maxCollectionsSize, - getFederatedServiceResolver()); - } -} diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/NativeSailStore.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/NativeSailStore.java index 696f702c38d..77b9fada2db 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/NativeSailStore.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/NativeSailStore.java @@ -180,9 +180,9 @@ List getContextIDs(Resource... contexts) throws IOException { return contextIDs; } - CloseableIteration getContexts() throws IOException { + CloseableIteration getContexts() throws IOException { RecordIterator btreeIter = tripleStore.getAllTriplesSortedByContext(false); - CloseableIteration stIter1; + CloseableIteration stIter1; if (btreeIter == null) { // Iterator over all statements stIter1 = createStatementIterator(null, null, null, true); @@ -190,7 +190,7 @@ CloseableIteration getContexts() throws IOException { stIter1 = new NativeStatementIterator(btreeIter, valueStore); } - FilterIteration stIter2 = new FilterIteration( + FilterIteration stIter2 = new FilterIteration( stIter1) { @Override protected boolean accept(Statement st) { @@ -198,7 +198,7 @@ protected boolean accept(Statement st) { } }; - return new ConvertingIteration(stIter2) { + return new ConvertingIteration(stIter2) { @Override protected Resource convert(Statement sourceObject) throws SailException { return sourceObject.getContext(); @@ -216,7 +216,7 @@ protected Resource convert(Statement sourceObject) throws SailException { * no contexts are supplied the method operates on the entire repository. * @return A StatementIterator that can be used to iterate over the statements that match the specified pattern. */ - CloseableIteration createStatementIterator(Resource subj, IRI pred, Value obj, + CloseableIteration createStatementIterator(Resource subj, IRI pred, Value obj, boolean explicit, Resource... contexts) throws IOException { int subjID = NativeValue.UNKNOWN_ID; if (subj != null) { @@ -606,17 +606,17 @@ public String getNamespace(String prefix) throws SailException { } @Override - public CloseableIteration getNamespaces() { - return new CloseableIteratorIteration(namespaceStore.iterator()); + public CloseableIteration getNamespaces() { + return new CloseableIteratorIteration(namespaceStore.iterator()); } @Override - public CloseableIteration getContextIDs() throws SailException { + public CloseableIteration getContextIDs() throws SailException { return new CloseableIteratorIteration<>(contextStore.iterator()); } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws SailException { try { return createStatementIterator(subj, pred, obj, explicit, contexts); diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/NativeStatementIterator.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/NativeStatementIterator.java index c5400a09ed3..f3f0e3eb204 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/NativeStatementIterator.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/NativeStatementIterator.java @@ -25,7 +25,7 @@ * A statement iterator that wraps a RecordIterator containing statement records and translates these records to * {@link Statement} objects. */ -class NativeStatementIterator extends LookAheadIteration { +class NativeStatementIterator extends LookAheadIteration { /*-----------* * Variables * @@ -42,7 +42,7 @@ class NativeStatementIterator extends LookAheadIteration { - final CloseableIteration stmts; + final CloseableIteration stmts; Statement last; - StatementIterator(CloseableIteration closeableIteration) { + StatementIterator(CloseableIteration closeableIteration) { this.stmts = closeableIteration; } @@ -151,7 +151,7 @@ public String toString() { public synchronized int size() { if (size < 0) { try { - CloseableIteration iter; + CloseableIteration iter; iter = dataset().getStatements(null, null, null); try { while (iter.hasNext()) { @@ -176,7 +176,7 @@ public synchronized int size() { public Set getNamespaces() { Set set = new LinkedHashSet<>(); try { - CloseableIteration spaces; + CloseableIteration spaces; spaces = dataset().getNamespaces(); try { while (spaces.hasNext()) { @@ -284,7 +284,7 @@ public synchronized boolean remove(Resource subj, IRI pred, Value obj, Resource. try { if (contains(subj, pred, obj, contexts)) { size = -1; - CloseableIteration stmts; + CloseableIteration stmts; stmts = dataset().getStatements(subj, pred, obj, contexts); try { while (stmts.hasNext()) { @@ -322,7 +322,7 @@ public Model filter(final Resource subj, final IRI pred, final Value obj, final public int size() { if (subj == null && pred == null && obj == null) { try { - CloseableIteration iter; + CloseableIteration iter; iter = dataset().getStatements(null, null, null); try { long size = 0; @@ -364,7 +364,7 @@ protected void removeFilteredTermIteration(Iterator iter, Resource su public synchronized void removeTermIteration(Iterator iter, Resource subj, IRI pred, Value obj, Resource... contexts) { try { - CloseableIteration stmts; + CloseableIteration stmts; stmts = dataset().getStatements(subj, pred, obj, contexts); try { while (stmts.hasNext()) { @@ -411,7 +411,7 @@ private boolean contains(SailDataset dataset, Resource subj, IRI pred, Value obj if (dataset == null) { return false; } - CloseableIteration stmts; + CloseableIteration stmts; stmts = dataset.getStatements(subj, pred, obj, contexts); try { return stmts.hasNext(); diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/SequentialRecordCache.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/SequentialRecordCache.java index b00d7a68559..232f4fc78c3 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/SequentialRecordCache.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/SequentialRecordCache.java @@ -119,7 +119,7 @@ protected void storeRecordInternal(byte[] data) throws IOException { } @Override - protected RecordIterator getRecordsInternal() throws IOException { + protected RecordIterator getRecordsInternal() { return new RecordCacheIterator(); } @@ -196,7 +196,7 @@ public void set(byte[] value) throws IOException { } @Override - public void close() throws IOException { + public void close() { } } } diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/TripleStore.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/TripleStore.java index 544ff9f2baa..96ec387ff2e 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/TripleStore.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/TripleStore.java @@ -445,13 +445,12 @@ public void close() throws IOException { } } - public RecordIterator getTriples(int subj, int pred, int obj, int context) throws IOException { + public RecordIterator getTriples(int subj, int pred, int obj, int context) { // Return all triples except those that were added but not yet committed return getTriples(subj, pred, obj, context, 0, ADDED_FLAG); } - public RecordIterator getTriples(int subj, int pred, int obj, int context, boolean readTransaction) - throws IOException { + public RecordIterator getTriples(int subj, int pred, int obj, int context, boolean readTransaction) { if (readTransaction) { // Don't read removed statements return getTriples(subj, pred, obj, context, 0, TripleStore.REMOVED_FLAG); @@ -466,9 +465,8 @@ public RecordIterator getTriples(int subj, int pred, int obj, int context, boole * * @param readTransaction * @return All triples sorted by context or null if no context index exists - * @throws IOException */ - public RecordIterator getAllTriplesSortedByContext(boolean readTransaction) throws IOException { + public RecordIterator getAllTriplesSortedByContext(boolean readTransaction) { if (readTransaction) { // Don't read removed statements return getAllTriplesSortedByContext(0, TripleStore.REMOVED_FLAG); @@ -479,7 +477,7 @@ public RecordIterator getAllTriplesSortedByContext(boolean readTransaction) thro } public RecordIterator getTriples(int subj, int pred, int obj, int context, boolean explicit, - boolean readTransaction) throws IOException { + boolean readTransaction) { int flags = 0; int flagsMask = 0; @@ -586,14 +584,13 @@ public void close() throws IOException { } } // end inner class ImplicitStatementFilter - private RecordIterator getTriples(int subj, int pred, int obj, int context, int flags, int flagsMask) - throws IOException { + private RecordIterator getTriples(int subj, int pred, int obj, int context, int flags, int flagsMask) { TripleIndex index = getBestIndex(subj, pred, obj, context); boolean doRangeSearch = index.getPatternScore(subj, pred, obj, context) > 0; return getTriplesUsingIndex(subj, pred, obj, context, flags, flagsMask, index, doRangeSearch); } - private RecordIterator getAllTriplesSortedByContext(int flags, int flagsMask) throws IOException { + private RecordIterator getAllTriplesSortedByContext(int flags, int flagsMask) { for (TripleIndex index : indexes) { if (index.getFieldSeq()[0] == 'c') { // found a context-first index diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/ValueStore.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/ValueStore.java index b981a4eee90..9dd0f4c2f8f 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/ValueStore.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/ValueStore.java @@ -26,6 +26,7 @@ import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.util.Literals; import org.eclipse.rdf4j.model.vocabulary.RDF; @@ -458,7 +459,7 @@ private byte[] uri2data(IRI uri, boolean create) throws IOException { return uriData; } - private byte[] bnode2data(BNode bNode, boolean create) throws IOException { + private byte[] bnode2data(BNode bNode, boolean create) { byte[] idData = bNode.getID().getBytes(StandardCharsets.UTF_8); byte[] bNodeData = new byte[1 + idData.length]; @@ -546,7 +547,7 @@ private NativeIRI data2uri(int id, byte[] data) throws IOException { return new NativeIRI(revision, namespace, localName, id); } - private NativeBNode data2bnode(int id, byte[] data) throws IOException { + private NativeBNode data2bnode(int id, byte[] data) { String nodeID = new String(data, 1, data.length - 1, StandardCharsets.UTF_8); return new NativeBNode(revision, nodeID, id); } @@ -574,11 +575,11 @@ private NativeLiteral data2literal(int id, byte[] data) throws IOException { } else if (datatype != null) { return new NativeLiteral(revision, label, datatype, id); } else { - return new NativeLiteral(revision, label, XSD.STRING, id); + return new NativeLiteral(revision, label, CoreDatatype.XSD.STRING, id); } } - private String data2namespace(byte[] data) throws UnsupportedEncodingException { + private String data2namespace(byte[] data) { return new String(data, StandardCharsets.UTF_8); } @@ -639,7 +640,7 @@ public NativeBNode createBNode(String nodeID) { @Override public NativeLiteral createLiteral(String value) { - return new NativeLiteral(revision, value, XSD.STRING); + return new NativeLiteral(revision, value, CoreDatatype.XSD.STRING); } @Override diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/BTree.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/BTree.java index 9400f255d5a..078f0f8601d 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/BTree.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/BTree.java @@ -1011,14 +1011,14 @@ private Node createNewNode() throws IOException { return node; } - Node readRootNode() throws IOException { + Node readRootNode() { if (rootNodeID > 0) { return readNode(rootNodeID); } return null; } - Node readNode(int id) throws IOException { + Node readNode(int id) { if (id <= 0) { throw new IllegalArgumentException("id must be larger than 0, is: " + id + " in " + getFile()); } diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/ConcurrentNodeCache.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/ConcurrentNodeCache.java index 1005d74fae4..e758bbb888a 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/ConcurrentNodeCache.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/ConcurrentNodeCache.java @@ -41,7 +41,7 @@ public void flush() { cache.forEachValue(Long.MAX_VALUE, writeNode); } - public void put(Node node) throws IOException { + public void put(Node node) { cache.put(node.getID(), node); } diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/Node.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/Node.java index 36d78bd1ade..d6898e8a90b 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/Node.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/Node.java @@ -227,7 +227,7 @@ public void setChildNodeID(int nodeIdx, int nodeID) { dataChanged = true; } - public Node getChildNode(int nodeIdx) throws IOException { + public Node getChildNode(int nodeIdx) { assert nodeIdx >= 0 : "nodeIdx must be positive, is: " + nodeIdx; assert nodeIdx <= valueCount : "nodeIdx out of range (" + nodeIdx + " > " + valueCount + ")"; diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/RangeIterator.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/RangeIterator.java index d0f623d8bf1..d7f1617b292 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/RangeIterator.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/btree/RangeIterator.java @@ -89,7 +89,7 @@ public byte[] next() throws IOException { } } - private void findMinimum() throws IOException { + private void findMinimum() { Node nextCurrentNode = currentNode = tree.readRootNode(); if (nextCurrentNode == null) { diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/config/NativeStoreConfig.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/config/NativeStoreConfig.java index d55a02dc2d8..bbfd3ce3d58 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/config/NativeStoreConfig.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/config/NativeStoreConfig.java @@ -31,9 +31,6 @@ */ public class NativeStoreConfig extends BaseSailConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - private String tripleIndexes; private boolean forceSync = false; private int valueCacheSize = -1; @@ -109,50 +106,56 @@ public void setNamespaceIDCacheSize(int namespaceIDCacheSize) { @Override public Resource export(Model m) { + if (Configurations.useLegacyConfig()) { + return exportLegacy(m); + } + Resource implNode = super.export(m); m.setNamespace(CONFIG.NS); if (tripleIndexes != null) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Native.tripleIndexes, literal(tripleIndexes)); - } else { - m.add(implNode, TRIPLE_INDEXES, literal(tripleIndexes)); - } + m.add(implNode, CONFIG.Native.tripleIndexes, literal(tripleIndexes)); + } + if (forceSync) { + m.add(implNode, CONFIG.Native.forceSync, literal(forceSync)); + } + if (valueCacheSize >= 0) { + m.add(implNode, CONFIG.Native.valueCacheSize, literal(valueCacheSize)); + } + if (valueIDCacheSize >= 0) { + m.add(implNode, CONFIG.Native.valueIDCacheSize, literal(valueIDCacheSize)); + } + if (namespaceCacheSize >= 0) { + m.add(implNode, CONFIG.Native.namespaceCacheSize, literal(namespaceCacheSize)); + } + if (namespaceIDCacheSize >= 0) { + m.add(implNode, CONFIG.Native.namespaceIDCacheSize, literal(namespaceIDCacheSize)); + } + + return implNode; + } + + private Resource exportLegacy(Model m) { + Resource implNode = super.export(m); + m.setNamespace("ns", NativeStoreSchema.NAMESPACE); + + if (tripleIndexes != null) { + m.add(implNode, TRIPLE_INDEXES, literal(tripleIndexes)); } if (forceSync) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Native.forceSync, literal(forceSync)); - } else { - m.add(implNode, FORCE_SYNC, literal(forceSync)); - } + m.add(implNode, FORCE_SYNC, literal(forceSync)); } if (valueCacheSize >= 0) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Native.valueCacheSize, literal(valueCacheSize)); - } else { - m.add(implNode, VALUE_CACHE_SIZE, literal(valueCacheSize)); - } + m.add(implNode, VALUE_CACHE_SIZE, literal(valueCacheSize)); } if (valueIDCacheSize >= 0) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Native.valueIDCacheSize, literal(valueIDCacheSize)); - } else { - m.add(implNode, VALUE_ID_CACHE_SIZE, literal(valueIDCacheSize)); - } + m.add(implNode, VALUE_ID_CACHE_SIZE, literal(valueIDCacheSize)); } if (namespaceCacheSize >= 0) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Native.namespaceCacheSize, literal(namespaceCacheSize)); - } else { - m.add(implNode, NAMESPACE_CACHE_SIZE, literal(namespaceCacheSize)); - } + m.add(implNode, NAMESPACE_CACHE_SIZE, literal(namespaceCacheSize)); } if (namespaceIDCacheSize >= 0) { - if (USE_CONFIG) { - m.add(implNode, CONFIG.Native.namespaceIDCacheSize, literal(namespaceIDCacheSize)); - } else { - m.add(implNode, NAMESPACE_ID_CACHE_SIZE, literal(namespaceIDCacheSize)); - } + m.add(implNode, NAMESPACE_ID_CACHE_SIZE, literal(namespaceIDCacheSize)); } return implNode; diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/DataFile.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/DataFile.java index 06972ce6fa0..d369c1649cf 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/DataFile.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/DataFile.java @@ -286,7 +286,7 @@ public class DataIterator { private long position = HEADER_LENGTH; - public boolean hasNext() throws IOException { + public boolean hasNext() { return position < nioFileSize; } diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/DataStore.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/DataStore.java index e52ace6faa0..981c2230cf0 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/DataStore.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/DataStore.java @@ -109,9 +109,8 @@ public int getID(byte[] queryData) throws IOException { * Returns the maximum value-ID that is in use. * * @return The largest ID, or 0 if the store does not contain any values. - * @throws IOException If an I/O error occurs. */ - public int getMaxID() throws IOException { + public int getMaxID() { return idFile.getMaxID(); } diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/HashFile.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/HashFile.java index df6d34e4661..594caa5872b 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/HashFile.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/HashFile.java @@ -507,7 +507,7 @@ public void close() { } @Override - public int next() throws IOException { + public int next() { return -1; } }; diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/IDFile.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/IDFile.java index 2df0b04ff77..2c7814e25bd 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/IDFile.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/datastore/IDFile.java @@ -137,9 +137,8 @@ public final File getFile() { * Gets the largest ID that is stored in this ID file. * * @return The largest ID, or 0 if the file does not contain any data. - * @throws IOException If an I/O error occurs. */ - public int getMaxID() throws IOException { + public int getMaxID() { return (int) (nioFileSize / ITEM_SIZE) - 1; } diff --git a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/model/NativeLiteral.java b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/model/NativeLiteral.java index 841fc989fc5..876aebe001f 100644 --- a/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/model/NativeLiteral.java +++ b/core/sail/nativerdf/src/main/java/org/eclipse/rdf4j/sail/nativerdf/model/NativeLiteral.java @@ -11,6 +11,7 @@ package org.eclipse.rdf4j.sail.nativerdf.model; import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.impl.SimpleLiteral; import org.eclipse.rdf4j.sail.nativerdf.ValueStoreRevision; @@ -61,11 +62,20 @@ public NativeLiteral(ValueStoreRevision revision, String label, IRI datatype) { this(revision, label, datatype, UNKNOWN_ID); } + public NativeLiteral(ValueStoreRevision revision, String label, CoreDatatype datatype) { + this(revision, label, datatype, UNKNOWN_ID); + } + public NativeLiteral(ValueStoreRevision revision, String label, IRI datatype, int internalID) { super(label, datatype); setInternalID(internalID, revision); } + public NativeLiteral(ValueStoreRevision revision, String label, CoreDatatype datatype, int internalID) { + super(label, datatype); + setInternalID(internalID, revision); + } + /*---------* * Methods * *---------*/ diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/ContextStoreTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/ContextStoreTest.java index 291558d0195..3decf6afa2a 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/ContextStoreTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/ContextStoreTest.java @@ -55,26 +55,26 @@ public void setUp() throws Exception { } @Test - public void testIncrementNew() throws Exception { + public void testIncrementNew() { subject.increment(g1); assertThat(countContexts(subject)).isEqualTo(1); } @Test - public void testIncrementNewBNode() throws Exception { + public void testIncrementNewBNode() { subject.increment(g2); assertThat(countContexts(subject)).isEqualTo(1); } @Test - public void testIncrementExisting() throws Exception { + public void testIncrementExisting() { subject.increment(g1); subject.increment(g1); assertThat(countContexts(subject)).isEqualTo(1); } @Test - public void testDecrementExisting() throws Exception { + public void testDecrementExisting() { subject.increment(g1); subject.increment(g1); @@ -86,7 +86,7 @@ public void testDecrementExisting() throws Exception { } @Test - public void testDecrementExistingBySeveral() throws Exception { + public void testDecrementExistingBySeveral() { subject.increment(g1); subject.increment(g1); @@ -95,7 +95,7 @@ public void testDecrementExistingBySeveral() throws Exception { } @Test - public void testDecrementExistingBNode() throws Exception { + public void testDecrementExistingBNode() { subject.increment(g2); subject.increment(g2); @@ -107,7 +107,7 @@ public void testDecrementExistingBNode() throws Exception { } @Test - public void testDecrementNonExisting() throws Exception { + public void testDecrementNonExisting() { subject.decrementBy(g1, 1); assertThat(countContexts(subject)).isEqualTo(0); } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStoreConnectionTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStoreConnectionTest.java deleted file mode 100644 index 8edeb54c7b1..00000000000 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/LimitedSizeNativeStoreConnectionTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.sail.nativerdf; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.IOException; - -import org.eclipse.rdf4j.common.iteration.Iterations; -import org.eclipse.rdf4j.common.transaction.IsolationLevel; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.QueryLanguage; -import org.eclipse.rdf4j.query.TupleQuery; -import org.eclipse.rdf4j.query.TupleQueryResult; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.sail.SailRepository; -import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection; -import org.eclipse.rdf4j.testsuite.repository.RepositoryConnectionTest; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -public class LimitedSizeNativeStoreConnectionTest extends RepositoryConnectionTest { - @Override - protected Repository createRepository(File dataDir) throws IOException { - return new SailRepository(new LimitedSizeNativeStore(dataDir, "spoc")); - } - - @ParameterizedTest - @MethodSource("parameters") - public void testSES715(IsolationLevel level) throws Exception { - setupTest(level); - - // load 1000 triples in two different contexts - testCon.begin(); - ValueFactory vf = testCon.getValueFactory(); - IRI context1 = vf.createIRI("http://my.context.1"); - IRI context2 = vf.createIRI("http://my.context.2"); - IRI context3 = vf.createIRI("http://my.context.3"); - IRI predicate = vf.createIRI("http://my.predicate"); - IRI object = vf.createIRI("http://my.object"); - - for (int j = 0; j < 1000; j++) { - testCon.add(vf.createIRI("http://my.subject" + j), predicate, object, context1); - testCon.add(vf.createIRI("http://my.subject" + j), predicate, object, context2); - testCon.add(vf.createIRI("http://my.subject" + j), predicate, object, context3); - } - assertEquals(1000, Iterations.asList(testCon.getStatements(null, null, null, false, context1)).size()); - assertEquals(1000, Iterations.asList(testCon.getStatements(null, null, null, false, context2)).size()); - - // remove all triples from context 1 - testCon.clear(context1); - assertEquals(0, Iterations.asList(testCon.getStatements(null, null, null, false, context1)).size()); - assertEquals(1000, Iterations.asList(testCon.getStatements(null, null, null, false, context2)).size()); - assertEquals(2000, - Iterations.asList(testCon.getStatements(null, null, null, false, context2, context3)).size()); - testCon.commit(); - - // check context content using fresh connection - assertEquals(0, Iterations.asList(testCon2.getStatements(null, null, null, false, context1)).size()); - assertEquals(1000, Iterations.asList(testCon2.getStatements(null, null, null, false, context2)).size()); - - testCon2.close(); - } - - @ParameterizedTest - @MethodSource("parameters") - public void testLimit(IsolationLevel level) throws Exception { - setupTest(level); - - ((LimitedSizeNativeStoreConnection) ((SailRepositoryConnection) testCon).getSailConnection()) - .setMaxCollectionsSize(2); - testCon.begin(); - ValueFactory vf = testCon.getValueFactory(); - IRI context1 = vf.createIRI("http://my.context.1"); - IRI predicate = vf.createIRI("http://my.predicate"); - IRI object = vf.createIRI("http://my.object"); - - for (int j = 0; j < 100; j++) { - testCon.add(vf.createIRI("http://my.subject" + j), predicate, object, context1); - } - testCon.commit(); - String queryString = "SELECT DISTINCT ?s WHERE {?s ?p ?o}"; - TupleQuery q = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryString); - QueryEvaluationException shouldThrow = runQuery(q); - assertNotNull(shouldThrow); - - // There is just one object therefore we should not throw a new - // exception - queryString = "SELECT DISTINCT ?o WHERE {?s ?p ?o}"; - q = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryString); - shouldThrow = runQuery(q); - assertNull(shouldThrow); - } - - protected QueryEvaluationException runQuery(TupleQuery q) { - QueryEvaluationException shouldThrow = null; - try (TupleQueryResult r = q.evaluate()) { - assertTrue(r.hasNext()); - while (r.hasNext()) { - assertNotNull(r.next()); - } - } catch (QueryEvaluationException e) { - shouldThrow = e; - } - return shouldThrow; - } -} diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeCascadeValueExceptionTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeCascadeValueExceptionTest.java index 5fc6a9c81e2..afbe6a1df0c 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeCascadeValueExceptionTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeCascadeValueExceptionTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.nativerdf; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -23,7 +22,7 @@ public class NativeCascadeValueExceptionTest extends CascadeValueExceptionTest { File tmpDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new NativeStore(tmpDir, "spoc")); } } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeGraphQueryResultTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeGraphQueryResultTest.java index 1a078df4cd6..46b4e2e6f02 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeGraphQueryResultTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeGraphQueryResultTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.nativerdf; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -23,7 +22,7 @@ public class NativeGraphQueryResultTest extends GraphQueryResultTest { File dataDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new NativeStore(dataDir, "spoc")); } } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSailStoreTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSailStoreTest.java index 22dcf945e1b..e712b8ba199 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSailStoreTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSailStoreTest.java @@ -53,7 +53,7 @@ public class NativeSailStoreTest { F.createLiteral("two")); @BeforeEach - public void before() throws Exception { + public void before() { File dataDir = new File(tempFolder, "dbmodel"); dataDir.mkdir(); repo = new SailRepository(new NativeStore(dataDir, "spoc,posc")); @@ -127,7 +127,7 @@ public void testClearMultipleValidContext() { } @AfterEach - public void after() throws Exception { + public void after() { repo.shutDown(); } } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSparqlOrderByTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSparqlOrderByTest.java index eb18f09a38e..4897fb226be 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSparqlOrderByTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSparqlOrderByTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.nativerdf; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -24,7 +23,7 @@ public class NativeSparqlOrderByTest extends SparqlOrderByTest { File dataDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new NativeStore(dataDir, "spoc")); } } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSparqlRegexTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSparqlRegexTest.java index cb826bf911b..3f197ca58e0 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSparqlRegexTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSparqlRegexTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.nativerdf; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -23,7 +22,7 @@ public class NativeSparqlRegexTest extends SparqlRegexTest { File dataDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new NativeStore(dataDir, "spoc")); } } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreConnectionTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreConnectionTest.java index 2bbb8a5f93c..98bb8ebd657 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreConnectionTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreConnectionTest.java @@ -13,7 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.common.transaction.IsolationLevel; @@ -27,13 +26,13 @@ public class NativeStoreConnectionTest extends RepositoryConnectionTest { @Override - protected Repository createRepository(File dataDir) throws IOException { + protected Repository createRepository(File dataDir) { return new SailRepository(new NativeStore(dataDir, "spoc")); } @ParameterizedTest @MethodSource("parameters") - public void testSES715(IsolationLevel level) throws Exception { + public void testSES715(IsolationLevel level) { setupTest(level); // load 1000 triples in two different contexts diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreDirLockTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreDirLockTest.java index 3249b0bf374..581e0da0aff 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreDirLockTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreDirLockTest.java @@ -25,7 +25,7 @@ public class NativeStoreDirLockTest { File dataDir; @Test - public void testLocking() throws Exception { + public void testLocking() { NativeStore sail = new NativeStore(dataDir, "spoc,posc"); sail.init(); diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreRepositoryTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreRepositoryTest.java index 5abf12b8918..1587ab73d94 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreRepositoryTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreRepositoryTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.nativerdf; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -23,7 +22,7 @@ public class NativeStoreRepositoryTest extends RepositoryTest { public File dataDir; @Override - protected Repository createRepository() throws IOException { + protected Repository createRepository() { return new SailRepository(new NativeStore(dataDir, "spoc")); } } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreTest.java index b38abd5408b..3e1440ac355 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreTest.java @@ -50,7 +50,7 @@ protected NotifyingSail createSail() throws SailException { // Test for SES-542 @Test - public void testGetNamespacePersistence() throws Exception { + public void testGetNamespacePersistence() { con.begin(); con.setNamespace("rdf", RDF.NAMESPACE); con.commit(); @@ -65,7 +65,7 @@ public void testGetNamespacePersistence() throws Exception { } @Test - public void testContextCacheReconstruction() throws Exception { + public void testContextCacheReconstruction() { con.begin(); con.addStatement(RDF.TYPE, RDF.TYPE, RDF.TYPE, RDF.ALT); con.commit(); diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreTxnTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreTxnTest.java index 10e40d64827..83af7b715c0 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreTxnTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeStoreTxnTest.java @@ -50,7 +50,7 @@ public class NativeStoreTxnTest { protected IRI ctx = vf.createIRI("http://ex.org/ctx"); @BeforeEach - public void before() throws Exception { + public void before() { File dataDir = new File(tempFolder, "dbmodel"); repo = new SailRepository(new NativeStore(dataDir, "spoc,posc")); @@ -58,7 +58,7 @@ public void before() throws Exception { } @AfterEach - public void after() throws Exception { + public void after() { repo.shutDown(); } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeTupleQueryResultTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeTupleQueryResultTest.java index 4eb7b6da01e..a763a0283a5 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeTupleQueryResultTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeTupleQueryResultTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.nativerdf; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -24,7 +23,7 @@ public class NativeTupleQueryResultTest extends TupleQueryResultTest { File tempDir; @Override - protected Repository newRepository() throws IOException { + protected Repository newRepository() { return new SailRepository(new NativeStore(tempDir, "spoc")); } } diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/QueryBenchmarkTest.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/QueryBenchmarkTest.java index f64ef3210d6..4ffb282d728 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/QueryBenchmarkTest.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/QueryBenchmarkTest.java @@ -83,7 +83,7 @@ private static InputStream getResourceAsStream(String name) { } @AfterAll - public static void afterClass() throws IOException { + public static void afterClass() { repository.shutDown(); repository = null; statementList = null; diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/TestNativeStoreMemoryOverflow.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/TestNativeStoreMemoryOverflow.java index 1c7321f5452..f1b3ab22b35 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/TestNativeStoreMemoryOverflow.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/TestNativeStoreMemoryOverflow.java @@ -13,7 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; -import java.io.IOException; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.Iterations; @@ -42,7 +41,7 @@ public class TestNativeStoreMemoryOverflow { private RepositoryConnection testCon2; @BeforeEach - public void setUp(@TempDir File dataDir) throws Exception { + public void setUp(@TempDir File dataDir) { testRepository = createRepository(dataDir); } @@ -56,12 +55,12 @@ private void setupConnections(IsolationLevel level) { testCon2.setIsolationLevel(level); } - private Repository createRepository(File dataDir) throws IOException { + private Repository createRepository(File dataDir) { return new SailRepository(new NativeStore(dataDir, "spoc")); } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { testCon2.close(); testCon.close(); testRepository.shutDown(); @@ -69,7 +68,7 @@ public void tearDown() throws Exception { @ParameterizedTest @EnumSource(IsolationLevels.class) - public void test(IsolationLevel level) throws Exception { + public void test(IsolationLevel level) { setupConnections(level); int size = 10000; // this should really be bigger @@ -94,7 +93,7 @@ public void test(IsolationLevel level) throws Exception { testCon.close(); } - private static final class DynamicIteration implements CloseableIteration { + private static final class DynamicIteration implements CloseableIteration { private final int size; diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/TestNativeStoreUpgrade.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/TestNativeStoreUpgrade.java index 5295005c9e3..fcfdb4b2857 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/TestNativeStoreUpgrade.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/TestNativeStoreUpgrade.java @@ -92,7 +92,7 @@ public void assertValue(File dataDir) throws SailException { store.init(); try (NotifyingSailConnection con = store.getConnection()) { ValueFactory vf = store.getValueFactory(); - CloseableIteration iter; + CloseableIteration iter; iter = con.getStatements(RDF.VALUE, RDFS.LABEL, vf.createLiteral("value"), false); try { assertTrue(iter.hasNext()); diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/benchmark/QueryBenchmark.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/benchmark/QueryBenchmark.java index ab1a4dcf29b..26534592871 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/benchmark/QueryBenchmark.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/benchmark/QueryBenchmark.java @@ -117,7 +117,7 @@ public static void main(String[] args) throws RunnerException { } @Setup(Level.Trial) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() throws IOException { file = Files.newTemporaryFolder(); repository = new SailRepository(new NativeStore(file, "spoc,ospc,psoc")); diff --git a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/benchmark/QueryWriteBenchmark.java b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/benchmark/QueryWriteBenchmark.java index 580bf578264..5ab3ec3ae41 100644 --- a/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/benchmark/QueryWriteBenchmark.java +++ b/core/sail/nativerdf/src/test/java/org/eclipse/rdf4j/sail/nativerdf/benchmark/QueryWriteBenchmark.java @@ -94,7 +94,7 @@ public static void main(String[] args) throws RunnerException { } @Setup(Level.Invocation) - public void beforeClass() throws IOException, InterruptedException { + public void beforeClass() { file = Files.newTemporaryFolder(); repository = new SailRepository(new NativeStore(file, "spoc,ospc,psoc")); diff --git a/core/sail/shacl/pom.xml b/core/sail/shacl/pom.xml index b234ccfb88b..d26ee58e5bf 100644 --- a/core/sail/shacl/pom.xml +++ b/core/sail/shacl/pom.xml @@ -85,6 +85,12 @@ junit-jupiter-params test + + ${project.groupId} + rdf4j-sail-lmdb + ${project.version} + test + diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ConnectionHelper.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ConnectionHelper.java index d7a025f35f2..ea5ebdca14a 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ConnectionHelper.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ConnectionHelper.java @@ -22,7 +22,7 @@ class ConnectionHelper { - static CloseableIteration getCloseableIteration( + static CloseableIteration getCloseableIteration( RepositoryResult repositoryResults) { return new CloseableIteration<>() { @@ -52,7 +52,7 @@ public void close() throws SailException { static void transferStatements(SailConnection from, TransferStatement transfer) { - try (CloseableIteration statements = from + try (CloseableIteration statements = from .getStatements(null, null, null, false)) { while (statements.hasNext()) { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ShaclSailConnection.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ShaclSailConnection.java index 779bdd7472e..3a5ad68d11c 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ShaclSailConnection.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ShaclSailConnection.java @@ -1060,7 +1060,7 @@ public RdfsSubClassOfReasoner getRdfsSubClassOfReasoner() { } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { if (useDefaultShapesGraph && contexts.length == 1 && RDF4J.SHACL_SHAPE_GRAPH.equals(contexts[0])) { return ConnectionHelper @@ -1106,97 +1106,6 @@ private long getTimeStamp() { return 0; } - @Deprecated(forRemoval = true) - public class ValidationContainer { - private final Shape shape; - private final PlanNode planNode; - private final ValidationExecutionLogger validationExecutionLogger; - - public ValidationContainer(Shape shape, PlanNode planNode) { - this.shape = shape; - this.validationExecutionLogger = ValidationExecutionLogger - .getInstance(sail.isGlobalLogValidationExecution()); - if (!(planNode.isGuaranteedEmpty())) { - assert planNode instanceof SingleCloseablePlanNode; - planNode.receiveLogger(validationExecutionLogger); - this.planNode = planNode; - } else { - this.planNode = planNode; - } - } - - public Shape getShape() { - return shape; - } - - public boolean hasPlanNode() { - return !(planNode.isGuaranteedEmpty()); - } - - public ValidationResultIterator performValidation() { - long before = getTimeStamp(); - - handlePreLogging(); - - ValidationResultIterator validationResults = null; - - try (CloseableIteration iterator = planNode.iterator()) { - validationResults = new ValidationResultIterator(iterator, - sail.getEffectiveValidationResultsLimitPerConstraint()); - return validationResults; - } catch (Exception e) { - throw new SailException("Error validating SHACL Shape " + shape.getId() + "\n" + shape, e); - } finally { - handlePostLogging(before, validationResults); - } - } - - private void handlePreLogging() { - if (validationExecutionLogger.isEnabled()) { - logger.info("Start execution of plan:\n{}\n", getShape().toString()); - } - } - - private void handlePostLogging(long before, ValidationResultIterator validationResults) { - if (validationExecutionLogger.isEnabled()) { - validationExecutionLogger.flush(); - } - - if (validationResults != null) { - - if (sail.isPerformanceLogging()) { - long after = System.currentTimeMillis(); - logger.info("Execution of plan took {} ms for:\n{}\n", - (after - before), - getShape().toString()); - } - - if (validationExecutionLogger.isEnabled()) { - logger.info("Finished execution of plan:\n{}\n", - getShape().toString()); - } - - if (sail.isLogValidationViolations()) { - if (!validationResults.conforms()) { - List tuples = validationResults.getTuples(); - - logger.info( - "SHACL not valid. The following experimental debug results were produced:\n\t\t{}\n\n{}\n", - tuples.stream() - .map(ValidationTuple::toString) - .collect(Collectors.joining("\n\t\t")), - getShape().toString() - - ); - } - } - - } - - } - - } - public static class Settings { private ValidationApproach validationApproach; @@ -1205,10 +1114,6 @@ public static class Settings { private IsolationLevel isolationLevel; transient private Settings previous = null; - @Deprecated(since = "4.0.0", forRemoval = true) - public Settings() { - } - public Settings(boolean cacheSelectNodes, boolean validationEnabled, boolean parallelValidation, IsolationLevel isolationLevel) { this.cacheSelectedNodes = cacheSelectNodes; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ShapeValidationContainer.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ShapeValidationContainer.java index ada79d21538..b97ec129ba1 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ShapeValidationContainer.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ShapeValidationContainer.java @@ -73,7 +73,7 @@ public ValidationResultIterator performValidation() { ValidationResultIterator validationResults = null; - try (CloseableIteration iterator = planNode.iterator()) { + try (CloseableIteration iterator = planNode.iterator()) { validationResults = new ValidationResultIterator(iterator, effectiveValidationResultsLimitPerConstraint); return validationResults; } catch (Exception e) { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/paths/SimplePath.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/paths/SimplePath.java index f3e07c7dd9d..f797453e873 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/paths/SimplePath.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/paths/SimplePath.java @@ -22,7 +22,6 @@ import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.query.QueryResults; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.shacl.ast.SparqlFragment; import org.eclipse.rdf4j.sail.shacl.ast.StatementMatcher; import org.eclipse.rdf4j.sail.shacl.ast.planNodes.PlanNode; @@ -92,7 +91,7 @@ public SparqlFragment getTargetQueryFragment(StatementMatcher.Variable subject, if (currentStatementMatcher.hasSubject(object)) { List newStatements = currentStatements.stream() .map(currentStatement -> { - try (CloseableIteration statements = connectionsGroup + try (CloseableIteration statements = connectionsGroup .getBaseConnection() .getStatements(null, predicate, currentStatement.getSubject(), true, dataGraph)) { @@ -105,7 +104,7 @@ public SparqlFragment getTargetQueryFragment(StatementMatcher.Variable subject, } else if (currentStatementMatcher.hasObject(object)) { List newStatements = currentStatements.stream() .map(currentStatement -> { - try (CloseableIteration statements = connectionsGroup + try (CloseableIteration statements = connectionsGroup .getBaseConnection() .getStatements(null, predicate, currentStatement.getObject(), true, dataGraph)) { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/AllTargetsPlanNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/AllTargetsPlanNode.java index e78a2610bf3..7aacec352ac 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/AllTargetsPlanNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/AllTargetsPlanNode.java @@ -23,7 +23,6 @@ import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.shacl.ast.SparqlFragment; import org.eclipse.rdf4j.sail.shacl.ast.StatementMatcher; import org.eclipse.rdf4j.sail.shacl.ast.StatementMatcher.Variable; @@ -59,11 +58,11 @@ public AllTargetsPlanNode(SailConnection sailConnection, } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration iterator; + private CloseableIteration iterator; @Override protected void init() { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BindSelect.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BindSelect.java index ffbcb672a36..d77d8223321 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BindSelect.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BindSelect.java @@ -28,13 +28,11 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.MalformedQueryException; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.BindingSetAssignment; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; import org.eclipse.rdf4j.query.impl.EmptyBindingSet; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStoreConnection; import org.eclipse.rdf4j.sail.shacl.ast.SparqlFragment; import org.eclipse.rdf4j.sail.shacl.ast.SparqlQueryParserCache; @@ -125,12 +123,12 @@ public void meet(BindingSetAssignment node) throws Exception { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - CloseableIteration bindingSet; + CloseableIteration bindingSet; - private CloseableIteration iterator; + private CloseableIteration iterator; List bulk; TupleExpr parsedQuery = null; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BufferedPlanNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BufferedPlanNode.java index af25a3c4741..62d50d47d7a 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BufferedPlanNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BufferedPlanNode.java @@ -37,7 +37,7 @@ public class BufferedPlanNode implemen } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new CloseableIteration<>() { { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BufferedSplitter.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BufferedSplitter.java index caca395c0e2..df62ca822f0 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BufferedSplitter.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BufferedSplitter.java @@ -56,7 +56,7 @@ public BufferedSplitter(PlanNode parent) { private synchronized void init() { if (tuplesBuffer == null) { tuplesBuffer = new ArrayList<>(); - try (CloseableIteration iterator = parent.iterator()) { + try (CloseableIteration iterator = parent.iterator()) { while (iterator.hasNext()) { ValidationTuple next = iterator.next(); tuplesBuffer.add(next); @@ -106,7 +106,7 @@ public BufferedSplitterPlaneNode(BufferedSplitter bufferedSplitter, boolean cach } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new CloseableIteration<>() { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BulkedExternalInnerJoin.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BulkedExternalInnerJoin.java index eb0b55ccbf9..08cb52484d3 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BulkedExternalInnerJoin.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BulkedExternalInnerJoin.java @@ -22,7 +22,6 @@ import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStoreConnection; import org.eclipse.rdf4j.sail.shacl.ast.SparqlFragment; import org.eclipse.rdf4j.sail.shacl.ast.StatementMatcher; @@ -88,13 +87,13 @@ public static Function getMapper(String a, String c } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { ArrayDeque left; ArrayDeque right; ArrayDeque joined; - private CloseableIteration leftNodeIterator; + private CloseableIteration leftNodeIterator; @Override protected void init() { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BulkedExternalLeftOuterJoin.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BulkedExternalLeftOuterJoin.java index 0926624ba36..13daa2c8ab0 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BulkedExternalLeftOuterJoin.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/BulkedExternalLeftOuterJoin.java @@ -22,7 +22,6 @@ import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStoreConnection; import org.eclipse.rdf4j.sail.shacl.ast.SparqlFragment; import org.eclipse.rdf4j.sail.shacl.ast.StatementMatcher; @@ -58,13 +57,13 @@ public BulkedExternalLeftOuterJoin(PlanNode leftNode, SailConnection connection, } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { ArrayDeque left; ArrayDeque right; - private CloseableIteration leftNodeIterator; + private CloseableIteration leftNodeIterator; @Override protected void init() { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/DebugPlanNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/DebugPlanNode.java index 2215c9d62cb..b64d75baa97 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/DebugPlanNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/DebugPlanNode.java @@ -47,7 +47,7 @@ public DebugPlanNode(PlanNode parent, Consumer debugPoint) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { if (validationExecutionLogger == null && validationExecutionLogger.isEnabled()) { throw new IllegalStateException("Did not receive validationExecutionLogger before .iterator() was called!"); @@ -55,7 +55,7 @@ public CloseableIteration iterator() { return new CloseableIteration<>() { - final CloseableIteration iterator = parent.iterator(); + final CloseableIteration iterator = parent.iterator(); @Override public boolean hasNext() throws SailException { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EmptyNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EmptyNode.java index 737b0fb2a4d..46053026cf0 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EmptyNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EmptyNode.java @@ -14,7 +14,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.EmptyIteration; -import org.eclipse.rdf4j.sail.SailException; public class EmptyNode implements PlanNode { @@ -30,7 +29,7 @@ public static EmptyNode getInstance() { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new EmptyIteration<>(); } diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EqualsJoin.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EqualsJoin.java index 907ec3b9670..4808927e750 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EqualsJoin.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EqualsJoin.java @@ -14,7 +14,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; public class EqualsJoin implements PlanNode { private final PlanNode left; @@ -31,11 +30,11 @@ public EqualsJoin(PlanNode left, PlanNode right, boolean useAsFilter) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration leftIterator; - private CloseableIteration rightIterator; + private CloseableIteration leftIterator; + private CloseableIteration rightIterator; ValidationTuple next; ValidationTuple nextLeft; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EqualsJoinValue.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EqualsJoinValue.java index d0c8f57de20..3551c681d4b 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EqualsJoinValue.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/EqualsJoinValue.java @@ -14,7 +14,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; public class EqualsJoinValue implements PlanNode { private final PlanNode left; @@ -34,11 +33,11 @@ public EqualsJoinValue(PlanNode left, PlanNode right, boolean useAsFilter) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration leftIterator; - private CloseableIteration rightIterator; + private CloseableIteration leftIterator; + private CloseableIteration rightIterator; ValidationTuple next; ValidationTuple nextLeft; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterByPredicate.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterByPredicate.java index a0ebee999b8..3072316acdf 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterByPredicate.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterByPredicate.java @@ -24,7 +24,6 @@ import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStoreConnection; /** @@ -56,13 +55,13 @@ public FilterByPredicate(SailConnection connection, Set filterOnPredicates, } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { ValidationTuple next = null; - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; List filterOnPredicates = null; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterByPredicateObject.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterByPredicateObject.java index 76fd9f7adac..61efae71219 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterByPredicateObject.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterByPredicateObject.java @@ -22,7 +22,6 @@ import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStoreConnection; /** @@ -58,13 +57,13 @@ public FilterByPredicateObject(SailConnection connection, Resource[] dataGraph, } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { ValidationTuple next = null; - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; Resource[] filterOnObject = null; IRI filterOnPredicate = null; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterPlanNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterPlanNode.java index 67d3832817f..72b8680a99a 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterPlanNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/FilterPlanNode.java @@ -31,7 +31,7 @@ public abstract class FilterPlanNode implements MultiStreamPlanNode, PlanNode { private PushablePlanNode trueNode; private PushablePlanNode falseNode; - private CloseableIteration iterator; + private CloseableIteration iterator; private ValidationExecutionLogger validationExecutionLogger; private boolean closed; @@ -70,16 +70,16 @@ public PlanNode getFalseNode(Class type) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { throw new IllegalStateException("Must specify if filter should return false or true nodes!"); } - private CloseableIteration iteratorInternal() { + private CloseableIteration iteratorInternal() { return new CloseableIteration<>() { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; ValidationTuple next; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/GroupByCountFilter.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/GroupByCountFilter.java index 7ed5a26c9d3..316c8394659 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/GroupByCountFilter.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/GroupByCountFilter.java @@ -16,7 +16,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; /** * @author Håvard Ottestad @@ -34,10 +33,10 @@ public GroupByCountFilter(PlanNode parent, Function filter) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; ValidationTuple next; ValidationTuple tempNext; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/GroupByFilter.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/GroupByFilter.java index ff8a22d682d..3f3f7c523d2 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/GroupByFilter.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/GroupByFilter.java @@ -19,7 +19,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; /** * @author Håvard Ottestad @@ -37,10 +36,10 @@ public GroupByFilter(PlanNode parent, Function, Bool } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; ValidationTuple next; ValidationTuple tempNext; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/InnerJoin.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/InnerJoin.java index ab1eb5ac3f1..46af91faa94 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/InnerJoin.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/InnerJoin.java @@ -36,7 +36,7 @@ public class InnerJoin implements MultiStreamPlanNode, PlanNode { private final PlanNode left; private final PlanNode right; - private CloseableIteration iterator; + private CloseableIteration iterator; private NotifyingPushablePlanNode joined; private NotifyingPushablePlanNode discardedLeft; private NotifyingPushablePlanNode discardedRight; @@ -91,16 +91,16 @@ public PlanNode getDiscardedRight(Class type) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { throw new IllegalStateException(); } - public CloseableIteration internalIterator() { + public CloseableIteration internalIterator() { - return new CloseableIteration() { + return new CloseableIteration() { - final CloseableIteration leftIterator = left.iterator(); - final CloseableIteration rightIterator = right.iterator(); + final CloseableIteration leftIterator = left.iterator(); + final CloseableIteration rightIterator = right.iterator(); ValidationTuple next; ValidationTuple nextLeft; @@ -388,7 +388,7 @@ public NotifyingPushablePlanNode(PushablePlanNode delegate) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return delegate.iterator(); } diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/LeftOuterJoin.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/LeftOuterJoin.java index 0d21a6dba97..b6a4e887f3e 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/LeftOuterJoin.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/LeftOuterJoin.java @@ -15,7 +15,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; /** * @author Håvard Ottestad @@ -34,11 +33,11 @@ public LeftOuterJoin(PlanNode left, PlanNode right) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - CloseableIteration leftIterator; - CloseableIteration rightIterator; + CloseableIteration leftIterator; + CloseableIteration rightIterator; ValidationTuple next; ValidationTuple nextLeft; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/LoggingCloseableIteration.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/LoggingCloseableIteration.java index 93c2b75c10a..d1c272cdbdc 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/LoggingCloseableIteration.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/LoggingCloseableIteration.java @@ -14,7 +14,7 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.sail.SailException; -public abstract class LoggingCloseableIteration implements CloseableIteration { +public abstract class LoggingCloseableIteration implements CloseableIteration { private final ValidationExecutionLogger validationExecutionLogger; private final PlanNode planNode; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NonUniqueTargetLang.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NonUniqueTargetLang.java index a1b4fa9cddc..db07836974d 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NonUniqueTargetLang.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NonUniqueTargetLang.java @@ -20,7 +20,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.SailException; /** * This PlanNode takes a stream of Tuples like: (ex:companyA, "Company A"@en). It assumes that the stream is sorted on @@ -42,7 +41,7 @@ public NonUniqueTargetLang(PlanNode parent) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new OnlyNonUnique(parent, validationExecutionLogger); @@ -117,7 +116,7 @@ class OnlyNonUnique extends LoggingCloseableIteration { private Set seenLanguages = new HashSet<>(); - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; OnlyNonUnique(PlanNode parent, ValidationExecutionLogger validationExecutionLogger) { super(parent, validationExecutionLogger); diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NotValuesIn.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NotValuesIn.java index 860ebffc707..d4cb09cc579 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NotValuesIn.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/NotValuesIn.java @@ -19,7 +19,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.SailException; public class NotValuesIn implements PlanNode { @@ -34,11 +33,11 @@ public NotValuesIn(PlanNode parent, PlanNode notIn) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; Set notInValueSet; ValidationTuple next; @@ -53,7 +52,7 @@ protected void init() { } else { notInValueSet = new HashSet<>(); - try (CloseableIteration iterator = notIn.iterator()) { + try (CloseableIteration iterator = notIn.iterator()) { while (iterator.hasNext()) { notInValueSet.add(iterator.next().getValue()); } diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/PlanNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/PlanNode.java index 173c96bdc39..9af9725b150 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/PlanNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/PlanNode.java @@ -12,14 +12,13 @@ package org.eclipse.rdf4j.sail.shacl.ast.planNodes; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; /** * @author Håvard Mikkelsen Ottestad */ public interface PlanNode { - CloseableIteration iterator(); + CloseableIteration iterator(); int depth(); diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ReduceTargets.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ReduceTargets.java index 9db0b9ff4d0..69e3b9afef6 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ReduceTargets.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ReduceTargets.java @@ -17,7 +17,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.SailException; /** * Takes a parentToReduce and filters away any tuples that have an active target that exists in reductionSource @@ -36,11 +35,11 @@ public ReduceTargets(PlanNode parentToReduce, PlanNode reductionSource) { @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; Set reductionSourceSet; ValidationTuple next; @@ -57,7 +56,7 @@ protected void init() { reductionSourceSet = new HashSet<>(); - try (CloseableIteration iterator = reductionSource + try (CloseableIteration iterator = reductionSource .iterator()) { while (iterator.hasNext()) { reductionSourceSet.add(iterator.next().getActiveTarget()); diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Select.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Select.java index 3d9745c99d3..e51c28a7070 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Select.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Select.java @@ -20,11 +20,9 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.MalformedQueryException; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.query.impl.EmptyBindingSet; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStoreConnection; import org.eclipse.rdf4j.sail.shacl.ast.SparqlFragment; import org.eclipse.rdf4j.sail.shacl.ast.SparqlQueryParserCache; @@ -97,10 +95,10 @@ public Select(SailConnection connection, String query, Function iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - CloseableIteration bindingSet; + CloseableIteration bindingSet; protected void init() { if (bindingSet != null) { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SetFilterNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SetFilterNode.java index 6e2420e0b5c..f5a8f46c975 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SetFilterNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SetFilterNode.java @@ -18,7 +18,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.SailException; public class SetFilterNode implements PlanNode { @@ -37,10 +36,10 @@ public SetFilterNode(Set targetNodeList, PlanNode parent, int index, bool } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; ValidationTuple next; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ShiftToNodeShape.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ShiftToNodeShape.java index 92a36587652..0d0d3fa30b7 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ShiftToNodeShape.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ShiftToNodeShape.java @@ -18,7 +18,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; /** * @author Håvard Ottestad @@ -36,10 +35,10 @@ public ShiftToNodeShape(PlanNode parent) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; Iterator iterator = Collections.emptyIterator(); @Override diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ShiftToPropertyShape.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ShiftToPropertyShape.java index a746699e3e8..fc2105f738c 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ShiftToPropertyShape.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ShiftToPropertyShape.java @@ -18,7 +18,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; /** * @author Håvard Ottestad @@ -36,10 +35,10 @@ public ShiftToPropertyShape(PlanNode parent) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; Iterator iterator = Collections.emptyIterator(); @Override diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SingleCloseablePlanNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SingleCloseablePlanNode.java index 3ecaa66a2c9..285550c060e 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SingleCloseablePlanNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SingleCloseablePlanNode.java @@ -35,7 +35,7 @@ public SingleCloseablePlanNode(PlanNode parent, Shape shape) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { assert receivedLogger; return new SingleCloseableIteration(parent); } @@ -97,9 +97,9 @@ public int hashCode() { return Objects.hash(parent); } - private static class SingleCloseableIteration implements CloseableIteration { + private static class SingleCloseableIteration implements CloseableIteration { - final CloseableIteration parentIterator; + final CloseableIteration parentIterator; final AtomicBoolean closed = new AtomicBoolean(false); public SingleCloseableIteration(PlanNode parent) { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Sort.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Sort.java index ede33264d32..70b98311500 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Sort.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Sort.java @@ -20,7 +20,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; public class Sort implements PlanNode { @@ -33,7 +32,7 @@ public Sort(PlanNode parent) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { @@ -46,7 +45,7 @@ protected void init() { boolean alreadySorted; - try (CloseableIteration iterator = parent.iterator()) { + try (CloseableIteration iterator = parent.iterator()) { sortedTuples = new ArrayList<>(1); alreadySorted = true; ValidationTuple prev = null; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SparqlConstraintSelect.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SparqlConstraintSelect.java index 76f30788104..c57a4729bf2 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SparqlConstraintSelect.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/SparqlConstraintSelect.java @@ -20,13 +20,11 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.MalformedQueryException; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.parser.ParsedQuery; import org.eclipse.rdf4j.query.parser.QueryParserFactory; import org.eclipse.rdf4j.query.parser.QueryParserRegistry; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStoreConnection; import org.eclipse.rdf4j.sail.shacl.ast.Shape; import org.eclipse.rdf4j.sail.shacl.ast.constraintcomponents.ConstraintComponent; @@ -86,12 +84,12 @@ public SparqlConstraintSelect(SailConnection connection, PlanNode targets, Strin } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - CloseableIteration results; + CloseableIteration results; - CloseableIteration targetIterator; + CloseableIteration targetIterator; ValidationTuple next; ValidationTuple nextTarget; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TargetChainPopper.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TargetChainPopper.java index 9d82b6c6cf2..a27e447388c 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TargetChainPopper.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TargetChainPopper.java @@ -18,7 +18,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; /** * Pops the last target off of the target chain and into the value. @@ -41,11 +40,11 @@ public TargetChainPopper(PlanNode parent) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; Iterator iterator = Collections.emptyIterator(); @Override diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TrimToTarget.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TrimToTarget.java index 8b958c2c5bf..ddccd356ff0 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TrimToTarget.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TrimToTarget.java @@ -15,7 +15,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; public class TrimToTarget implements PlanNode { @@ -32,10 +31,10 @@ public TrimToTarget(PlanNode parent) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; @Override protected void init() { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TupleMapper.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TupleMapper.java index 2c16c424502..c407b21431a 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TupleMapper.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/TupleMapper.java @@ -16,7 +16,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; public class TupleMapper implements PlanNode { PlanNode parent; @@ -30,10 +29,10 @@ public TupleMapper(PlanNode parent, Function f } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration parentIterator; + private CloseableIteration parentIterator; @Override protected void init() { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnBufferedPlanNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnBufferedPlanNode.java index 79cd75a8790..ee78958329d 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnBufferedPlanNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnBufferedPlanNode.java @@ -37,7 +37,7 @@ public class UnBufferedPlanNode implem } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { next = null; closed = false; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnionNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnionNode.java index 7c1c6237e03..a130e9c8729 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnionNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnionNode.java @@ -77,12 +77,12 @@ public static PlanNode getInstanceDedupe(PlanNode... nodes) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { if (nodes.length == 1) { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration iterator; + private CloseableIteration iterator; @Override protected void init() { @@ -110,7 +110,7 @@ protected boolean localHasNext() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration[] iterators; + private CloseableIteration[] iterators; final ValidationTuple[] peekList = new ValidationTuple[nodes.length]; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Unique.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Unique.java index 75c916f72c4..5cdeac16758 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Unique.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/Unique.java @@ -65,11 +65,11 @@ public static PlanNode getInstance(PlanNode parent, boolean compress) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - CloseablePeakableIteration parentIterator; + CloseablePeakableIteration parentIterator; Set targetAndValueDedupeSet; boolean propertyShapeWithValue; @@ -290,12 +290,12 @@ public int hashCode() { } } - static class TargetAndValueSortIterator implements CloseableIteration { + static class TargetAndValueSortIterator implements CloseableIteration { - private final CloseablePeakableIteration iterator; + private final CloseablePeakableIteration iterator; public TargetAndValueSortIterator( - CloseablePeakableIteration iterator) { + CloseablePeakableIteration iterator) { this.iterator = iterator; } diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnorderedSelect.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnorderedSelect.java index 4b14e1e2144..bfdb996fcd4 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnorderedSelect.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/UnorderedSelect.java @@ -22,7 +22,6 @@ import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStoreConnection; import org.eclipse.rdf4j.sail.shacl.ast.constraintcomponents.ConstraintComponent; import org.slf4j.Logger; @@ -58,10 +57,10 @@ public UnorderedSelect(SailConnection connection, Resource subject, IRI predicat } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - CloseableIteration statements; + CloseableIteration statements; @Override protected void init() { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ValidationReportNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ValidationReportNode.java index f7f77244cdd..9810d2df145 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ValidationReportNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ValidationReportNode.java @@ -16,7 +16,6 @@ import org.apache.commons.text.StringEscapeUtils; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.shacl.results.ValidationResult; public class ValidationReportNode implements PlanNode { @@ -32,11 +31,11 @@ public ValidationReportNode(PlanNode parent, Function iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { - private CloseableIteration iterator; + private CloseableIteration iterator; @Override protected void init() { diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ValuesBackedNode.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ValuesBackedNode.java index f741cae0752..3a92d9c2a04 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ValuesBackedNode.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/planNodes/ValuesBackedNode.java @@ -21,7 +21,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.shacl.ast.constraintcomponents.ConstraintComponent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,7 +47,7 @@ public ValuesBackedNode(SortedSet values, ConstraintComponent.Scope scope } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { final Iterator iterator = tuples.iterator(); diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/targets/TargetChainRetriever.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/targets/TargetChainRetriever.java index 24bc6e5bfb2..d9f4763019b 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/targets/TargetChainRetriever.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/ast/targets/TargetChainRetriever.java @@ -30,7 +30,6 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.MalformedQueryException; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.algebra.BindingSetAssignment; import org.eclipse.rdf4j.query.algebra.QueryRoot; @@ -43,7 +42,6 @@ import org.eclipse.rdf4j.query.parser.QueryParserFactory; import org.eclipse.rdf4j.query.parser.QueryParserRegistry; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.shacl.ast.SparqlFragment; import org.eclipse.rdf4j.sail.shacl.ast.StatementMatcher; import org.eclipse.rdf4j.sail.shacl.ast.StatementMatcher.Variable; @@ -134,7 +132,7 @@ public TargetChainRetriever(ConnectionsGroup connectionsGroup, } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new LoggingCloseableIteration(this, validationExecutionLogger) { @@ -144,10 +142,10 @@ public CloseableIteration iterator() { private StatementMatcher currentStatementMatcher; private String sparqlValuesDecl; private Set currentVarNames; - private CloseableIteration statements; + private CloseableIteration statements; private ValidationTuple next; - private CloseableIteration results; + private CloseableIteration results; private ParsedQuery parsedQuery; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/config/ShaclSailConfig.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/config/ShaclSailConfig.java index a76737c3f0f..31642f60aa5 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/config/ShaclSailConfig.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/config/ShaclSailConfig.java @@ -12,8 +12,6 @@ import static org.eclipse.rdf4j.model.util.Values.literal; import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.CACHE_SELECT_NODES; -import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.DASH_DATA_SHAPES; -import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.ECLIPSE_RDF4J_SHACL_EXTENSIONS; import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.GLOBAL_LOG_VALIDATION_EXECUTION; import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.LOG_VALIDATION_PLANS; import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.LOG_VALIDATION_VIOLATIONS; @@ -22,10 +20,7 @@ import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.RDFS_SUB_CLASS_REASONING; import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.SERIALIZABLE_VALIDATION; import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.SHAPES_GRAPH; -import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.TRANSACTIONAL_VALIDATION_LIMIT; import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.VALIDATION_ENABLED; -import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.VALIDATION_RESULTS_LIMIT_PER_CONSTRAINT; -import static org.eclipse.rdf4j.sail.shacl.config.ShaclSailSchema.VALIDATION_RESULTS_LIMIT_TOTAL; import java.util.Set; import java.util.stream.Collectors; @@ -50,9 +45,6 @@ */ public class ShaclSailConfig extends AbstractDelegatingSailImplConfig { - private static final boolean USE_CONFIG = "true" - .equalsIgnoreCase(System.getProperty("org.eclipse.rdf4j.model.vocabulary.experimental.enableConfig")); - public static final boolean PARALLEL_VALIDATION_DEFAULT = true; public static final boolean LOG_VALIDATION_PLANS_DEFAULT = false; public static final boolean LOG_VALIDATION_VIOLATIONS_DEFAULT = false; @@ -222,49 +214,26 @@ public Resource export(Model m) { Resource implNode = super.export(m); m.setNamespace(CONFIG.NS); - if (USE_CONFIG) { - m.add(implNode, CONFIG.Shacl.parallelValidation, BooleanLiteral.valueOf(isParallelValidation())); - m.add(implNode, CONFIG.Shacl.logValidationPlans, BooleanLiteral.valueOf(isLogValidationPlans())); - m.add(implNode, CONFIG.Shacl.logValidationViolations, BooleanLiteral.valueOf(isLogValidationViolations())); - m.add(implNode, CONFIG.Shacl.validationEnabled, BooleanLiteral.valueOf(isValidationEnabled())); - m.add(implNode, CONFIG.Shacl.cacheSelectNodes, BooleanLiteral.valueOf(isCacheSelectNodes())); - m.add(implNode, CONFIG.Shacl.globalLogValidationExecution, - BooleanLiteral.valueOf(isGlobalLogValidationExecution())); - m.add(implNode, CONFIG.Shacl.rdfsSubClassReasoning, BooleanLiteral.valueOf(isRdfsSubClassReasoning())); - m.add(implNode, CONFIG.Shacl.performanceLogging, BooleanLiteral.valueOf(isPerformanceLogging())); - m.add(implNode, CONFIG.Shacl.serializableValidation, BooleanLiteral.valueOf(isSerializableValidation())); - m.add(implNode, CONFIG.Shacl.eclipseRdf4jShaclExtensions, - BooleanLiteral.valueOf(isEclipseRdf4jShaclExtensions())); - m.add(implNode, CONFIG.Shacl.dashDataShapes, BooleanLiteral.valueOf(isDashDataShapes())); - m.add(implNode, CONFIG.Shacl.validationResultsLimitTotal, literal(getValidationResultsLimitTotal())); - m.add(implNode, CONFIG.Shacl.validationResultsLimitPerConstraint, - literal(getValidationResultsLimitPerConstraint())); - m.add(implNode, CONFIG.Shacl.transactionalValidationLimit, literal(getTransactionalValidationLimit())); - - for (IRI shapesGraph : shapesGraphs) { - m.add(implNode, CONFIG.Shacl.shapesGraph, shapesGraph); - } - - } else { - - m.add(implNode, PARALLEL_VALIDATION, BooleanLiteral.valueOf(isParallelValidation())); - m.add(implNode, LOG_VALIDATION_PLANS, BooleanLiteral.valueOf(isLogValidationPlans())); - m.add(implNode, LOG_VALIDATION_VIOLATIONS, BooleanLiteral.valueOf(isLogValidationViolations())); - m.add(implNode, VALIDATION_ENABLED, BooleanLiteral.valueOf(isValidationEnabled())); - m.add(implNode, CACHE_SELECT_NODES, BooleanLiteral.valueOf(isCacheSelectNodes())); - m.add(implNode, GLOBAL_LOG_VALIDATION_EXECUTION, BooleanLiteral.valueOf(isGlobalLogValidationExecution())); - m.add(implNode, RDFS_SUB_CLASS_REASONING, BooleanLiteral.valueOf(isRdfsSubClassReasoning())); - m.add(implNode, PERFORMANCE_LOGGING, BooleanLiteral.valueOf(isPerformanceLogging())); - m.add(implNode, SERIALIZABLE_VALIDATION, BooleanLiteral.valueOf(isSerializableValidation())); - m.add(implNode, ECLIPSE_RDF4J_SHACL_EXTENSIONS, BooleanLiteral.valueOf(isEclipseRdf4jShaclExtensions())); - m.add(implNode, DASH_DATA_SHAPES, BooleanLiteral.valueOf(isDashDataShapes())); - m.add(implNode, VALIDATION_RESULTS_LIMIT_TOTAL, literal(getValidationResultsLimitTotal())); - m.add(implNode, VALIDATION_RESULTS_LIMIT_PER_CONSTRAINT, literal(getValidationResultsLimitPerConstraint())); - m.add(implNode, TRANSACTIONAL_VALIDATION_LIMIT, literal(getTransactionalValidationLimit())); - - for (IRI shapesGraph : shapesGraphs) { - m.add(implNode, SHAPES_GRAPH, shapesGraph); - } + m.add(implNode, CONFIG.Shacl.parallelValidation, BooleanLiteral.valueOf(isParallelValidation())); + m.add(implNode, CONFIG.Shacl.logValidationPlans, BooleanLiteral.valueOf(isLogValidationPlans())); + m.add(implNode, CONFIG.Shacl.logValidationViolations, BooleanLiteral.valueOf(isLogValidationViolations())); + m.add(implNode, CONFIG.Shacl.validationEnabled, BooleanLiteral.valueOf(isValidationEnabled())); + m.add(implNode, CONFIG.Shacl.cacheSelectNodes, BooleanLiteral.valueOf(isCacheSelectNodes())); + m.add(implNode, CONFIG.Shacl.globalLogValidationExecution, + BooleanLiteral.valueOf(isGlobalLogValidationExecution())); + m.add(implNode, CONFIG.Shacl.rdfsSubClassReasoning, BooleanLiteral.valueOf(isRdfsSubClassReasoning())); + m.add(implNode, CONFIG.Shacl.performanceLogging, BooleanLiteral.valueOf(isPerformanceLogging())); + m.add(implNode, CONFIG.Shacl.serializableValidation, BooleanLiteral.valueOf(isSerializableValidation())); + m.add(implNode, CONFIG.Shacl.eclipseRdf4jShaclExtensions, + BooleanLiteral.valueOf(isEclipseRdf4jShaclExtensions())); + m.add(implNode, CONFIG.Shacl.dashDataShapes, BooleanLiteral.valueOf(isDashDataShapes())); + m.add(implNode, CONFIG.Shacl.validationResultsLimitTotal, literal(getValidationResultsLimitTotal())); + m.add(implNode, CONFIG.Shacl.validationResultsLimitPerConstraint, + literal(getValidationResultsLimitPerConstraint())); + m.add(implNode, CONFIG.Shacl.transactionalValidationLimit, literal(getTransactionalValidationLimit())); + + for (IRI shapesGraph : shapesGraphs) { + m.add(implNode, CONFIG.Shacl.shapesGraph, shapesGraph); } return implNode; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/results/lazy/ValidationResultIterator.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/results/lazy/ValidationResultIterator.java index b0ba38ca007..c0272b675d8 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/results/lazy/ValidationResultIterator.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/results/lazy/ValidationResultIterator.java @@ -21,7 +21,6 @@ import org.eclipse.rdf4j.common.annotation.InternalUseOnly; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.CloseableIteratorIteration; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.shacl.ast.planNodes.ValidationTuple; import org.eclipse.rdf4j.sail.shacl.results.ValidationResult; @@ -34,9 +33,9 @@ public class ValidationResultIterator implements Iterator { private boolean truncated = false; private Iterator next = Collections.emptyIterator(); - private CloseableIteration tupleIterator; + private CloseableIteration tupleIterator; - public ValidationResultIterator(CloseableIteration tupleIterator, + public ValidationResultIterator(CloseableIteration tupleIterator, long limit) { this.limit = limit; this.tupleIterator = tupleIterator; diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/data/CloseablePeakableIteration.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/data/CloseablePeakableIteration.java index 191afd952e9..5a351e1886e 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/data/CloseablePeakableIteration.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/data/CloseablePeakableIteration.java @@ -19,23 +19,23 @@ * warning from one release to the next. */ @InternalUseOnly -public class CloseablePeakableIteration implements CloseableIteration { +public class CloseablePeakableIteration implements CloseableIteration { - CloseableIteration parent; + CloseableIteration parent; E peek; - public CloseablePeakableIteration(CloseableIteration parent) { + public CloseablePeakableIteration(CloseableIteration parent) { this.parent = parent; } @Override - public void close() throws X { + public void close() { parent.close(); } @Override - public boolean hasNext() throws X { + public boolean hasNext() { if (peek != null) { return true; } @@ -43,7 +43,7 @@ public boolean hasNext() throws X { } @Override - public E next() throws X { + public E next() { E next; if (peek != null) { next = peek; @@ -56,11 +56,11 @@ public E next() throws X { } @Override - public void remove() throws X { + public void remove() { parent.remove(); } - public E peek() throws X { + public E peek() { if (peek == null) { peek = parent.next(); } diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/data/VerySimpleRdfsBackwardsChainingConnection.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/data/VerySimpleRdfsBackwardsChainingConnection.java index ab0f1eabd2f..3e08175edaa 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/data/VerySimpleRdfsBackwardsChainingConnection.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/data/VerySimpleRdfsBackwardsChainingConnection.java @@ -62,7 +62,7 @@ public boolean hasStatement(Resource subj, IRI pred, Value obj, boolean includeI return hasStatement; } if (types.size() > 10) { - try (CloseableIteration statements = super.getStatements(subj, + try (CloseableIteration statements = super.getStatements(subj, RDF.TYPE, null, false, contexts)) { return statements.stream() .map(Statement::getObject) @@ -82,7 +82,7 @@ public boolean hasStatement(Resource subj, IRI pred, Value obj, boolean includeI } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { if (rdfsSubClassOfReasoner != null && includeInferred && obj != null && obj.isResource() @@ -90,13 +90,13 @@ public CloseableIteration getStatements(Reso Set inferredTypes = rdfsSubClassOfReasoner.backwardsChain((Resource) obj); if (inferredTypes.size() > 1) { - CloseableIteration[] statementsMatchingInferredTypes = inferredTypes.stream() + CloseableIteration[] statementsMatchingInferredTypes = inferredTypes.stream() .map(r -> super.getStatements(subj, pred, r, false, contexts)) .toArray(CloseableIteration[]::new); return new LookAheadIteration<>() { - final UnionIteration unionIteration = new UnionIteration<>( + final UnionIteration unionIteration = new UnionIteration<>( statementsMatchingInferredTypes); final HashSet dedupe = new HashSet<>(); diff --git a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/shape/ShapeSourceHelper.java b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/shape/ShapeSourceHelper.java index e35258ea2df..b5c16b8b0b2 100644 --- a/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/shape/ShapeSourceHelper.java +++ b/core/sail/shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/wrapper/shape/ShapeSourceHelper.java @@ -19,7 +19,6 @@ import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.repository.RepositoryResult; import org.eclipse.rdf4j.sail.SailConnection; -import org.eclipse.rdf4j.sail.SailException; class ShapeSourceHelper { @@ -58,7 +57,7 @@ static Resource getRdfRest(SailConnection connection, Resource subject, Resource // .orElse(null); // } - private static Value getObject(CloseableIteration iteration) { + private static Value getObject(CloseableIteration iteration) { if (iteration.hasNext()) { return iteration.next().getObject(); } diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/MultithreadedLmdbStoreIT.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/MultithreadedLmdbStoreIT.java new file mode 100644 index 00000000000..4584b9e10c0 --- /dev/null +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/MultithreadedLmdbStoreIT.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.sail.shacl; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.io.FileUtils; +import org.assertj.core.util.Files; +import org.eclipse.rdf4j.common.transaction.IsolationLevels; +import org.eclipse.rdf4j.sail.NotifyingSail; +import org.eclipse.rdf4j.sail.NotifyingSailConnection; +import org.eclipse.rdf4j.sail.lmdb.LmdbStore; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +@Tag("slow") +public class MultithreadedLmdbStoreIT extends MultithreadedTest { + + File file; + + @AfterEach + public void after() { + try { + FileUtils.deleteDirectory(file); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @BeforeEach + public void before() { + file = Files.newTemporaryFolder(); + System.out.println("Max memory: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + " MB"); + } + + @Override + NotifyingSail getBaseSail() { + NotifyingSail notifyingSail = new LmdbStore(file); + try (NotifyingSailConnection connection = notifyingSail.getConnection()) { + connection.begin(IsolationLevels.NONE); + connection.clear(); + connection.commit(); + } + return notifyingSail; + } + +} diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/MultithreadedLmdbStoreRDFSIT.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/MultithreadedLmdbStoreRDFSIT.java new file mode 100644 index 00000000000..2a01f18a268 --- /dev/null +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/MultithreadedLmdbStoreRDFSIT.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.sail.shacl; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.io.FileUtils; +import org.assertj.core.util.Files; +import org.eclipse.rdf4j.common.transaction.IsolationLevels; +import org.eclipse.rdf4j.sail.NotifyingSail; +import org.eclipse.rdf4j.sail.NotifyingSailConnection; +import org.eclipse.rdf4j.sail.inferencer.fc.SchemaCachingRDFSInferencer; +import org.eclipse.rdf4j.sail.lmdb.LmdbStore; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; + +@Tag("slow") +public class MultithreadedLmdbStoreRDFSIT extends MultithreadedTest { + + File file; + + @AfterEach + public void after() { + try { + FileUtils.deleteDirectory(file); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @BeforeEach + public void before() { + file = Files.newTemporaryFolder(); + } + + @Override + NotifyingSail getBaseSail() { + NotifyingSail notifyingSail = new LmdbStore(file); + notifyingSail = new SchemaCachingRDFSInferencer(notifyingSail); + try (NotifyingSailConnection connection = notifyingSail.getConnection()) { + connection.begin(IsolationLevels.NONE); + connection.clear(); + connection.commit(); + } + return notifyingSail; + } + +} diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/NativeStoreTest.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/NativeStoreTest.java index cc5aeaf099f..2eaad2fd48b 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/NativeStoreTest.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/NativeStoreTest.java @@ -28,7 +28,7 @@ public class NativeStoreTest { @Test - public void testEmpty(@TempDir File file) throws IOException { + public void testEmpty(@TempDir File file) { SailRepository shaclSail = new SailRepository(new ShaclSail(new NativeStore(file))); shaclSail.init(); shaclSail.shutDown(); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/RdfsShaclConnectionTest.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/RdfsShaclConnectionTest.java index 4c2cc93bc78..39dc1780a59 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/RdfsShaclConnectionTest.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/RdfsShaclConnectionTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.shacl; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -80,24 +79,21 @@ public void testGetStatement() { try (Stream stream = connection2.getStatements(aSubSub, RDF.TYPE, sup, true) .stream()) { Set collect = stream.collect(Collectors.toSet()); - HashSet expected = new HashSet<>( - Collections.singletonList(vf.createStatement(aSubSub, RDF.TYPE, sup))); + Set expected = Set.of(vf.createStatement(aSubSub, RDF.TYPE, sup)); Assertions.assertEquals(expected, collect); } try (Stream stream = connection2.getStatements(aSubSub, RDF.TYPE, sub, true) .stream()) { Set collect = stream.collect(Collectors.toSet()); - HashSet expected = new HashSet<>( - Collections.singletonList(vf.createStatement(aSubSub, RDF.TYPE, sub))); + Set expected = Set.of(vf.createStatement(aSubSub, RDF.TYPE, sub)); Assertions.assertEquals(expected, collect); } try (Stream stream = connection2.getStatements(aSubSub, RDF.TYPE, subSub, true) .stream()) { Set collect = stream.collect(Collectors.toSet()); - HashSet expected = new HashSet<>( - Collections.singletonList(vf.createStatement(aSubSub, RDF.TYPE, subSub))); + Set expected = Set.of(vf.createStatement(aSubSub, RDF.TYPE, subSub)); Assertions.assertEquals(expected, collect); } } diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/ShaclSailSupportedPredicatesDocumentationIT.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/ShaclSailSupportedPredicatesDocumentationIT.java index d3beeff514e..96a7155d4f8 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/ShaclSailSupportedPredicatesDocumentationIT.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/ShaclSailSupportedPredicatesDocumentationIT.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.sail.shacl; -import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -46,7 +45,7 @@ public static void afterClass() { @ParameterizedTest @MethodSource("testCases") - public void testShaclSailSupportedPredicatesDocumentation(TestCase testCase) throws IOException { + public void testShaclSailSupportedPredicatesDocumentation(TestCase testCase) { HashSet shaclPredicates = new HashSet<>(ShaclSail.getSupportedShaclPredicates()); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/UnknownShapesTest.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/UnknownShapesTest.java index 91b8a0498d2..44175008568 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/UnknownShapesTest.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/UnknownShapesTest.java @@ -67,8 +67,8 @@ public void testPropertyShapes() throws IOException { Set relevantLog = getRelevantLog(2); Set expected = Set.of( - "Unsupported SHACL feature detected sh:unknownShaclProperty in statement (http://example.com/ns#PersonPropertyShape, http://www.w3.org/ns/shacl#unknownShaclProperty, \"1\"^^)", - "Unsupported SHACL feature detected sh:unknownTarget in statement (http://example.com/ns#PersonShape, http://www.w3.org/ns/shacl#unknownTarget, http://www.w3.org/2000/01/rdf-schema#Class)" + "Unsupported SHACL feature detected sh:unknownShaclProperty in statement (http://example.com/ns#PersonPropertyShape, http://www.w3.org/ns/shacl#unknownShaclProperty, \"1\"^^) [null]", + "Unsupported SHACL feature detected sh:unknownTarget in statement (http://example.com/ns#PersonShape, http://www.w3.org/ns/shacl#unknownTarget, http://www.w3.org/2000/01/rdf-schema#Class) [null]" ); Assertions.assertEquals(expected, relevantLog); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/W3cComplianceTest.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/W3cComplianceTest.java index 1c1f85880aa..58017da8de4 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/W3cComplianceTest.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/W3cComplianceTest.java @@ -81,7 +81,7 @@ public static Stream data() { @ParameterizedTest @MethodSource("data") - public void test(URL testCasePath) throws IOException, InterruptedException { + public void test(URL testCasePath) throws IOException { boolean testPassed = false; try { runTest(testCasePath); @@ -217,7 +217,7 @@ public Manifest(URL filename) { } - private void runTest(URL resourceName) throws IOException, InterruptedException { + private void runTest(URL resourceName) throws IOException { W3C_shaclTestValidate expected = new W3C_shaclTestValidate(resourceName); SailRepository data = new SailRepository(new MemoryStore()); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/AddRemoveBenchmarkEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/AddRemoveBenchmarkEmpty.java index 4ce1be5ccf6..7412e39e064 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/AddRemoveBenchmarkEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/AddRemoveBenchmarkEmpty.java @@ -56,7 +56,7 @@ public class AddRemoveBenchmarkEmpty { private List> allStatements; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexBenchmark.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexBenchmark.java index e236b75507d..7799ee42c0d 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexBenchmark.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexBenchmark.java @@ -78,7 +78,7 @@ public class ComplexBenchmark { } @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { ((Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName())) .setLevel(ch.qos.logback.classic.Level.ERROR); ((Logger) LoggerFactory.getLogger(ShaclSail.class.getName())).setLevel(ch.qos.logback.classic.Level.ERROR); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexLargeBenchmark.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexLargeBenchmark.java index ee455397b7a..48f9236611d 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexLargeBenchmark.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexLargeBenchmark.java @@ -15,6 +15,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.net.URL; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; @@ -31,6 +32,8 @@ import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.Rio; +import org.eclipse.rdf4j.sail.NotifyingSail; +import org.eclipse.rdf4j.sail.lmdb.LmdbStore; import org.eclipse.rdf4j.sail.nativerdf.NativeStore; import org.eclipse.rdf4j.sail.shacl.ShaclSail; import org.eclipse.rdf4j.sail.shacl.ShaclSailConnection; @@ -112,7 +115,7 @@ public void teardown() { } } - public static void main(String[] args) throws IOException, InterruptedException { + public static void main(String[] args) throws InterruptedException { ComplexLargeBenchmark complexLargeBenchmark = new ComplexLargeBenchmark(); complexLargeBenchmark.setUp(); for (int i = 0; i < 20; i++) { @@ -322,6 +325,46 @@ public void noPreloadingNonEmptyParallel() { } + @Benchmark + public void noPreloadingNonEmptyParallelLmdb() { + + try { + File file = Files.newTemporaryFolder(); + SailRepository repository = new SailRepository(new ShaclSail(new LmdbStore(file))); + try (SailRepositoryConnection connection = repository.getConnection()) { + connection.begin(ShaclSail.TransactionSettings.ValidationApproach.Disabled); + URL shacl = ComplexLargeBenchmark.class.getClassLoader().getResource("complexBenchmark/shacl.trig"); + connection.add(shacl, RDFFormat.TRIG); + connection.commit(); + } + + ((ShaclSail) repository.getSail()).setTransactionalValidationLimit(1000000); + + try (SailRepositoryConnection connection = repository.getConnection()) { + connection.begin(IsolationLevels.NONE, ShaclSail.TransactionSettings.ValidationApproach.Disabled); + SimpleValueFactory vf = SimpleValueFactory.getInstance(); + connection.add(vf.createBNode(), DUMMY_PREDICATE, vf.createBNode()); + connection.commit(); + } + + ((ShaclSail) repository.getSail()).setParallelValidation(true); + ((ShaclSail) repository.getSail()).setCacheSelectNodes(true); + ((ShaclSail) repository.getSail()).setPerformanceLogging(false); + + try (SailRepositoryConnection connection = repository.getConnection()) { + connection.begin(IsolationLevels.NONE); + connection.add(realData); + connection.commit(); + } + + repository.shutDown(); + + } catch (IOException e) { + throw new RuntimeException(e); + } + + } + @Benchmark public void noPreloadingNonEmptyParallelReadCommitted() { diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexTargetBenchmark.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexTargetBenchmark.java index 5cfb7e4e5db..f1e6aae63cf 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexTargetBenchmark.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ComplexTargetBenchmark.java @@ -126,7 +126,7 @@ public void invocationSetup() throws IOException, InterruptedException { } @Benchmark - public void benchmark() throws Exception { + public void benchmark() { try (SailRepositoryConnection connection = repository.getConnection()) { for (List statements : transactions) { diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkEmpty.java index d451bc35860..6a7023e7b7f 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkEmpty.java @@ -56,7 +56,7 @@ public class DatatypeBenchmarkEmpty { private List> allStatements; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkPrefilled.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkPrefilled.java index 80edb18faa3..b142f5c348d 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkPrefilled.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkPrefilled.java @@ -98,7 +98,7 @@ public void setUp() throws Exception { } @TearDown(Level.Invocation) - public void tearDown() throws Exception { + public void tearDown() { if (shaclRepo != null) { shaclRepo.shutDown(); } diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkSerializableEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkSerializableEmpty.java index 4996b88f8d8..5506251f3ad 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkSerializableEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/DatatypeBenchmarkSerializableEmpty.java @@ -55,7 +55,7 @@ public class DatatypeBenchmarkSerializableEmpty { private List> allStatements; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { ((Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName())) .setLevel(ch.qos.logback.classic.Level.ERROR); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/HasValueBenchmarkEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/HasValueBenchmarkEmpty.java index f39a0aa74af..890f7dff49d 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/HasValueBenchmarkEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/HasValueBenchmarkEmpty.java @@ -64,7 +64,7 @@ public class HasValueBenchmarkEmpty { private List> allStatements; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/LanguageInBenchmarkEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/LanguageInBenchmarkEmpty.java index 38d70fef325..204fbd81bdf 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/LanguageInBenchmarkEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/LanguageInBenchmarkEmpty.java @@ -58,7 +58,7 @@ public class LanguageInBenchmarkEmpty { private final Random random = new Random(849075897); @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NativeStoreBenchmark.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NativeStoreBenchmark.java index 928f70dd029..99958b4d38a 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NativeStoreBenchmark.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NativeStoreBenchmark.java @@ -63,7 +63,7 @@ public class NativeStoreBenchmark { @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { ((Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName())) .setLevel(ch.qos.logback.classic.Level.ERROR); ((Logger) LoggerFactory.getLogger(ShaclSail.class.getName())).setLevel(ch.qos.logback.classic.Level.ERROR); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NotClassBenchmarkEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NotClassBenchmarkEmpty.java index 1edc31490ae..3aed24b684d 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NotClassBenchmarkEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NotClassBenchmarkEmpty.java @@ -59,7 +59,7 @@ public class NotClassBenchmarkEmpty { private final IRI ANIMAL = vf.createIRI("http://example.com/ns#Animal"); @Setup(Level.Iteration) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NotUniqueLangBenchmarkEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NotUniqueLangBenchmarkEmpty.java index 2bbcfffe536..1ff6ed89a1a 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NotUniqueLangBenchmarkEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/NotUniqueLangBenchmarkEmpty.java @@ -55,7 +55,7 @@ public class NotUniqueLangBenchmarkEmpty { private List> allStatements; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/OrDatatypeBenchmark.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/OrDatatypeBenchmark.java index 4df2de3e395..8fd7e1f66a6 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/OrDatatypeBenchmark.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/OrDatatypeBenchmark.java @@ -56,7 +56,7 @@ public class OrDatatypeBenchmark { private List> allStatements; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.WARN); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ShaclLoadingBenchmark.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ShaclLoadingBenchmark.java index b17fa5d51e8..ed3798e2103 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ShaclLoadingBenchmark.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ShaclLoadingBenchmark.java @@ -50,7 +50,7 @@ public class ShaclLoadingBenchmark { @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { ((Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName())) .setLevel(ch.qos.logback.classic.Level.ERROR); ((Logger) LoggerFactory.getLogger(ShaclSail.class.getName())).setLevel(ch.qos.logback.classic.Level.ERROR); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/TargetBenchmarkInitialData.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/TargetBenchmarkInitialData.java index f2482c3333e..eb8323a795f 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/TargetBenchmarkInitialData.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/TargetBenchmarkInitialData.java @@ -120,7 +120,7 @@ public void invocationSetup() throws IOException, InterruptedException { } @Benchmark - public void benchmark() throws Exception { + public void benchmark() { runBenchmark(repository); } diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/TargetShapeBenchmark.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/TargetShapeBenchmark.java index 639e6bd79fd..399ff7a2d46 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/TargetShapeBenchmark.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/TargetShapeBenchmark.java @@ -48,7 +48,7 @@ public class TargetShapeBenchmark { @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); } diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/UniqueLangBenchmarkEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/UniqueLangBenchmarkEmpty.java index a2226ed483a..b9b295302e1 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/UniqueLangBenchmarkEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/UniqueLangBenchmarkEmpty.java @@ -55,7 +55,7 @@ public class UniqueLangBenchmarkEmpty { private List> allStatements; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ValueInBenchmarkEmpty.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ValueInBenchmarkEmpty.java index efd03013696..8cf410b5ddc 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ValueInBenchmarkEmpty.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/benchmark/ValueInBenchmarkEmpty.java @@ -66,7 +66,7 @@ public class ValueInBenchmarkEmpty { private List> allStatements; @Setup(Level.Trial) - public void setUp() throws InterruptedException { + public void setUp() { Logger root = (Logger) LoggerFactory.getLogger(ShaclSailConnection.class.getName()); root.setLevel(ch.qos.logback.classic.Level.INFO); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/config/ShaclSailConfigTest.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/config/ShaclSailConfigTest.java index 1dc91665a9f..2638a59b295 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/config/ShaclSailConfigTest.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/config/ShaclSailConfigTest.java @@ -115,20 +115,20 @@ public void parseFromModelSetValuesCorrectly() { shaclSailConfig.parse(mb.build(), implNode); - assertThat(shaclSailConfig.isParallelValidation()).isTrue(); - assertThat(shaclSailConfig.isLogValidationPlans()).isTrue(); - assertThat(shaclSailConfig.isLogValidationViolations()).isTrue(); - assertThat(shaclSailConfig.isValidationEnabled()).isTrue(); - assertThat(shaclSailConfig.isCacheSelectNodes()).isTrue(); - assertThat(shaclSailConfig.isGlobalLogValidationExecution()).isTrue(); - assertThat(shaclSailConfig.isRdfsSubClassReasoning()).isFalse(); - assertThat(shaclSailConfig.isPerformanceLogging()).isTrue(); - assertThat(shaclSailConfig.isSerializableValidation()).isFalse(); - assertThat(shaclSailConfig.isEclipseRdf4jShaclExtensions()).isTrue(); - assertThat(shaclSailConfig.isDashDataShapes()).isTrue(); - assertThat(shaclSailConfig.getValidationResultsLimitTotal()).isEqualTo(100); - assertThat(shaclSailConfig.getValidationResultsLimitPerConstraint()).isEqualTo(3); - assertThat(shaclSailConfig.getTransactionalValidationLimit()).isEqualTo(9); + assertThat(shaclSailConfig.isParallelValidation()).isFalse(); + assertThat(shaclSailConfig.isLogValidationPlans()).isFalse(); + assertThat(shaclSailConfig.isLogValidationViolations()).isFalse(); + assertThat(shaclSailConfig.isValidationEnabled()).isFalse(); + assertThat(shaclSailConfig.isCacheSelectNodes()).isFalse(); + assertThat(shaclSailConfig.isGlobalLogValidationExecution()).isFalse(); + assertThat(shaclSailConfig.isRdfsSubClassReasoning()).isTrue(); + assertThat(shaclSailConfig.isPerformanceLogging()).isFalse(); + assertThat(shaclSailConfig.isSerializableValidation()).isTrue(); + assertThat(shaclSailConfig.isEclipseRdf4jShaclExtensions()).isFalse(); + assertThat(shaclSailConfig.isDashDataShapes()).isFalse(); + assertThat(shaclSailConfig.getValidationResultsLimitTotal()).isEqualTo(1000); + assertThat(shaclSailConfig.getValidationResultsLimitPerConstraint()).isEqualTo(30); + assertThat(shaclSailConfig.getTransactionalValidationLimit()).isEqualTo(90); assertThat(shaclSailConfig.getShapesGraphs()).isEqualTo(shapesGraphs); } @@ -139,7 +139,7 @@ public void parseFromPartialModelSetValuesCorrectly() { BNode implNode = SimpleValueFactory.getInstance().createBNode(); ModelBuilder mb = new ModelBuilder().subject(implNode); - mb.add(PARALLEL_VALIDATION, false); + mb.add(CONFIG.Shacl.parallelValidation, false); shaclSailConfig.parse(mb.build(), implNode); @@ -154,7 +154,7 @@ public void parseInvalidModelGivesCorrectException() { BNode implNode = SimpleValueFactory.getInstance().createBNode(); ModelBuilder mb = new ModelBuilder().subject(implNode); - mb.add(PARALLEL_VALIDATION, "I'm not a boolean"); + mb.add(CONFIG.Shacl.parallelValidation, "I'm not a boolean"); assertThrows(SailConfigException.class, () -> { shaclSailConfig.parse(mb.build(), implNode); @@ -180,21 +180,21 @@ public void exportAddsAllConfigData() { Model m = new TreeModel(); Resource node = shaclSailConfig.export(m); - Assertions.assertTrue(m.contains(node, PARALLEL_VALIDATION, null)); - Assertions.assertTrue(m.contains(node, LOG_VALIDATION_PLANS, null)); - Assertions.assertTrue(m.contains(node, LOG_VALIDATION_VIOLATIONS, null)); - Assertions.assertTrue(m.contains(node, VALIDATION_ENABLED, null)); - Assertions.assertTrue(m.contains(node, CACHE_SELECT_NODES, null)); - Assertions.assertTrue(m.contains(node, GLOBAL_LOG_VALIDATION_EXECUTION, null)); - Assertions.assertTrue(m.contains(node, RDFS_SUB_CLASS_REASONING, null)); - Assertions.assertTrue(m.contains(node, PERFORMANCE_LOGGING, null)); - Assertions.assertTrue(m.contains(node, SERIALIZABLE_VALIDATION, null)); - Assertions.assertTrue(m.contains(node, ECLIPSE_RDF4J_SHACL_EXTENSIONS, null)); - Assertions.assertTrue(m.contains(node, DASH_DATA_SHAPES, null)); - Assertions.assertTrue(m.contains(node, VALIDATION_RESULTS_LIMIT_TOTAL, null)); - Assertions.assertTrue(m.contains(node, VALIDATION_RESULTS_LIMIT_PER_CONSTRAINT, null)); - Assertions.assertTrue(m.contains(node, TRANSACTIONAL_VALIDATION_LIMIT, null)); - Assertions.assertTrue(m.contains(node, SHAPES_GRAPH, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.parallelValidation, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.logValidationPlans, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.logValidationViolations, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.validationEnabled, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.cacheSelectNodes, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.globalLogValidationExecution, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.rdfsSubClassReasoning, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.performanceLogging, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.serializableValidation, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.eclipseRdf4jShaclExtensions, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.dashDataShapes, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.validationResultsLimitPerConstraint, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.validationResultsLimitTotal, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.transactionalValidationLimit, null)); + Assertions.assertTrue(m.contains(node, CONFIG.Shacl.shapesGraph, null)); } diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/mock/MockConsumePlanNode.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/mock/MockConsumePlanNode.java index 79f14c95428..4ed2ad4c27f 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/mock/MockConsumePlanNode.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/mock/MockConsumePlanNode.java @@ -15,7 +15,6 @@ import java.util.List; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.shacl.ast.planNodes.PlanNode; import org.eclipse.rdf4j.sail.shacl.ast.planNodes.ValidationExecutionLogger; import org.eclipse.rdf4j.sail.shacl.ast.planNodes.ValidationTuple; @@ -37,7 +36,7 @@ public MockConsumePlanNode(PlanNode innerNode) { public List asList() { - try (CloseableIteration iterator = innerNode.iterator()) { + try (CloseableIteration iterator = innerNode.iterator()) { List ret = new ArrayList<>(); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/mock/MockInputPlanNode.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/mock/MockInputPlanNode.java index 61565235c53..7cfde46c651 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/mock/MockInputPlanNode.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/mock/MockInputPlanNode.java @@ -64,7 +64,7 @@ public MockInputPlanNode(Collection... list) { } @Override - public CloseableIteration iterator() { + public CloseableIteration iterator() { return new CloseableIteration<>() { final Iterator iterator = initialData.iterator(); diff --git a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/rdf4jcompliance/ShaclIsolationLevelTest.java b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/rdf4jcompliance/ShaclIsolationLevelTest.java index 739f1c952e2..52ba501d547 100644 --- a/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/rdf4jcompliance/ShaclIsolationLevelTest.java +++ b/core/sail/shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/rdf4jcompliance/ShaclIsolationLevelTest.java @@ -30,7 +30,7 @@ protected Sail createSail() throws SailException { } @Override - public void testLargeTransaction(IsolationLevel isolationLevel, int count) throws InterruptedException { + public void testLargeTransaction(IsolationLevel isolationLevel, int count) { // see: https://github.com/eclipse/rdf4j/issues/1795 } } diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/SpinParser.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/SpinParser.java index e146d17854a..c6652d4c35e 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/SpinParser.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/SpinParser.java @@ -30,7 +30,6 @@ import org.eclipse.rdf4j.common.exception.RDF4JException; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; @@ -253,7 +252,7 @@ public void setStrictFunctionChecking(boolean strictFunctionChecking) { public Map parseRuleProperties(TripleSource store) throws RDF4JException { Map rules = new HashMap<>(); - try (CloseableIteration rulePropIter = TripleSources + try (CloseableIteration rulePropIter = TripleSources .getSubjectURIs(RDFS.SUBPROPERTYOF, SPIN.RULE_PROPERTY, store)) { while (rulePropIter.hasNext()) { @@ -353,7 +352,7 @@ protected ParsedOperation parse(Resource queryResource, IRI queryClass, TripleSo Boolean isQueryElseTemplate = null; Set possibleQueryTypes = new HashSet<>(); Set possibleTemplates = new HashSet<>(); - try (CloseableIteration typeIter = TripleSources + try (CloseableIteration typeIter = TripleSources .getObjectURIs(queryResource, RDF.TYPE, store)) { while (typeIter.hasNext()) { IRI type = typeIter.next(); @@ -563,7 +562,7 @@ public Map parseArguments(final IRI moduleUri, final TripleSource } private void parseArguments(IRI moduleUri, TripleSource store, Map args) throws RDF4JException { - try (CloseableIteration argIter = TripleSources + try (CloseableIteration argIter = TripleSources .getObjectResources(moduleUri, SPIN.CONSTRAINT_PROPERTY, store)) { while (argIter.hasNext()) { @@ -871,7 +870,7 @@ private void addSourceExpressions(UnaryTupleOperator op, Collection projElemLists = new ArrayList<>(); - Iteration iter = TripleSources.listResources(templates, + CloseableIteration iter = TripleSources.listResources(templates, store); while (iter.hasNext()) { Resource r = iter.next(); @@ -909,7 +908,7 @@ private ProjectionElemList visitTemplate(Resource r) throws RDF4JException { private Projection visitResultNodes(Resource resultNodes) throws RDF4JException { ProjectionElemList projElemList = new ProjectionElemList(); - Iteration iter = TripleSources.listResources(resultNodes, + CloseableIteration iter = TripleSources.listResources(resultNodes, store); while (iter.hasNext()) { Resource r = iter.next(); @@ -931,7 +930,7 @@ private ProjectionElem visitResultNode(Resource r) throws RDF4JException { private Projection visitResultVariables(Resource resultVars, Map previousProjElems) throws RDF4JException { ProjectionElemList projElemList = new ProjectionElemList(); - Iteration iter = TripleSources.listResources(resultVars, + CloseableIteration iter = TripleSources.listResources(resultVars, store); while (iter.hasNext()) { Resource r = iter.next(); @@ -955,7 +954,7 @@ private void visitGroupBy(Resource groupby) throws RDF4JException { if (group == null) { group = new Group(); } - Iteration iter = TripleSources.listResources(groupby, store); + CloseableIteration iter = TripleSources.listResources(groupby, store); while (iter.hasNext()) { Resource r = iter.next(); ValueExpr groupByExpr = visitExpression(r); @@ -972,7 +971,7 @@ private void visitGroupBy(Resource groupby) throws RDF4JException { private TupleExpr visitHaving(Resource having) throws RDF4JException { UnaryTupleOperator op = (UnaryTupleOperator) group.getParentNode(); op.setArg(new Extension(group)); - Iteration iter = TripleSources.listResources(having, store); + CloseableIteration iter = TripleSources.listResources(having, store); while (iter.hasNext()) { Resource r = iter.next(); ValueExpr havingExpr = visitExpression(r); @@ -985,7 +984,7 @@ private TupleExpr visitHaving(Resource having) throws RDF4JException { private Order visitOrderBy(Resource orderby) throws RDF4JException { Order order = new Order(); - Iteration iter = TripleSources.listResources(orderby, store); + CloseableIteration iter = TripleSources.listResources(orderby, store); while (iter.hasNext()) { Resource r = iter.next(); OrderElem orderElem = visitOrderByCondition(r); @@ -1182,7 +1181,7 @@ public TupleExpr visitGroupGraphPattern(Resource group) throws RDF4JException { QueryRoot groupRoot = new QueryRoot(tupleNode); Map> patternTypes = new LinkedHashMap<>(); - Iteration groupIter = TripleSources.listResources(group, + CloseableIteration groupIter = TripleSources.listResources(group, store); while (groupIter.hasNext()) { Resource r = groupIter.next(); @@ -1229,7 +1228,7 @@ public TupleExpr visitGroupGraphPattern(Resource group) throws RDF4JException { } private void visitInsert(Resource insert) throws RDF4JException { - Iteration groupIter = TripleSources.listResources(insert, + CloseableIteration groupIter = TripleSources.listResources(insert, store); while (groupIter.hasNext()) { Resource r = groupIter.next(); @@ -1239,7 +1238,7 @@ private void visitInsert(Resource insert) throws RDF4JException { } private void visitDelete(Resource delete) throws RDF4JException { - Iteration groupIter = TripleSources.listResources(delete, + CloseableIteration groupIter = TripleSources.listResources(delete, store); while (groupIter.hasNext()) { Resource r = groupIter.next(); @@ -1276,7 +1275,7 @@ private void visitPattern(Resource r, Set types, TupleExpr currentGroupExpr String.format("Value of %s is not a resource", SP.ELEMENTS_PROPERTY)); } - Iteration iter = TripleSources + CloseableIteration iter = TripleSources .listResources((Resource) elements, store); TupleExpr prev = null; while (iter.hasNext()) { @@ -1324,7 +1323,7 @@ private void visitPattern(Resource r, Set types, TupleExpr currentGroupExpr BindingSetAssignment bsa = new BindingSetAssignment(); Set varNames = new LinkedHashSet<>(); Value varNameList = TripleSources.singleValue(r, SP.VAR_NAMES_PROPERTY, store); - Iteration varNameIter = TripleSources + CloseableIteration varNameIter = TripleSources .list((Resource) varNameList, store); while (varNameIter.hasNext()) { Value v = varNameIter.next(); @@ -1335,13 +1334,13 @@ private void visitPattern(Resource r, Set types, TupleExpr currentGroupExpr bsa.setBindingNames(varNames); List bindingSets = new ArrayList<>(); Value bindingsList = TripleSources.singleValue(r, SP.BINDINGS_PROPERTY, store); - Iteration bindingsIter = TripleSources + CloseableIteration bindingsIter = TripleSources .list((Resource) bindingsList, store); while (bindingsIter.hasNext()) { Value valueList = bindingsIter.next(); QueryBindingSet bs = new QueryBindingSet(); Iterator nameIter = varNames.iterator(); - Iteration valueIter = TripleSources + CloseableIteration valueIter = TripleSources .list((Resource) valueList, store); while (nameIter.hasNext() && valueIter.hasNext()) { String name = nameIter.next(); diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/SpinRenderer.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/SpinRenderer.java index 552b331a3cd..c13af712cfb 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/SpinRenderer.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/SpinRenderer.java @@ -95,7 +95,7 @@ import org.eclipse.rdf4j.query.algebra.ValueConstant; import org.eclipse.rdf4j.query.algebra.ValueExpr; import org.eclipse.rdf4j.query.algebra.Var; -import org.eclipse.rdf4j.query.algebra.helpers.QueryModelVisitorBase; +import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; import org.eclipse.rdf4j.query.parser.ParsedBooleanQuery; import org.eclipse.rdf4j.query.parser.ParsedDescribeQuery; import org.eclipse.rdf4j.query.parser.ParsedGraphQuery; @@ -387,7 +387,7 @@ public void meet(ProjectionElem node) throws RDFHandlerException { } } - private class SpinVisitor extends QueryModelVisitorBase { + private class SpinVisitor extends AbstractQueryModelVisitor { final RDFHandler handler; @@ -1338,7 +1338,7 @@ public void meet(Create node) throws RDFHandlerException { } } - private final class ExtensionVisitor extends QueryModelVisitorBase { + private final class ExtensionVisitor extends AbstractQueryModelVisitor { @Override public void meet(Count node) throws RDFHandlerException { @@ -1437,7 +1437,7 @@ public void meet(Var node) throws RDFHandlerException { } } - private final class GroupVisitor extends QueryModelVisitorBase { + private final class GroupVisitor extends AbstractQueryModelVisitor { Group group; @@ -1486,7 +1486,7 @@ protected void meetNode(QueryModelNode node) { } } - private final class OrderVisitor extends QueryModelVisitorBase { + private final class OrderVisitor extends AbstractQueryModelVisitor { @Override public void meet(Order node) throws RDFHandlerException { @@ -1514,7 +1514,7 @@ protected void meetNode(QueryModelNode node) { } } - private static final class ExtensionContext extends QueryModelVisitorBase { + private static final class ExtensionContext extends AbstractQueryModelVisitor { Extension extension; diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/ConstructTupleFunction.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/ConstructTupleFunction.java index f17d369e78b..cd0fdd25ca0 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/ConstructTupleFunction.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/ConstructTupleFunction.java @@ -53,7 +53,7 @@ public void setSpinParser(SpinParser parser) { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( ValueFactory valueFactory, Value... args) throws QueryEvaluationException { QueryPreparer qp = getCurrentQueryPreparer(); if (args.length == 0 || !(args[0] instanceof Resource)) { @@ -75,7 +75,7 @@ public CloseableIteration, QueryEvaluationExcept } } - static class GraphQueryResultIteration extends AbstractCloseableIteration, QueryEvaluationException> { + static class GraphQueryResultIteration extends AbstractCloseableIteration> { private final GraphQueryResult queryResult; diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/EvalFunction.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/EvalFunction.java index cbc339ccdf1..27a8abb39d4 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/EvalFunction.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/EvalFunction.java @@ -25,7 +25,6 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.BooleanQuery; import org.eclipse.rdf4j.query.Query; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.query.algebra.Extension; @@ -120,7 +119,7 @@ public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExpr } private boolean isQuery(Resource r, TripleSource store) throws RDF4JException { - try (CloseableIteration typeIter = TripleSources.getObjectURIs(r, + try (CloseableIteration typeIter = TripleSources.getObjectURIs(r, RDF.TYPE, store)) { while (typeIter.hasNext()) { diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/ObjectFunction.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/ObjectFunction.java index c1b3fbc12f1..b55073576c3 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/ObjectFunction.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/ObjectFunction.java @@ -45,7 +45,7 @@ public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExpr } try { - try (CloseableIteration stmts = qp.getTripleSource() + try (CloseableIteration stmts = qp.getTripleSource() .getStatements((Resource) subj, (IRI) pred, null)) { if (stmts.hasNext()) { return stmts.next().getObject(); diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SelectTupleFunction.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SelectTupleFunction.java index d9bd1d1d5e4..1fa62734831 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SelectTupleFunction.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SelectTupleFunction.java @@ -59,7 +59,7 @@ public void setSpinParser(SpinParser parser) { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( ValueFactory valueFactory, Value... args) throws QueryEvaluationException { QueryPreparer qp = getCurrentQueryPreparer(); if (args.length == 0 || !(args[0] instanceof Resource)) { @@ -92,7 +92,7 @@ public CloseableIteration, QueryEvaluationExcept } } - static class TupleQueryResultIteration extends AbstractCloseableIteration, QueryEvaluationException> { + static class TupleQueryResultIteration extends AbstractCloseableIteration> { private final TupleQueryResult queryResult; diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SpinTupleFunction.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SpinTupleFunction.java index e3cc7ec2936..15db85021bf 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SpinTupleFunction.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SpinTupleFunction.java @@ -67,10 +67,10 @@ public String toString() { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( ValueFactory valueFactory, Value... args) throws QueryEvaluationException { QueryPreparer qp = getCurrentQueryPreparer(); - CloseableIteration, QueryEvaluationException> iter; + CloseableIteration> iter; if (parsedQuery instanceof ParsedBooleanQuery) { ParsedBooleanQuery askQuery = (ParsedBooleanQuery) parsedQuery; BooleanQuery queryOp = qp.prepare(askQuery); diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SpinTupleFunctionAsFunctionParser.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SpinTupleFunctionAsFunctionParser.java index a74b758520b..1845d208d90 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SpinTupleFunctionAsFunctionParser.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/SpinTupleFunctionAsFunctionParser.java @@ -59,7 +59,7 @@ public String getURI() { @Override public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { try { - try (CloseableIteration, QueryEvaluationException> iter = tupleFunc + try (CloseableIteration> iter = tupleFunc .evaluate(valueFactory, args)) { if (iter.hasNext()) { return iter.next().get(0); diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/apf/ConcatTupleFunction.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/apf/ConcatTupleFunction.java index dd48a846704..fac241fbf80 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/apf/ConcatTupleFunction.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/apf/ConcatTupleFunction.java @@ -31,10 +31,10 @@ public String getURI() { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( ValueFactory valueFactory, Value... args) throws QueryEvaluationException { Literal result = new Concat().evaluate(valueFactory, args); - return new SingletonIteration, QueryEvaluationException>( + return new SingletonIteration>( Collections.singletonList(result)); } } diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Index.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Index.java index 5e6a12bea77..02774198460 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Index.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Index.java @@ -30,7 +30,7 @@ public String getURI() { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( final ValueFactory valueFactory, final Value... args) throws QueryEvaluationException { return new CloseableIteratorIteration<>( new Iterator>() { diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Length.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Length.java index 6c9f898b63b..1ca9c9ee88d 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Length.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Length.java @@ -29,9 +29,9 @@ public String getURI() { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( final ValueFactory valueFactory, final Value... args) throws QueryEvaluationException { - return new SingletonIteration, QueryEvaluationException>( + return new SingletonIteration>( Collections.singletonList(valueFactory.createLiteral(args.length))); } } diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Member.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Member.java index 11fb86a6179..c6e9b269df7 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Member.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/list/Member.java @@ -28,7 +28,7 @@ public String getURI() { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( ValueFactory valueFactory, Value... args) throws QueryEvaluationException { return new ForEach().evaluate(valueFactory, args); } diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/For.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/For.java index 0b443757e09..4dca432413d 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/For.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/For.java @@ -31,7 +31,7 @@ public String getURI() { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( final ValueFactory valueFactory, Value... args) throws QueryEvaluationException { if (args.length != 2) { throw new ValueExprEvaluationException( diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/ForEach.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/ForEach.java index b4494b8a5e5..b8591701ce9 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/ForEach.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/ForEach.java @@ -29,7 +29,7 @@ public String getURI() { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( ValueFactory valueFactory, Value... args) throws QueryEvaluationException { return new CloseableIteratorIteration<>( SingleValueToListTransformer.transform(Arrays.asList(args).iterator())); diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/HasAllObjects.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/HasAllObjects.java index d574c420b50..bb88f3a7bab 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/HasAllObjects.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/HasAllObjects.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.rdf4j.spin.function.spif; -import org.eclipse.rdf4j.common.iteration.Iteration; +import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; @@ -41,7 +41,7 @@ public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExpr IRI pred = (IRI) args[1]; Resource list = (Resource) args[2]; try { - Iteration iter = TripleSources.list(list, qp.getTripleSource()); + CloseableIteration iter = TripleSources.list(list, qp.getTripleSource()); while (iter.hasNext()) { Value obj = iter.next(); if (TripleSources.single(subj, pred, obj, qp.getTripleSource()) == null) { diff --git a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/Split.java b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/Split.java index 737e47e0e10..a7bcf233050 100644 --- a/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/Split.java +++ b/core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/Split.java @@ -31,7 +31,7 @@ public String getURI() { } @Override - public CloseableIteration, QueryEvaluationException> evaluate( + public CloseableIteration> evaluate( final ValueFactory valueFactory, Value... args) throws QueryEvaluationException { if (args.length != 2) { throw new ValueExprEvaluationException( diff --git a/core/spin/src/test/java/org/eclipse/rdf4j/model/evaluation/ModelTripleSource.java b/core/spin/src/test/java/org/eclipse/rdf4j/model/evaluation/ModelTripleSource.java index 52144eb7a06..5906f14a5d0 100644 --- a/core/spin/src/test/java/org/eclipse/rdf4j/model/evaluation/ModelTripleSource.java +++ b/core/spin/src/test/java/org/eclipse/rdf4j/model/evaluation/ModelTripleSource.java @@ -31,7 +31,7 @@ public ModelTripleSource(Model m) { } @Override - public CloseableIteration getStatements(Resource subj, IRI pred, + public CloseableIteration getStatements(Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { return new CloseableIteratorIteration<>(model.getStatements(subj, pred, obj, contexts).iterator()); } diff --git a/pom.xml b/pom.xml index e0c5db19f68..a8de117eafd 100644 --- a/pom.xml +++ b/pom.xml @@ -368,7 +368,7 @@ 2.13.5 4.4.16 0.13.4 - 4.0.0 + 5.0.0 2.3.8 3.3.3 8.9.0 @@ -620,11 +620,6 @@ - - org.mapdb - mapdb - 1.0.9 - @@ -1060,6 +1055,10 @@ org.apache.maven.plugins maven-enforcer-plugin + + com.github.siom79.japicmp + japicmp-maven-plugin + diff --git a/site/content/release-notes/5.0.0.md b/site/content/release-notes/5.0.0.md new file mode 100644 index 00000000000..199d8dc735a --- /dev/null +++ b/site/content/release-notes/5.0.0.md @@ -0,0 +1,25 @@ +--- +title: "5.0.0" +toc: true +--- +RDF4J 5.0.0 is a major release of the Eclipse RDF4J framework. Some highlights: + +- Replacement of the custom Iteration interface with Java Iterable/Iterator +- Upgrade of MapDB +- Replacement of old openrdf.org config vocabulary IRIS with new rdf4j.org vocabulary + +For a complete overview, see [all issues fixed in 5.0.0](https://github.com/eclipse/rdf4j/milestone/80?closed=1). + +## Upgrade notes + +RDF4J 5.0.0 contains several [backward incompatible +changes](https://github.com/eclipse/rdf4j/issues?q=is%3Aclosed+is%3Aissue+label%3A%22%E2%9B%94+Not+backwards+compatible%22+milestone%3A%225.0.0%22), including removal of several deprecated modules and classes. + +### Configuration vocabulary upgrade + +The repository configuration vocabulary has been refactored and simplified, using the `tag:rdf4j.org,2023:config/` namespace (see [GH-4401](https://github.com/eclipse-rdf4j/rdf4j/issues/4401)). All existing configurations with legacy vocabulary will remain readable, and when using `LocalRepositoryManager` to manage configurations they will be automatically converted to the new vocabulary. RDF4J Server, Workbench, and Console will also automatically convert all repository configurations to the new vocabulary. + +If you are manually querying configuration data, you will need to update your queries to use the new vocabulary IRIs. The legacy IRI classes have all been annotated with references to relevant the replacement IRI, and a full overview of all new vocabulary can be found in the [CONFIG javadoc](/javadoc/latest/org/eclipse/rdf4j/model/vocabulary/CONFIG.html). + +If you wish to force RDF4J to stick to the legacy vocabulary for now, this is possible by setting the system property `org.eclipse.rdf4j.model.vocabulary.useLegacyConfig` to `true`. + diff --git a/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/operationlog/LoggingRepositoryConnection.java b/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/operationlog/LoggingRepositoryConnection.java index 61f9da953f8..eedd29fc5e1 100644 --- a/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/operationlog/LoggingRepositoryConnection.java +++ b/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/operationlog/LoggingRepositoryConnection.java @@ -18,7 +18,7 @@ import java.lang.invoke.MethodHandles; import java.net.URL; -import org.eclipse.rdf4j.common.iteration.Iteration; +import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; @@ -148,9 +148,9 @@ public void add(Iterable statements, Resource... contexts) } @Override - public void add( - Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void add( + CloseableIteration statementIter, Resource... contexts) + throws RepositoryException { operationLog.runWithLog( PseudoOperation.forAdd(statementIter, contexts), wrapInRuntimeException(() -> getDelegate().add(statementIter, contexts))); @@ -205,9 +205,9 @@ public void remove(Iterable statements, Resource... context } @Override - public void remove( - Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void remove( + CloseableIteration statementIter, Resource... contexts) + throws RepositoryException { operationLog.runWithLog( PseudoOperation.forRemove(statementIter, contexts), wrapInRuntimeException(() -> getDelegate().remove(statementIter, contexts))); diff --git a/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/resultcache/CachingRepositoryConnection.java b/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/resultcache/CachingRepositoryConnection.java index 61a422c516f..fc160629643 100644 --- a/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/resultcache/CachingRepositoryConnection.java +++ b/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/resultcache/CachingRepositoryConnection.java @@ -17,7 +17,7 @@ import java.io.Reader; import java.net.URL; -import org.eclipse.rdf4j.common.iteration.Iteration; +import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; @@ -152,9 +152,9 @@ public void add(Iterable statements, Resource... contexts) } @Override - public void add( - Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void add( + CloseableIteration statementIter, Resource... contexts) + throws RepositoryException { super.add(statementIter, contexts); markDirty(); } @@ -200,9 +200,9 @@ public void remove(Iterable statements, Resource... context } @Override - public void remove( - Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void remove( + CloseableIteration statementIter, Resource... contexts) + throws RepositoryException { super.remove(statementIter, contexts); markDirty(); } diff --git a/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/tx/TransactionalRepositoryConnection.java b/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/tx/TransactionalRepositoryConnection.java index 3045ccd64d4..1f40cb7e0a8 100644 --- a/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/tx/TransactionalRepositoryConnection.java +++ b/spring-components/rdf4j-spring/src/main/java/org/eclipse/rdf4j/spring/tx/TransactionalRepositoryConnection.java @@ -17,7 +17,7 @@ import java.io.Reader; import java.net.URL; -import org.eclipse.rdf4j.common.iteration.Iteration; +import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; @@ -84,9 +84,9 @@ public void add(Iterable statements, Resource... contexts) } @Override - public void add( - Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void add( + CloseableIteration statementIter, Resource... contexts) + throws RepositoryException { throwExceptionIfReadonly(); super.add(statementIter, contexts); } @@ -132,9 +132,9 @@ public void remove(Iterable statements, Resource... context } @Override - public void remove( - Iteration statementIter, Resource... contexts) - throws RepositoryException, E { + public void remove( + CloseableIteration statementIter, Resource... contexts) + throws RepositoryException { throwExceptionIfReadonly(); super.remove(statementIter, contexts); } diff --git a/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/QueryResponder.java b/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/QueryResponder.java index 909c22151cf..574382c544b 100644 --- a/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/QueryResponder.java +++ b/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/QueryResponder.java @@ -32,6 +32,9 @@ @Experimental @RestController public class QueryResponder { + + private static final String[] ALL_GRAPHS = {}; + /** * The repository that is being served. */ @@ -54,7 +57,7 @@ public void sparqlPostURLencoded( HttpServletRequest request, HttpServletResponse response) throws IOException { try { EvaluateResultHttpResponse result = new EvaluateResultHttpResponse(response); - sparqlQueryEvaluator.evaluate(result, repository, query, acceptHeader, defaultGraphUri, + sparqlQueryEvaluator.evaluate(result, repository, query, acceptHeader, toArray(defaultGraphUri), toArray(namedGraphUri)); } catch (MalformedQueryException | IllegalStateException | IOException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); @@ -69,7 +72,7 @@ public void sparqlGet(@RequestParam(value = "default-graph-uri", required = fals try { EvaluateResultHttpResponse result = new EvaluateResultHttpResponse(response); - sparqlQueryEvaluator.evaluate(result, repository, query, acceptHeader, defaultGraphUri, + sparqlQueryEvaluator.evaluate(result, repository, query, acceptHeader, toArray(defaultGraphUri), toArray(namedGraphUri)); } catch (MalformedQueryException | IllegalStateException | IOException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); @@ -77,10 +80,9 @@ public void sparqlGet(@RequestParam(value = "default-graph-uri", required = fals } private String[] toArray(String namedGraphUri) { - String[] namedGraphUris = new String[] {}; if (namedGraphUri != null) { - namedGraphUris = new String[] { namedGraphUri }; + return new String[] { namedGraphUri }; } - return namedGraphUris; + return ALL_GRAPHS; } } diff --git a/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluator.java b/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluator.java index 50bccce3206..73a03f1f862 100644 --- a/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluator.java +++ b/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluator.java @@ -24,13 +24,14 @@ public interface SparqlQueryEvaluator { * @param repository the repository against which the query is to be executed * @param query The query to be evaluated * @param acceptHeader needed to find the best response format. - * @param defaultGraphUri see {@link Dataset#getDefaultGraphs()} - * @param namedGraphUris see {@link Dataset#getNamedGraphs()} + * @param defaultGraphUri The graphs that are embedded in the query with FROM {@link Dataset#getDefaultGraphs()} + * @param namedGraphUris The graphs that are embedded in the query with FROM NAMED see + * {@link Dataset#getNamedGraphs()} * @throws MalformedQueryException If the supplied query is malformed. * @throws IOException if there is a problem with the {@link EvaluateResult#getOutputstream()} * @throws IllegalStateException if no acceptHeader is present */ void evaluate(EvaluateResult result, Repository repository, String query, String acceptHeader, - String defaultGraphUri, + String[] defaultGraphUri, String[] namedGraphUris) throws MalformedQueryException, IllegalStateException, IOException; } diff --git a/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluatorDefault.java b/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluatorDefault.java index 19706c257e0..7e5c74c3593 100644 --- a/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluatorDefault.java +++ b/spring-components/spring-boot-sparql-web/src/main/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluatorDefault.java @@ -13,7 +13,7 @@ import java.io.IOException; import java.util.Arrays; -import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.query.MalformedQueryException; import org.eclipse.rdf4j.query.Query; @@ -28,7 +28,7 @@ class SparqlQueryEvaluatorDefault implements SparqlQueryEvaluator { @Override public void evaluate(EvaluateResult result, Repository repository, String query, - String acceptHeader, String defaultGraphUri, String[] namedGraphUris) + String acceptHeader, String[] defaultGraphUri, String[] namedGraphUris) throws MalformedQueryException, IOException, IllegalStateException { try (RepositoryConnection connection = repository.getConnection()) { Query preparedQuery = connection.prepareQuery(QueryLanguage.SPARQL, query); @@ -42,24 +42,27 @@ public void evaluate(EvaluateResult result, Repository repository, String query, } /** - * @param q the query * @param defaultGraphUri * @param namedGraphUris * @param connection * @see protocol dataset */ - private Dataset getQueryDataSet(String defaultGraphUri, String[] namedGraphUris, RepositoryConnection connection) { + private Dataset getQueryDataSet(String[] defaultGraphUri, String[] namedGraphUris, + RepositoryConnection connection) { SimpleDataset dataset = new SimpleDataset(); + ValueFactory valueFactory = connection.getValueFactory(); if (defaultGraphUri != null) { - IRI defaultIri = connection.getValueFactory().createIRI(defaultGraphUri); - dataset.addDefaultGraph(defaultIri); + Arrays.stream(defaultGraphUri) + .map(valueFactory::createIRI) + .forEach(dataset::addDefaultGraph); } - Arrays.stream(namedGraphUris).forEach(namedGraphUri -> { - IRI namedIri = connection.getValueFactory().createIRI(namedGraphUri); - dataset.addNamedGraph(namedIri); - }); + if (namedGraphUris != null) { + Arrays.stream(namedGraphUris) + .map(valueFactory::createIRI) + .forEach(dataset::addNamedGraph); + } return dataset; } } diff --git a/spring-components/spring-boot-sparql-web/src/test/java/org/eclipse/rdf4j/http/server/readonly/sparql/EvaluateResultDefault.java b/spring-components/spring-boot-sparql-web/src/test/java/org/eclipse/rdf4j/http/server/readonly/sparql/EvaluateResultDefault.java new file mode 100644 index 00000000000..6ecad6e19e1 --- /dev/null +++ b/spring-components/spring-boot-sparql-web/src/test/java/org/eclipse/rdf4j/http/server/readonly/sparql/EvaluateResultDefault.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.http.server.readonly.sparql; + +import java.io.OutputStream; + +public class EvaluateResultDefault implements EvaluateResult { + private String contentType; + + private OutputStream outputstream; + + public EvaluateResultDefault(OutputStream outputstream) { + this.outputstream = outputstream; + } + + @Override + public String getContentType() { + return contentType; + } + + @Override + public void setContentType(String contentType) { + this.contentType = contentType; + } + + @Override + public OutputStream getOutputstream() { + return outputstream; + } + + public void setOutputstream(OutputStream outputstream) { + this.outputstream = outputstream; + } +} diff --git a/spring-components/spring-boot-sparql-web/src/test/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluatorDefaultTest.java b/spring-components/spring-boot-sparql-web/src/test/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluatorDefaultTest.java new file mode 100644 index 00000000000..5ef6901a70f --- /dev/null +++ b/spring-components/spring-boot-sparql-web/src/test/java/org/eclipse/rdf4j/http/server/readonly/sparql/SparqlQueryEvaluatorDefaultTest.java @@ -0,0 +1,175 @@ +/******************************************************************************* + * Copyright (c) 2023 Eclipse RDF4J contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.http.server.readonly.sparql; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Literal; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.util.ModelBuilder; +import org.eclipse.rdf4j.model.util.Values; +import org.eclipse.rdf4j.query.MalformedQueryException; +import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; +import org.eclipse.rdf4j.repository.sail.SailRepository; +import org.eclipse.rdf4j.sail.memory.MemoryStore; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; + +public class SparqlQueryEvaluatorDefaultTest { + + private static final IRI CTX1 = Values.iri("http://example.com/ctx1"); + + private static final IRI CTX2 = Values.iri("http://example.com/ctx2"); + + private static final IRI TYP1 = Values.iri("http://example.com/typ1"); + + private static final IRI TYP2 = Values.iri("http://example.com/typ2"); + + @Test + public void queryWithoutContext() throws MalformedQueryException, IllegalStateException, IOException { + Repository repo = new SailRepository(new MemoryStore()); + try (RepositoryConnection con = repo.getConnection()) { + con.add(getTestModel1(), CTX1); + con.add(getTestModel2(), CTX2); + con.getStatements(null, null, null).forEach(System.out::println); + } + + EvaluateResult evaluateResult = new EvaluateResultDefault(new ByteArrayOutputStream()); + SparqlQueryEvaluator sparqlQueryEvaluator = new SparqlQueryEvaluatorDefault(); + + String queryString = "SELECT ?subject ?predicate ?object WHERE { ?subject ?predicate ?object} "; + String[] namedGraphUris = null;// new String[] {}; + + String[] defaultGraphUri = null;// new String[] {}; + + sparqlQueryEvaluator.evaluate(evaluateResult, repo, queryString, null, + defaultGraphUri, namedGraphUris); + + ArrayNode bindingArray = asArrayNode(evaluateResult); + assertEquals(4, bindingArray.size()); + } + + @Test + public void queryWithDefaultGraphUri() throws MalformedQueryException, IllegalStateException, IOException { + Repository repo = new SailRepository(new MemoryStore()); + try (RepositoryConnection con = repo.getConnection()) { + con.add(getTestModel1(), CTX1); + con.add(getTestModel2(), CTX1); + con.getStatements(null, null, null).forEach(System.out::println); + } + + EvaluateResult evaluateResult = new EvaluateResultDefault(new ByteArrayOutputStream()); + SparqlQueryEvaluator sparqlQueryEvaluator = new SparqlQueryEvaluatorDefault(); + + String queryString = "SELECT ?subject ?predicate ?object WHERE { ?subject ?predicate ?object} "; + String[] namedGraphUris = new String[] {}; + String[] defaultGraphUri = new String[] { CTX1.stringValue() }; + + sparqlQueryEvaluator.evaluate(evaluateResult, repo, queryString, null, + defaultGraphUri, namedGraphUris); + + ArrayNode bindingArray = asArrayNode(evaluateResult); + assertEquals(4, bindingArray.size()); + } + + @Test + public void queryWithDefaultGraphUriAndNamedGraphUris() + throws MalformedQueryException, IllegalStateException, IOException { + Repository repo = new SailRepository(new MemoryStore()); + try (RepositoryConnection con = repo.getConnection()) { + con.add(getTestModel1(), CTX1); + con.add(getTestModel2(), CTX2); + con.getStatements(null, null, null).forEach(System.out::println); + } + + EvaluateResult evaluateResult = new EvaluateResultDefault(new ByteArrayOutputStream()); + SparqlQueryEvaluator sparqlQueryEvaluator = new SparqlQueryEvaluatorDefault(); + + String queryString = "SELECT ?subject ?predicate ?object WHERE { ?subject ?predicate ?object} "; + String[] namedGraphUris = new String[] { CTX2.stringValue() }; + String[] defaultGraphUri = new String[] { CTX1.stringValue() }; + + sparqlQueryEvaluator.evaluate(evaluateResult, repo, queryString, null, + defaultGraphUri, namedGraphUris); + + ArrayNode bindingArray = asArrayNode(evaluateResult); + assertEquals(2, bindingArray.size()); + } + + @Test + public void queryWithNamedGraphUris() throws MalformedQueryException, IllegalStateException, IOException { + Repository repo = new SailRepository(new MemoryStore()); + try (RepositoryConnection con = repo.getConnection()) { + con.add(getTestModel1(), CTX1); + con.add(getTestModel2(), CTX2); + con.getStatements(null, null, null).forEach(System.out::println); + } + + EvaluateResult evaluateResult = new EvaluateResultDefault(new ByteArrayOutputStream()); + SparqlQueryEvaluator sparqlQueryEvaluator = new SparqlQueryEvaluatorDefault(); + + String queryString = "SELECT ?subject ?predicate ?object WHERE { ?subject ?predicate ?object} "; + String[] namedGraphUris = new String[] {}; + String[] defaultGraphUri = new String[] { CTX1.stringValue(), CTX2.stringValue() }; + + sparqlQueryEvaluator.evaluate(evaluateResult, repo, queryString, null, + defaultGraphUri, namedGraphUris); + + ArrayNode bindingArray = asArrayNode(evaluateResult); + assertEquals(4, bindingArray.size()); + } + + private Model getTestModel1() { + Literal obj1_1 = Values.literal("testValue_user1_obj1_1"); + Literal obj1_2 = Values.literal("testValue_user1_obj1_2"); + IRI obj1 = Values.iri("http://example.com/user1/object1"); + Model model = new ModelBuilder() + .subject(obj1) + .add(TYP1, obj1_1) + .add(TYP2, obj1_2) + .build(); + return model; + } + + private Model getTestModel2() { + Literal obj2_1 = Values.literal("testValue_user1_obj2_1"); + Literal obj2_2 = Values.literal("testValue_user1_obj2_2"); + IRI obj2 = Values.iri("http://example.com/user1/object2"); + + Model model = new ModelBuilder() + .subject(obj2) + .add(TYP1, obj2_1) + .add(TYP2, obj2_2) + .build(); + return model; + } + + private ArrayNode asArrayNode(EvaluateResult evaluateResult) + throws IOException, JsonProcessingException, JsonMappingException { + ByteArrayOutputStream stream = (ByteArrayOutputStream) evaluateResult.getOutputstream(); + String evaluateResultString = new String(stream.toByteArray()); + System.out.println(evaluateResultString); + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(evaluateResultString); + ArrayNode bindingArray = (ArrayNode) root.get("results").get("bindings"); + return bindingArray; + } +} diff --git a/testsuites/benchmark/src/main/java/org/eclipse/rdf4j/benchmark/QueryOrderBenchmark.java b/testsuites/benchmark/src/main/java/org/eclipse/rdf4j/benchmark/QueryOrderBenchmark.java index 3f8343846a6..722443eace9 100644 --- a/testsuites/benchmark/src/main/java/org/eclipse/rdf4j/benchmark/QueryOrderBenchmark.java +++ b/testsuites/benchmark/src/main/java/org/eclipse/rdf4j/benchmark/QueryOrderBenchmark.java @@ -73,7 +73,7 @@ public class QueryOrderBenchmark { public int syncThreshold = 10; @Setup - public void setup() throws Exception { + public void setup() { dataDir = Files.newTemporaryFolder(); NativeStore sail = new NativeStore(dataDir, "spoc,posc"); sail.setIterationCacheSyncThreshold(syncThreshold); @@ -105,7 +105,7 @@ public void tearDown() throws Exception { } @Benchmark - public void selectAll() throws Exception { + public void selectAll() { StringBuilder rq = new StringBuilder("SELECT * { ?s ?p ?o } ORDER BY ?o"); if (limit > 0) { rq = rq.append(" LIMIT ").append(limit); @@ -130,7 +130,7 @@ public void selectAll() throws Exception { } @Benchmark - public void selectDistinct() throws Exception { + public void selectDistinct() { StringBuilder rq = new StringBuilder("SELECT DISTINCT ?s ?o { ?s ?p ?o } ORDER BY ?o"); if (limit > 0) { rq = rq.append(" LIMIT ").append(limit); diff --git a/testsuites/benchmark/src/main/java/org/eclipse/rdf4j/benchmark/rio/WriterBenchmark.java b/testsuites/benchmark/src/main/java/org/eclipse/rdf4j/benchmark/rio/WriterBenchmark.java index f0adab9f1cf..c8960ec1836 100644 --- a/testsuites/benchmark/src/main/java/org/eclipse/rdf4j/benchmark/rio/WriterBenchmark.java +++ b/testsuites/benchmark/src/main/java/org/eclipse/rdf4j/benchmark/rio/WriterBenchmark.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.benchmark.rio; -import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.TimeUnit; @@ -73,7 +72,7 @@ public class WriterBenchmark { private Model model; @Setup(Level.Trial) - public void setup() throws IOException { + public void setup() { writerFormat = Rio.getWriterFormatForFileName("dummy." + format).orElseThrow(); model = new LinkedHashModel(); diff --git a/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailGeoSPARQLTest.java b/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailGeoSPARQLTest.java index 76574eea806..3f789d27362 100644 --- a/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailGeoSPARQLTest.java +++ b/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailGeoSPARQLTest.java @@ -86,10 +86,10 @@ public abstract class AbstractLuceneSailGeoSPARQLTest { protected Repository repository; - protected abstract void configure(LuceneSail sail) throws IOException; + protected abstract void configure(LuceneSail sail); @Before - public void setUp() throws Exception { + public void setUp() { // setup a LuceneSail MemoryStore memoryStore = new MemoryStore(); // enable lock tracking @@ -131,7 +131,7 @@ public void tearDown() throws IOException, RepositoryException { } @Test - public void testTriplesStored() throws Exception { + public void testTriplesStored() { // are the triples stored in the underlying sail? checkPoints(); checkPolygons(); diff --git a/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailIndexedPropertiesTest.java b/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailIndexedPropertiesTest.java index 2b4c9f30c4e..9c80c2f13e1 100644 --- a/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailIndexedPropertiesTest.java +++ b/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailIndexedPropertiesTest.java @@ -127,7 +127,7 @@ public void tearDown() throws IOException, RepositoryException { } @Test - public void testTriplesStored() throws Exception { + public void testTriplesStored() { // are the triples stored in the underlying sail? try (RepositoryConnection connection = repository.getConnection()) { assertTrue(connection.hasStatement(SUBJECT_1, RDFSLABEL, vf.createLiteral("the first resource"), false)); diff --git a/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailTest.java b/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailTest.java index 3f0a3220230..d17d17b353a 100644 --- a/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailTest.java +++ b/testsuites/lucene/src/main/java/org/eclipse/testsuite/rdf4j/sail/lucene/AbstractLuceneSailTest.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -106,10 +105,10 @@ public abstract class AbstractLuceneSailTest { QUERY_STRING = buffer.toString(); } - protected abstract void configure(LuceneSail sail) throws IOException; + protected abstract void configure(LuceneSail sail); @BeforeEach - public void setUp() throws Exception { + public void setUp() { // set logging, uncomment this to get better logging for debugging // org.apache.log4j.BasicConfigurator.configure(); @@ -141,7 +140,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws IOException, RepositoryException { + public void tearDown() throws RepositoryException { if (repository != null) { repository.shutDown(); } @@ -149,7 +148,7 @@ public void tearDown() throws IOException, RepositoryException { } @Test - public void testTriplesStored() throws Exception { + public void testTriplesStored() { try (RepositoryConnection connection = repository.getConnection()) { // are the triples stored in the underlying sail? assertTrue(connection.hasStatement(SUBJECT_1, PREDICATE_1, vf.createLiteral("one"), false)); @@ -847,7 +846,7 @@ public void testUnionQuery() throws RepositoryException, MalformedQueryException } @Test - public void testContextHandling() throws Exception { + public void testContextHandling() { try (RepositoryConnection connection = repository.getConnection()) { connection.begin(); connection.add(SUBJECT_4, PREDICATE_1, vf.createLiteral("sfourponecone"), CONTEXT_1); @@ -879,7 +878,7 @@ public void testContextHandling() throws Exception { } @Test - public void testConcurrentReadingAndWriting() throws Exception { + public void testConcurrentReadingAndWriting() { try (RepositoryConnection connection = repository.getConnection()) { connection.begin(); @@ -929,10 +928,9 @@ public void testConcurrentReadingAndWriting() throws Exception { /** * we experienced problems with the NULL context and lucenesail in August 2008 * - * @throws Exception */ @Test - public void testNullContextHandling() throws Exception { + public void testNullContextHandling() { try (RepositoryConnection connection = repository.getConnection()) { connection.add(SUBJECT_4, PREDICATE_1, vf.createLiteral("sfourponecone")); connection.add(SUBJECT_4, PREDICATE_2, vf.createLiteral("sfourptwocone")); @@ -1006,7 +1004,7 @@ public void testFuzzyQuery() throws MalformedQueryException, RepositoryException } @Test - public void testReindexing() throws Exception { + public void testReindexing() { sail.reindex(); testComplexQueryTwo(); } @@ -1083,7 +1081,7 @@ public void run() { assertEquals(0, exceptions.size(), "Exceptions occurred during testMultithreadedAdd, see stacktraces above"); } - protected void assertQueryResult(String literal, IRI predicate, Resource resultUri) throws Exception { + protected void assertQueryResult(String literal, IRI predicate, Resource resultUri) { try (RepositoryConnection connection = repository.getConnection()) { // fire a query for all subjects with a given term String queryString = "SELECT ?Resource WHERE { ?Resource <" + MATCHES + "> [ " + " <" + QUERY + "> \"" @@ -1101,7 +1099,7 @@ protected void assertQueryResult(String literal, IRI predicate, Resource resultU } } - protected void assertNoQueryResult(String literal) throws Exception { + protected void assertNoQueryResult(String literal) { try (RepositoryConnection connection = repository.getConnection()) { // fire a query for all subjects with a given term String queryString = "SELECT ?Resource WHERE { ?Resource <" + MATCHES + "> [ " + " <" + QUERY + "> \"" diff --git a/testsuites/model/src/main/java/org/eclipse/rdf4j/testsuite/model/ModelNamespacesTest.java b/testsuites/model/src/main/java/org/eclipse/rdf4j/testsuite/model/ModelNamespacesTest.java index 9a92591fa5c..dc23ac8fbe3 100644 --- a/testsuites/model/src/main/java/org/eclipse/rdf4j/testsuite/model/ModelNamespacesTest.java +++ b/testsuites/model/src/main/java/org/eclipse/rdf4j/testsuite/model/ModelNamespacesTest.java @@ -48,10 +48,9 @@ public abstract class ModelNamespacesTest { protected abstract Model getModelImplementation(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { testModel = getModelImplementation(); } diff --git a/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOBooleanTest.java b/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOBooleanTest.java index b4b038ffab1..53fd1abb752 100644 --- a/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOBooleanTest.java +++ b/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOBooleanTest.java @@ -100,7 +100,7 @@ public final void testMultipleResultsAndStylesheet() throws Exception { } @Test - public final void testInvalidBooleanAfterStartQueryResult() throws Exception { + public final void testInvalidBooleanAfterStartQueryResult() { doInvalidBooleanAfterStartQueryResult(getBooleanFormat(), true, Arrays.asList("info", "alternate", "other", "another")); doInvalidBooleanAfterStartQueryResult(getBooleanFormat(), false, diff --git a/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOTest.java b/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOTest.java index 83b96ade612..120c21c916b 100644 --- a/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOTest.java +++ b/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOTest.java @@ -20,7 +20,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; @@ -103,7 +102,7 @@ protected TupleQueryResult parseTupleInternal(TupleQueryResultFormat format, Inp * {@link org.eclipse.rdf4j.query.resultio.QueryResultIO#getParserFormatForFileName(java.lang.String)} . */ @Test - public final void testGetParserFormatForFileNameString() throws Exception { + public final void testGetParserFormatForFileNameString() { String fileName = getFileName(); Optional format; @@ -446,14 +445,13 @@ protected void doTupleLinksAndStylesheetMultipleEndHeaders(TupleQueryResultForma } protected void assertQueryResultsEqual(TupleQueryResult expected, TupleQueryResult output) - throws QueryEvaluationException, TupleQueryResultHandlerException, QueryResultHandlerException, - UnsupportedEncodingException { + throws QueryEvaluationException, TupleQueryResultHandlerException, QueryResultHandlerException { assertTrue(QueryResults.equals(expected, output)); } protected void doTupleMissingStartQueryResult(TupleQueryResultFormat format, TupleQueryResult input, TupleQueryResult expected, List links, String stylesheetUrl) throws QueryResultHandlerException, - QueryEvaluationException, QueryResultParseException, UnsupportedQueryResultFormatException, IOException { + QueryEvaluationException, QueryResultParseException, UnsupportedQueryResultFormatException { ByteArrayOutputStream out = new ByteArrayOutputStream(4096); TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out); // Test for handling when startDocument and startHeader are not called @@ -568,7 +566,7 @@ protected void doBooleanLinksOnly(BooleanQueryResultFormat format, boolean input } protected void doInvalidBooleanAfterStartQueryResult(BooleanQueryResultFormat format, boolean input, - List links) throws IOException, QueryResultHandlerException, QueryResultParseException, + List links) throws QueryResultHandlerException, QueryResultParseException, UnsupportedQueryResultFormatException, QueryEvaluationException { ByteArrayOutputStream out = new ByteArrayOutputStream(4096); BooleanQueryResultWriter writer = QueryResultIO.createBooleanWriter(format, out); diff --git a/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOTupleTest.java b/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOTupleTest.java index 310ffd454f5..39410cfaf59 100644 --- a/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOTupleTest.java +++ b/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractQueryResultIOTupleTest.java @@ -193,13 +193,13 @@ public final void testNoResultsJSONPCallback() throws Exception { } @Test - public final void testNoResultsExceptionHandleSolutionBeforeStartQueryResult() throws Exception { + public final void testNoResultsExceptionHandleSolutionBeforeStartQueryResult() { doTupleMissingStartQueryResult(getTupleFormat(), createTupleNoBindingSets(), createTupleNoBindingSets(), Arrays.asList("info", "alternate", "other", "another"), "test.xsl"); } @Test - public final void testMultipleExceptionHandleSolutionBeforeStartQueryResult() throws Exception { + public final void testMultipleExceptionHandleSolutionBeforeStartQueryResult() { doTupleMissingStartQueryResult(getTupleFormat(), createTupleMultipleBindingSets(), createTupleMultipleBindingSets(), Arrays.asList("info", "alternate", "other", "another"), "test.xsl"); } diff --git a/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractTupleQueryResultWriterTest.java b/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractTupleQueryResultWriterTest.java index ee643950a1d..c41821266c6 100644 --- a/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractTupleQueryResultWriterTest.java +++ b/testsuites/queryresultio/src/main/java/org/eclipse/rdf4j/testsuite/query/resultio/AbstractTupleQueryResultWriterTest.java @@ -146,7 +146,7 @@ public void testRDFStarHandling_DeepNesting() throws Exception { } @Test - public void testGetSupportedSettings() throws Exception { + public void testGetSupportedSettings() { TupleQueryResultWriter writer = getWriterFactory().getWriter(System.out); Collection> supportedSettings = writer.getSupportedSettings(); diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/CascadeValueExceptionTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/CascadeValueExceptionTest.java index 7ac1a55a07c..12e0ecba6dd 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/CascadeValueExceptionTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/CascadeValueExceptionTest.java @@ -27,12 +27,12 @@ public abstract class CascadeValueExceptionTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterAll - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -65,7 +65,7 @@ public static void afterClass() throws Exception { private Repository repository; @Test - public void testValueExceptionLessThanPlain() throws Exception { + public void testValueExceptionLessThanPlain() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrLT); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -73,7 +73,7 @@ public void testValueExceptionLessThanPlain() throws Exception { } @Test - public void testValueExceptionLessThanOrEqualPlain() throws Exception { + public void testValueExceptionLessThanOrEqualPlain() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrLE); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -81,7 +81,7 @@ public void testValueExceptionLessThanOrEqualPlain() throws Exception { } @Test - public void testValueExceptionEqualPlain() throws Exception { + public void testValueExceptionEqualPlain() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrEQ); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -89,7 +89,7 @@ public void testValueExceptionEqualPlain() throws Exception { } @Test - public void testValueExceptionNotEqualPlain() throws Exception { + public void testValueExceptionNotEqualPlain() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrNE); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -97,7 +97,7 @@ public void testValueExceptionNotEqualPlain() throws Exception { } @Test - public void testValueExceptionGreaterThanOrEqualPlain() throws Exception { + public void testValueExceptionGreaterThanOrEqualPlain() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrGE); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -105,7 +105,7 @@ public void testValueExceptionGreaterThanOrEqualPlain() throws Exception { } @Test - public void testValueExceptionGreaterThanPlain() throws Exception { + public void testValueExceptionGreaterThanPlain() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrGT); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -113,7 +113,7 @@ public void testValueExceptionGreaterThanPlain() throws Exception { } @Test - public void testValueExceptionLessThanTyped() throws Exception { + public void testValueExceptionLessThanTyped() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrAltLT); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -121,7 +121,7 @@ public void testValueExceptionLessThanTyped() throws Exception { } @Test - public void testValueExceptionLessThanOrEqualTyped() throws Exception { + public void testValueExceptionLessThanOrEqualTyped() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrAltLE); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -129,7 +129,7 @@ public void testValueExceptionLessThanOrEqualTyped() throws Exception { } @Test - public void testValueExceptionEqualTyped() throws Exception { + public void testValueExceptionEqualTyped() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrAltEQ); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -137,7 +137,7 @@ public void testValueExceptionEqualTyped() throws Exception { } @Test - public void testValueExceptionNotEqualTyped() throws Exception { + public void testValueExceptionNotEqualTyped() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrAltNE); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -145,7 +145,7 @@ public void testValueExceptionNotEqualTyped() throws Exception { } @Test - public void testValueExceptionGreaterThanOrEqualTyped() throws Exception { + public void testValueExceptionGreaterThanOrEqualTyped() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrAltGE); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -153,7 +153,7 @@ public void testValueExceptionGreaterThanOrEqualTyped() throws Exception { } @Test - public void testValueExceptionGreaterThanTyped() throws Exception { + public void testValueExceptionGreaterThanTyped() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrAltGT); try (TupleQueryResult evaluate = query.evaluate()) { assertFalse(evaluate.hasNext()); @@ -161,13 +161,13 @@ public void testValueExceptionGreaterThanTyped() throws Exception { } @BeforeEach - public void setUp() throws Exception { + public void setUp() { repository = createRepository(); conn = repository.getConnection(); conn.add(RDF.NIL, RDF.TYPE, RDF.LIST); } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { con.clear(); @@ -176,10 +176,10 @@ protected Repository createRepository() throws Exception { return repository; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); @AfterEach - public void tearDown() throws Exception { + public void tearDown() { conn.close(); conn = null; diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/GraphQueryResultTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/GraphQueryResultTest.java index 7f3bc3929d9..ef8e44e9cfe 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/GraphQueryResultTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/GraphQueryResultTest.java @@ -38,7 +38,7 @@ public abstract class GraphQueryResultTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @@ -74,7 +74,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { try { con.close(); con = null; @@ -84,7 +84,7 @@ public void tearDown() throws Exception { } } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { @@ -97,7 +97,7 @@ protected Repository createRepository() throws Exception { return repository; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); /* * build some simple SPARQL queries to use for testing the result set object. @@ -123,7 +123,7 @@ private void addData() throws IOException, UnsupportedRDFormatException, RDFPars } @Test - public void testDescribeEmpty() throws Exception { + public void testDescribeEmpty() { GraphQueryResult result = con.prepareGraphQuery(QueryLanguage.SPARQL, emptyDescribeQuery).evaluate(); assertFalse(result.hasNext(), "Query result should be empty"); @@ -132,7 +132,7 @@ public void testDescribeEmpty() throws Exception { } @Test - public void testDescribeSingle() throws Exception { + public void testDescribeSingle() { GraphQueryResult result = con.prepareGraphQuery(QueryLanguage.SPARQL, singleDescribeQuery).evaluate(); assertTrue(result.hasNext(), "Query result should not be empty"); @@ -142,7 +142,7 @@ public void testDescribeSingle() throws Exception { } @Test - public void testDescribeMultiple() throws Exception { + public void testDescribeMultiple() { GraphQueryResult result = con.prepareGraphQuery(QueryLanguage.SPARQL, multipleDescribeQuery).evaluate(); assertTrue(result.hasNext(), "Query result should not be empty"); @@ -152,7 +152,7 @@ public void testDescribeMultiple() throws Exception { } @Test - public void testConstructEmpty() throws Exception { + public void testConstructEmpty() { GraphQueryResult result = con.prepareGraphQuery(QueryLanguage.SPARQL, emptyConstructQuery).evaluate(); assertFalse(result.hasNext(), "Query result should be empty"); @@ -161,7 +161,7 @@ public void testConstructEmpty() throws Exception { } @Test - public void testConstructSingle() throws Exception { + public void testConstructSingle() { GraphQueryResult result = con.prepareGraphQuery(QueryLanguage.SPARQL, singleConstructQuery).evaluate(); assertTrue(result.hasNext(), "Query result should not be empty"); @@ -171,7 +171,7 @@ public void testConstructSingle() throws Exception { } @Test - public void testConstructMultiple() throws Exception { + public void testConstructMultiple() { GraphQueryResult result = con.prepareGraphQuery(QueryLanguage.SPARQL, multipleConstructQuery).evaluate(); assertTrue(result.hasNext(), "Query result should not be empty"); diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/OptimisticIsolationTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/OptimisticIsolationTest.java index 65d858849dc..d749f8ad4d0 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/OptimisticIsolationTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/OptimisticIsolationTest.java @@ -49,7 +49,7 @@ public static void setUpClass() throws Exception { } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RDFSchemaRepositoryConnectionTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RDFSchemaRepositoryConnectionTest.java index 8a9991336d1..097315241c9 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RDFSchemaRepositoryConnectionTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RDFSchemaRepositoryConnectionTest.java @@ -52,7 +52,7 @@ protected void setupTest(IsolationLevel level) { @ParameterizedTest @MethodSource("parameters") - public void testDomainInference(IsolationLevel level) throws Exception { + public void testDomainInference(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -65,7 +65,7 @@ public void testDomainInference(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSubClassInference(IsolationLevel level) throws Exception { + public void testSubClassInference(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -82,7 +82,7 @@ public void testSubClassInference(IsolationLevel level) throws Exception { /** * See https://github.com/eclipse/rdf4j/issues/1685 */ - public void testSubClassInferenceAfterRemoval(IsolationLevel level) throws Exception { + public void testSubClassInferenceAfterRemoval(IsolationLevel level) { setupTest(level); IRI mother = vf.createIRI("http://example.org/Mother"); @@ -107,7 +107,7 @@ public void testSubClassInferenceAfterRemoval(IsolationLevel level) throws Excep @ParameterizedTest @MethodSource("parameters") - public void testMakeExplicit(IsolationLevel level) throws Exception { + public void testMakeExplicit(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -126,7 +126,7 @@ public void testMakeExplicit(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testExplicitFlag(IsolationLevel level) throws Exception { + public void testExplicitFlag(IsolationLevel level) { setupTest(level); RepositoryResult result = testCon.getStatements(RDF.TYPE, RDF.TYPE, null, true); @@ -146,7 +146,7 @@ public void testExplicitFlag(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testInferencerUpdates(IsolationLevel level) throws Exception { + public void testInferencerUpdates(IsolationLevel level) { setupTest(level); testCon.begin(IsolationLevels.READ_COMMITTED); @@ -161,7 +161,7 @@ public void testInferencerUpdates(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testInferencerQueryDuringTransaction(IsolationLevel level) throws Exception { + public void testInferencerQueryDuringTransaction(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -174,7 +174,7 @@ public void testInferencerQueryDuringTransaction(IsolationLevel level) throws Ex @ParameterizedTest @EnumSource(IsolationLevels.class) - public void testInferencerTransactionIsolation(IsolationLevel level) throws Exception { + public void testInferencerTransactionIsolation(IsolationLevel level) { setupTest(level); if (IsolationLevels.NONE.isCompatibleWith(level)) { @@ -194,7 +194,7 @@ public void testInferencerTransactionIsolation(IsolationLevel level) throws Exce @ParameterizedTest @MethodSource("parameters") - public void testContextStatementsNotDuplicated(IsolationLevel level) throws Exception { + public void testContextStatementsNotDuplicated(IsolationLevel level) { setupTest(level); testCon.add(bob, RDF.TYPE, FOAF.PERSON, RDF.FIRST); @@ -211,7 +211,7 @@ public void testContextStatementsNotDuplicated(IsolationLevel level) throws Exce @ParameterizedTest @MethodSource("parameters") - public void testContextStatementsNotDuplicated2(IsolationLevel level) throws Exception { + public void testContextStatementsNotDuplicated2(IsolationLevel level) { setupTest(level); testCon.add(FOAF.PERSON, RDF.TYPE, RDFS.CLASS, RDF.FIRST); diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RDFStarSupportTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RDFStarSupportTest.java index 03a7c6cfb8e..135b515045c 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RDFStarSupportTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RDFStarSupportTest.java @@ -66,7 +66,7 @@ public abstract class RDFStarSupportTest { private IRI context2; @BeforeEach - public void setUp() throws Exception { + public void setUp() { testRepository = createRepository(); testCon = testRepository.getConnection(); @@ -91,7 +91,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { try { testCon.close(); } finally { diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RepositoryConnectionTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RepositoryConnectionTest.java index 6feaef56b9e..a22e98b9f73 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RepositoryConnectionTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RepositoryConnectionTest.java @@ -98,7 +98,7 @@ @Timeout(value = 10, unit = TimeUnit.MINUTES) public abstract class RepositoryConnectionTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { // Turn off debugging for this test, as the cleanup processes are working correctly, // but they debug a lot of information in testOrderByQueriesAreInterrupable System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); @@ -109,8 +109,6 @@ public static IsolationLevel[] parameters() { return IsolationLevels.values(); } - private static final String URN_TEST_OTHER = "urn:test:other"; - private static final String SPARQL_DEL_ALL = "DELETE { ?s ?p ?o } WHERE { ?s ?p ?o }"; private static final String URN_TEST_O1 = "urn:test:o1"; @@ -231,7 +229,7 @@ protected void setupTest(IsolationLevel level) { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { try { testCon2.close(); } finally { @@ -279,7 +277,7 @@ public void testAddStatement(IsolationLevel level, @TempDir File dataDir) throws @ParameterizedTest @MethodSource("parameters") - public void testAddStatementWithContext(IsolationLevel level) throws Exception { + public void testAddStatementWithContext(IsolationLevel level) { setupTest(level); Statement statement = vf.createStatement(alice, name, nameAlice, context1); @@ -292,7 +290,7 @@ public void testAddStatementWithContext(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testAddLiteralWithNewline(IsolationLevel level) throws Exception { + public void testAddLiteralWithNewline(IsolationLevel level) { setupTest(level); Literal test = vf.createLiteral("this is a test\n"); @@ -303,7 +301,7 @@ public void testAddLiteralWithNewline(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testTransactionIsolation(IsolationLevel level) throws Exception { + public void testTransactionIsolation(IsolationLevel level) { setupTest(level); if (IsolationLevels.READ_UNCOMMITTED.isCompatibleWith(level)) { @@ -481,7 +479,7 @@ public void testAddMalformedLiteralsStrictConfig(IsolationLevel level) throws Ex @ParameterizedTest @MethodSource("parameters") - public void testAutoCommit(IsolationLevel level) throws Exception { + public void testAutoCommit(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -498,7 +496,7 @@ public void testAutoCommit(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testRollback(IsolationLevel level) throws Exception { + public void testRollback(IsolationLevel level) { setupTest(level); if (IsolationLevels.NONE.isCompatibleWith(level)) { @@ -518,7 +516,7 @@ public void testRollback(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSimpleTupleQuery(IsolationLevel level) throws Exception { + public void testSimpleTupleQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -527,14 +525,13 @@ public void testSimpleTupleQuery(IsolationLevel level) throws Exception { testCon.add(bob, name, nameBob, context1); testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); - StringBuilder queryBuilder = new StringBuilder(128); - queryBuilder.append(" PREFIX foaf: <" + FOAF_NS + "> \n"); - queryBuilder.append(" SELECT ?name ?mbox"); - queryBuilder.append(" WHERE { [] foaf:name ?name;"); - queryBuilder.append(" foaf:mbox ?mbox. }"); - - try (TupleQueryResult result = testCon.prepareTupleQuery(queryBuilder.toString()).evaluate()) { - assertThat(result).isNotNull(); + String queryBuilder = " PREFIX foaf: <" + FOAF_NS + "> \n" + + " SELECT ?name ?mbox" + + " WHERE { [] foaf:name ?name;" + + " foaf:mbox ?mbox. }"; + + try (TupleQueryResult result = testCon.prepareTupleQuery(queryBuilder).evaluate()) { + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); while (result.hasNext()) { BindingSet solution = result.next(); @@ -550,7 +547,7 @@ public void testSimpleTupleQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testPrepareSPARQLQuery(IsolationLevel level) throws Exception { + public void testPrepareSPARQLQuery(IsolationLevel level) { setupTest(level); StringBuilder queryBuilder = new StringBuilder(); @@ -585,17 +582,16 @@ public void testPrepareSPARQLQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSimpleTupleQueryUnicode(IsolationLevel level) throws Exception { + public void testSimpleTupleQueryUnicode(IsolationLevel level) { setupTest(level); testCon.add(alexander, name, Александър); - StringBuilder queryBuilder = new StringBuilder(128); - queryBuilder.append(" PREFIX foaf: <" + FOAF_NS + "> \n"); - queryBuilder.append(" SELECT ?person"); - queryBuilder.append(" WHERE { ?person foaf:name \"").append(Александър.getLabel()).append("\". }"); + String queryBuilder = " PREFIX foaf: <" + FOAF_NS + "> \n" + + " SELECT ?person" + + " WHERE { ?person foaf:name \"" + Александър.getLabel() + "\". }"; - try (TupleQueryResult result = testCon.prepareTupleQuery(queryBuilder.toString()).evaluate()) { - assertThat(result).isNotNull(); + try (TupleQueryResult result = testCon.prepareTupleQuery(queryBuilder).evaluate()) { + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); while (result.hasNext()) { BindingSet solution = result.next(); @@ -607,7 +603,7 @@ public void testSimpleTupleQueryUnicode(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testPreparedTupleQuery(IsolationLevel level) throws Exception { + public void testPreparedTupleQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -616,16 +612,15 @@ public void testPreparedTupleQuery(IsolationLevel level) throws Exception { testCon.add(bob, name, nameBob, context1); testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); - StringBuilder queryBuilder = new StringBuilder(); - queryBuilder.append(" PREFIX foaf: <" + FOAF_NS + "> \n"); - queryBuilder.append(" SELECT ?name ?mbox \n"); - queryBuilder.append(" WHERE { [] foaf:name ?name; \n"); - queryBuilder.append(" foaf:mbox ?mbox . }"); - TupleQuery query = testCon.prepareTupleQuery(queryBuilder.toString()); + String queryBuilder = " PREFIX foaf: <" + FOAF_NS + "> \n" + + " SELECT ?name ?mbox \n" + + " WHERE { [] foaf:name ?name; \n" + + " foaf:mbox ?mbox . }"; + TupleQuery query = testCon.prepareTupleQuery(queryBuilder); query.setBinding(NAME, nameBob); try (TupleQueryResult result = query.evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); while (result.hasNext()) { BindingSet solution = result.next(); @@ -641,21 +636,20 @@ public void testPreparedTupleQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testPreparedTupleQueryUnicode(IsolationLevel level) throws Exception { + public void testPreparedTupleQueryUnicode(IsolationLevel level) { setupTest(level); testCon.add(alexander, name, Александър); - StringBuilder queryBuilder = new StringBuilder(); - queryBuilder.append(" PREFIX foaf: <" + FOAF_NS + "> \n"); - queryBuilder.append(" SELECT ?person \n"); - queryBuilder.append(" WHERE { ?person foaf:name ?name . }"); + String queryBuilder = " PREFIX foaf: <" + FOAF_NS + "> \n" + + " SELECT ?person \n" + + " WHERE { ?person foaf:name ?name . }"; - TupleQuery query = testCon.prepareTupleQuery(queryBuilder.toString()); + TupleQuery query = testCon.prepareTupleQuery(queryBuilder); query.setBinding(NAME, Александър); try (TupleQueryResult result = query.evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); while (result.hasNext()) { @@ -668,7 +662,7 @@ public void testPreparedTupleQueryUnicode(IsolationLevel level) throws Exception @ParameterizedTest @MethodSource("parameters") - public void testSimpleGraphQuery(IsolationLevel level) throws Exception { + public void testSimpleGraphQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -679,14 +673,13 @@ public void testSimpleGraphQuery(IsolationLevel level) throws Exception { testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); - StringBuilder queryBuilder = new StringBuilder(128); - queryBuilder.append(" PREFIX foaf: <" + FOAF_NS + "> \n"); - queryBuilder.append(" CONSTRUCT\n"); - queryBuilder.append(" WHERE { [] foaf:name ?name;\n"); - queryBuilder.append(" foaf:mbox ?mbox.}"); + String queryBuilder = " PREFIX foaf: <" + FOAF_NS + "> \n" + + " CONSTRUCT\n" + + " WHERE { [] foaf:name ?name;\n" + + " foaf:mbox ?mbox.}"; - try (GraphQueryResult result = testCon.prepareGraphQuery(queryBuilder.toString()).evaluate()) { - assertThat(result).isNotNull(); + try (GraphQueryResult result = testCon.prepareGraphQuery(queryBuilder).evaluate()) { + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); while (result.hasNext()) { @@ -703,7 +696,7 @@ public void testSimpleGraphQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testPreparedGraphQuery(IsolationLevel level) throws Exception { + public void testPreparedGraphQuery(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -714,16 +707,15 @@ public void testPreparedGraphQuery(IsolationLevel level) throws Exception { testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); testCon.commit(); - StringBuilder queryBuilder = new StringBuilder(128); - queryBuilder.append(" PREFIX foaf: <" + FOAF_NS + "> \n"); - queryBuilder.append(" CONSTRUCT\n"); - queryBuilder.append(" WHERE { [] foaf:name ?name;\n"); - queryBuilder.append(" foaf:mbox ?mbox.}"); - GraphQuery query = testCon.prepareGraphQuery(queryBuilder.toString()); + String queryBuilder = " PREFIX foaf: <" + FOAF_NS + "> \n" + + " CONSTRUCT\n" + + " WHERE { [] foaf:name ?name;\n" + + " foaf:mbox ?mbox.}"; + GraphQuery query = testCon.prepareGraphQuery(queryBuilder); query.setBinding(NAME, nameBob); try (GraphQueryResult result = query.evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); while (result.hasNext()) { Statement st = result.next(); @@ -742,7 +734,7 @@ public void testPreparedGraphQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSimpleBooleanQuery(IsolationLevel level) throws Exception { + public void testSimpleBooleanQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -753,19 +745,18 @@ public void testSimpleBooleanQuery(IsolationLevel level) throws Exception { testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); - StringBuilder queryBuilder = new StringBuilder(64); - queryBuilder.append(PREFIX_FOAF + FOAF_NS + "> "); - queryBuilder.append(ASK); - queryBuilder.append("{ ?p foaf:name ?name }"); + String queryBuilder = PREFIX_FOAF + FOAF_NS + "> " + + ASK + + "{ ?p foaf:name ?name }"; - boolean exists = testCon.prepareBooleanQuery(QueryLanguage.SPARQL, queryBuilder.toString()).evaluate(); + boolean exists = testCon.prepareBooleanQuery(QueryLanguage.SPARQL, queryBuilder).evaluate(); assertThat(exists).isTrue(); } @ParameterizedTest @MethodSource("parameters") - public void testPreparedBooleanQuery(IsolationLevel level) throws Exception { + public void testPreparedBooleanQuery(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -776,12 +767,11 @@ public void testPreparedBooleanQuery(IsolationLevel level) throws Exception { testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); - StringBuilder queryBuilder = new StringBuilder(); - queryBuilder.append(PREFIX_FOAF + FOAF_NS + "> "); - queryBuilder.append(ASK); - queryBuilder.append("{ ?p foaf:name ?name }"); + String queryBuilder = PREFIX_FOAF + FOAF_NS + "> " + + ASK + + "{ ?p foaf:name ?name }"; - BooleanQuery query = testCon.prepareBooleanQuery(QueryLanguage.SPARQL, queryBuilder.toString()); + BooleanQuery query = testCon.prepareBooleanQuery(QueryLanguage.SPARQL, queryBuilder); query.setBinding(NAME, nameBob); assertThat(query.evaluate()).isTrue(); @@ -789,7 +779,7 @@ public void testPreparedBooleanQuery(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testDataset(IsolationLevel level) throws Exception { + public void testDataset(IsolationLevel level) { setupTest(level); testCon.add(alice, name, nameAlice, context2); @@ -847,7 +837,7 @@ public void testDataset(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testGetStatements(IsolationLevel level) throws Exception { + public void testGetStatements(IsolationLevel level) { setupTest(level); testCon.add(bob, name, nameBob); @@ -861,7 +851,7 @@ public void testGetStatements(IsolationLevel level) throws Exception { while (result.hasNext()) { Statement st = result.next(); assertNull(st.getContext(), "Statement should not be in a context "); - assertTrue(st.getPredicate().equals(name), "Statement predicate should be equal to name "); + assertEquals(st.getPredicate(), name, "Statement predicate should be equal to name "); } } @@ -873,7 +863,7 @@ public void testGetStatements(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testGetStatementsIterable(IsolationLevel level) throws Exception { + public void testGetStatementsIterable(IsolationLevel level) { setupTest(level); testCon.add(bob, name, nameBob); @@ -881,15 +871,15 @@ public void testGetStatementsIterable(IsolationLevel level) throws Exception { assertTrue(testCon.hasStatement(bob, name, nameBob, false), "Repository should contain statement"); try (RepositoryResult result = testCon.getStatements(null, name, null, false)) { - assertThat(result).isNotNull(); - assertThat(result).isNotEmpty(); + assertThat((Iterable) result).isNotNull(); + assertThat((Iterable) result).isNotEmpty(); for (Statement st : result) { assertThat(st.getContext()).isNull(); assertThat(st.getPredicate()).isEqualTo(name); } - assertThat(result).isEmpty(); + assertThat((Iterable) result).isEmpty(); assertThat(result.isClosed()).isTrue(); } @@ -897,7 +887,7 @@ public void testGetStatementsIterable(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testGetStatementsMalformedTypedLiteral(IsolationLevel level) throws Exception { + public void testGetStatementsMalformedTypedLiteral(IsolationLevel level) { setupTest(level); Literal invalidIntegerLiteral = vf.createLiteral("the number four", XSD.INTEGER); @@ -910,7 +900,7 @@ public void testGetStatementsMalformedTypedLiteral(IsolationLevel level) throws assertTrue(statements.hasNext()); Statement st = statements.next(); assertTrue(st.getObject() instanceof Literal); - assertTrue(st.getObject().equals(invalidIntegerLiteral)); + assertEquals(st.getObject(), invalidIntegerLiteral); } } catch (RepositoryException e) { // shouldn't happen @@ -920,7 +910,7 @@ public void testGetStatementsMalformedTypedLiteral(IsolationLevel level) throws @ParameterizedTest @MethodSource("parameters") - public void testGetStatementsMalformedLanguageLiteral(IsolationLevel level) throws Exception { + public void testGetStatementsMalformedLanguageLiteral(IsolationLevel level) { setupTest(level); Literal invalidLanguageLiteral = vf.createLiteral("the number four", "en_us"); @@ -933,7 +923,7 @@ public void testGetStatementsMalformedLanguageLiteral(IsolationLevel level) thro assertTrue(statements.hasNext()); Statement st = statements.next(); assertTrue(st.getObject() instanceof Literal); - assertTrue(st.getObject().equals(invalidLanguageLiteral)); + assertEquals(st.getObject(), invalidLanguageLiteral); } } catch (RepositoryException e) { e.printStackTrace(); @@ -944,7 +934,7 @@ public void testGetStatementsMalformedLanguageLiteral(IsolationLevel level) thro @ParameterizedTest @MethodSource("parameters") - public void testGetStatementsInSingleContext(IsolationLevel level) throws Exception { + public void testGetStatementsInSingleContext(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -982,7 +972,7 @@ public void testGetStatementsInSingleContext(IsolationLevel level) throws Except // Check handling of getStatements with an unknown context ID try (RepositoryResult result = testCon.getStatements(null, null, null, false, unknownContext)) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isFalse(); } @@ -995,7 +985,7 @@ public void testGetStatementsInSingleContext(IsolationLevel level) throws Except @ParameterizedTest @MethodSource("parameters") - public void testGetStatementsInMultipleContexts(IsolationLevel level) throws Exception { + public void testGetStatementsInMultipleContexts(IsolationLevel level) { setupTest(level); testCon.clear(); @@ -1054,7 +1044,7 @@ public void testGetStatementsInMultipleContexts(IsolationLevel level) throws Exc testCon.commit(); try (RepositoryResult iter = testCon.getStatements(null, null, null, false, context1)) { - assertThat(iter).isNotNull(); + assertThat((Iterable) iter).isNotNull(); assertThat(iter.hasNext()).isTrue(); } @@ -1085,7 +1075,7 @@ public void testGetStatementsInMultipleContexts(IsolationLevel level) throws Exc @ParameterizedTest @MethodSource("parameters") - public void testDuplicateFilter(IsolationLevel level) throws Exception { + public void testDuplicateFilter(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -1110,7 +1100,7 @@ public void testDuplicateFilter(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testRemoveStatements(IsolationLevel level) throws Exception { + public void testRemoveStatements(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -1133,7 +1123,7 @@ public void testRemoveStatements(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testRemoveStatementWithContext(IsolationLevel level) throws Exception { + public void testRemoveStatementWithContext(IsolationLevel level) { setupTest(level); Statement statement = vf.createStatement(alice, name, nameAlice, context1); @@ -1151,7 +1141,7 @@ public void testRemoveStatementWithContext(IsolationLevel level) throws Exceptio @ParameterizedTest @MethodSource("parameters") - public void testRemoveStatementCollection(IsolationLevel level) throws Exception { + public void testRemoveStatementCollection(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -1174,7 +1164,7 @@ public void testRemoveStatementCollection(IsolationLevel level) throws Exception @ParameterizedTest @MethodSource("parameters") - public void testRemoveStatementIteration(IsolationLevel level) throws Exception { + public void testRemoveStatementIteration(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -1185,7 +1175,7 @@ public void testRemoveStatementIteration(IsolationLevel level) throws Exception assertThat(testCon.hasStatement(bob, name, nameBob, false)).isTrue(); assertThat(testCon.hasStatement(alice, name, nameAlice, false)).isTrue(); - try (CloseableIteration iter = testCon.getStatements(null, null, null, + try (CloseableIteration iter = testCon.getStatements(null, null, null, false)) { testCon.remove(iter); } @@ -1196,7 +1186,7 @@ public void testRemoveStatementIteration(IsolationLevel level) throws Exception @ParameterizedTest @MethodSource("parameters") - public void testGetNamespace(IsolationLevel level) throws Exception { + public void testGetNamespace(IsolationLevel level) { setupTest(level); setupNamespaces(); @@ -1208,7 +1198,7 @@ public void testGetNamespace(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testGetNamespaces(IsolationLevel level) throws Exception { + public void testGetNamespaces(IsolationLevel level) { setupTest(level); setupNamespaces(); @@ -1222,7 +1212,7 @@ public void testGetNamespaces(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testImportNamespacesFromIterable(IsolationLevel level) throws Exception { + public void testImportNamespacesFromIterable(IsolationLevel level) { setupTest(level); Model nsAwareModel = new LinkedHashModel(); @@ -1239,7 +1229,7 @@ public void testImportNamespacesFromIterable(IsolationLevel level) throws Except assertThat(testCon.getNamespace(EXAMPLE)).isEqualTo(EXAMPLE_NS); } - private void setupNamespaces() throws IOException, RDFParseException, RepositoryException { + private void setupNamespaces() throws RDFParseException, RepositoryException { testCon.setNamespace(EXAMPLE, EXAMPLE_NS); testCon.setNamespace(RDF_PREFIX, "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); testCon.setNamespace(RDFS_PREFIX, RDFS_NS); @@ -1250,7 +1240,7 @@ private void setupNamespaces() throws IOException, RDFParseException, Repository @ParameterizedTest @MethodSource("parameters") - public void testClear(IsolationLevel level) throws Exception { + public void testClear(IsolationLevel level) { setupTest(level); testCon.add(bob, name, nameBob); @@ -1434,7 +1424,7 @@ public void testGraphSerialization(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testEmptyRollback(IsolationLevel level) throws Exception { + public void testEmptyRollback(IsolationLevel level) { setupTest(level); if (IsolationLevels.NONE.isCompatibleWith(level)) { @@ -1453,7 +1443,7 @@ public void testEmptyRollback(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testEmptyCommit(IsolationLevel level) throws Exception { + public void testEmptyCommit(IsolationLevel level) { setupTest(level); if (IsolationLevels.NONE.isCompatibleWith(level)) { @@ -1472,7 +1462,7 @@ public void testEmptyCommit(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testOpen(IsolationLevel level) throws Exception { + public void testOpen(IsolationLevel level) { setupTest(level); assertThat(testCon.isOpen()).isTrue(); @@ -1484,7 +1474,7 @@ public void testOpen(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSizeRollback(IsolationLevel level) throws Exception { + public void testSizeRollback(IsolationLevel level) { setupTest(level); if (IsolationLevels.NONE.isCompatibleWith(level)) { @@ -1506,7 +1496,7 @@ public void testSizeRollback(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSizeCommit(IsolationLevel level) throws Exception { + public void testSizeCommit(IsolationLevel level) { setupTest(level); if (IsolationLevels.NONE.isCompatibleWith(level)) { @@ -1528,7 +1518,7 @@ public void testSizeCommit(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSizeDuplicateStatement(IsolationLevel level) throws Exception { + public void testSizeDuplicateStatement(IsolationLevel level) { setupTest(level); testCon.begin(); @@ -1692,7 +1682,7 @@ public void testAddDeleteInsert(IsolationLevel level) throws RDF4JException { @ParameterizedTest @MethodSource("parameters") - public void testQueryInTransaction(IsolationLevel level) throws Exception { + public void testQueryInTransaction(IsolationLevel level) { setupTest(level); testCon.add(bob, RDF.TYPE, FOAF.PERSON); @@ -1710,7 +1700,7 @@ public void testQueryInTransaction(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testUpdateInTransaction(IsolationLevel level) throws Exception { + public void testUpdateInTransaction(IsolationLevel level) { setupTest(level); testCon.add(bob, RDF.TYPE, FOAF.PERSON); @@ -1727,7 +1717,7 @@ public void testUpdateInTransaction(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testInferredStatementCount(IsolationLevel level) throws Exception { + public void testInferredStatementCount(IsolationLevel level) { setupTest(level); assertThat(testCon.isEmpty()).isTrue(); @@ -1744,7 +1734,7 @@ public void testInferredStatementCount(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testGetContextIDs(IsolationLevel level) throws Exception { + public void testGetContextIDs(IsolationLevel level) { setupTest(level); assertThat(Iterations.asList(testCon.getContextIDs())).isEmpty(); @@ -1792,17 +1782,19 @@ public void testXmlCalendarZ(IsolationLevel level) throws Exception { xcal.setTimezone(OFFSET); TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, SELECT_BY_DATE); query.setBinding("date", vf.createLiteral(xcal)); - TupleQueryResult result = query.evaluate(); - List list = new ArrayList<>(); - while (result.hasNext()) { - list.add(result.next()); + List list; + try (TupleQueryResult result = query.evaluate()) { + list = new ArrayList<>(); + while (result.hasNext()) { + list.add(result.next()); + } } assertThat(list).hasSize(7); } @ParameterizedTest @MethodSource("parameters") - public void testOptionalFilter(IsolationLevel level) throws Exception { + public void testOptionalFilter(IsolationLevel level) { setupTest(level); String optional = "{ ?s :p1 ?v1 OPTIONAL {?s :p2 ?v2 FILTER(?v1<3) } }"; @@ -1830,7 +1822,7 @@ public void testOptionalFilter(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testOrPredicate(IsolationLevel level) throws Exception { + public void testOrPredicate(IsolationLevel level) { setupTest(level); String union = "{ :s ?p :o FILTER (?p = :p1 || ?p = :p2) }"; @@ -1855,7 +1847,7 @@ public void testOrPredicate(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSES713(IsolationLevel level) throws Exception { + public void testSES713(IsolationLevel level) { setupTest(level); String queryString = "SELECT * { ?sub ?pred ?obj . FILTER ( 'not a number' + 1 = ?obj )}"; @@ -1868,7 +1860,7 @@ public void testSES713(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testSES2172ChineseChars(IsolationLevel level) throws Exception { + public void testSES2172ChineseChars(IsolationLevel level) { setupTest(level); String updateString = "INSERT DATA { rdfs:label \"\\u8BBE\\u5907\". }"; @@ -1895,7 +1887,7 @@ public void testSES2172ChineseChars(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testQueryDefaultGraph(IsolationLevel level) throws Exception { + public void testQueryDefaultGraph(IsolationLevel level) { setupTest(level); IRI graph = vf.createIRI("urn:test:default"); @@ -1907,7 +1899,7 @@ public void testQueryDefaultGraph(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testQueryBaseURI(IsolationLevel level) throws Exception { + public void testQueryBaseURI(IsolationLevel level) { setupTest(level); testCon.add(vf.createIRI(URN_TEST_S1), vf.createIRI(URN_TEST_P1), vf.createIRI(URN_TEST_O1)); @@ -1919,7 +1911,7 @@ public void testQueryBaseURI(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testUpdateBaseURI(IsolationLevel level) throws Exception { + public void testUpdateBaseURI(IsolationLevel level) { setupTest(level); testCon.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { <> a <> }", URN_TEST_S1).execute(); @@ -1928,7 +1920,7 @@ public void testUpdateBaseURI(IsolationLevel level) throws Exception { @ParameterizedTest @MethodSource("parameters") - public void testDeleteDefaultGraph(IsolationLevel level) throws Exception { + public void testDeleteDefaultGraph(IsolationLevel level) { setupTest(level); IRI g1 = vf.createIRI("urn:test:g1"); @@ -2008,7 +2000,7 @@ private long size(IRI defaultGraph) throws RepositoryException, MalformedQueryEx } private long getTotalStatementCount(RepositoryConnection connection) throws RepositoryException { - try (CloseableIteration iter = connection.getStatements(null, null, + try (CloseableIteration iter = connection.getStatements(null, null, null, true)) { return iter.stream().count(); } diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RepositoryTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RepositoryTest.java index 23ac61329b3..79a65e5f98f 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RepositoryTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/RepositoryTest.java @@ -37,7 +37,7 @@ public abstract class RepositoryTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @@ -108,7 +108,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { testRepository.shutDown(); } @@ -117,10 +117,10 @@ public void tearDown() throws Exception { * * @return an uninitialized repository. */ - protected abstract Repository createRepository() throws Exception; + protected abstract Repository createRepository(); @Test - public void testShutdownFollowedByInit() throws Exception { + public void testShutdownFollowedByInit() { testRepository.init(); RepositoryConnection conn = testRepository.getConnection(); try { @@ -143,7 +143,7 @@ public void testShutdownFollowedByInit() throws Exception { } @Test - public void testAutoInit() throws Exception { + public void testAutoInit() { try (RepositoryConnection conn = testRepository.getConnection()) { conn.add(bob, mbox, mboxBob); assertTrue(conn.hasStatement(bob, mbox, mboxBob, true)); diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlAggregatesTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlAggregatesTest.java index 6f99760dad7..1cef9157863 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlAggregatesTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlAggregatesTest.java @@ -35,12 +35,12 @@ public abstract class SparqlAggregatesTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterAll - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -69,7 +69,7 @@ public static void afterClass() throws Exception { private ValueFactory vf; @Test - public void testSelect() throws Exception { + public void testSelect() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, selectNameMbox); TupleQueryResult result = query.evaluate(); assertTrue(result.hasNext()); @@ -80,7 +80,7 @@ public void testSelect() throws Exception { } @Test - public void testConcat() throws Exception { + public void testConcat() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, concatMbox); TupleQueryResult result = query.evaluate(); assertTrue(result.hasNext()); @@ -91,7 +91,7 @@ public void testConcat() throws Exception { } @Test - public void testConcatOptional() throws Exception { + public void testConcatOptional() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, concatOptionalMbox); TupleQueryResult result = query.evaluate(); assertTrue(result.hasNext()); @@ -103,7 +103,7 @@ public void testConcatOptional() throws Exception { } @Test - public void testCount() throws Exception { + public void testCount() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, countMbox); TupleQueryResult result = query.evaluate(); assertTrue(result.hasNext()); @@ -114,7 +114,7 @@ public void testCount() throws Exception { } @Test - public void testCountOptional() throws Exception { + public void testCountOptional() { Set zeroOr1 = new HashSet<>(); zeroOr1.add("0"); zeroOr1.add("1"); @@ -129,7 +129,7 @@ public void testCountOptional() throws Exception { } @BeforeEach - public void setUp() throws Exception { + public void setUp() { repository = createRepository(); vf = repository.getValueFactory(); createUser("james", "James Leigh", "james@leigh"); @@ -138,7 +138,7 @@ public void setUp() throws Exception { conn = repository.getConnection(); } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { con.clear(); @@ -147,10 +147,10 @@ protected Repository createRepository() throws Exception { return repository; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); @AfterEach - public void tearDown() throws Exception { + public void tearDown() { conn.close(); conn = null; diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlDatasetTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlDatasetTest.java index 84b7ad7af12..6859029ad19 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlDatasetTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlDatasetTest.java @@ -37,12 +37,12 @@ public abstract class SparqlDatasetTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterAll - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -72,7 +72,7 @@ public static void afterClass() throws Exception { private IRI ringo; @Test - public void testNoFrom() throws Exception { + public void testNoFrom() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryNoFrom); TupleQueryResult result = query.evaluate(); @@ -103,7 +103,7 @@ public void testNoFrom() throws Exception { } @Test - public void testWithFrom() throws Exception { + public void testWithFrom() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryWithFrom); TupleQueryResult result = query.evaluate(); @@ -134,7 +134,7 @@ public void testWithFrom() throws Exception { } @BeforeEach - public void setUp() throws Exception { + public void setUp() { repository = createRepository(); vf = repository.getValueFactory(); graph1 = vf.createIRI("http://example.org/graph1"); @@ -148,7 +148,7 @@ public void setUp() throws Exception { dataset.addDefaultGraph(graph1); } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { con.clear(); @@ -157,10 +157,10 @@ protected Repository createRepository() throws Exception { return repository; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); @AfterEach - public void tearDown() throws Exception { + public void tearDown() { conn.close(); conn = null; @@ -183,7 +183,7 @@ private IRI createUser(String id, String name, String email, Resource... context } @Test - public void testSelectAllIsSameAsCount() throws Exception { + public void testSelectAllIsSameAsCount() { try (RepositoryConnection con = repository.getConnection()) { TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT ?s ?p ?o WHERE {?s ?p ?o}"); TupleQueryResult res = tupleQuery.evaluate(); diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlOrderByTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlOrderByTest.java index beb210328b5..43a8e88fd68 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlOrderByTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlOrderByTest.java @@ -37,7 +37,7 @@ public abstract class SparqlOrderByTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @@ -62,23 +62,23 @@ public static void afterClass() throws Exception { private RepositoryConnection conn; @Test - public void testQuery1() throws Exception { + public void testQuery1() { assertTrue("James Leigh".compareTo("James Leigh Hunt") < 0); assertResult(query1, Arrays.asList("James Leigh", "James Leigh", "James Leigh Hunt", "Megan Leigh")); } @Test - public void testQuery2() throws Exception { + public void testQuery2() { assertResult(query2, Arrays.asList("Megan Leigh", "James Leigh", "James Leigh Hunt", "James Leigh")); } @Test - public void testQuery3() throws Exception { + public void testQuery3() { assertResult(query3, Arrays.asList("James Leigh", "James Leigh", "James Leigh Hunt", "Megan Leigh")); } @BeforeEach - public void setUp() throws Exception { + public void setUp() { repository = createRepository(); createEmployee("james", "James Leigh", 123); createEmployee("jim", "James Leigh", 244); @@ -87,7 +87,7 @@ public void setUp() throws Exception { conn = repository.getConnection(); } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { con.clear(); @@ -96,10 +96,10 @@ protected Repository createRepository() throws Exception { return repository; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); @AfterEach - public void tearDown() throws Exception { + public void tearDown() { conn.close(); conn = null; diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlRegexTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlRegexTest.java index 7532c78caee..fcd4a19c10e 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlRegexTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlRegexTest.java @@ -32,7 +32,7 @@ public abstract class SparqlRegexTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @@ -68,7 +68,7 @@ public static void afterClass() throws Exception { private Literal hunt; @Test - public void testInline() throws Exception { + public void testInline() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryInline); TupleQueryResult result = query.evaluate(); assertEquals(hunt, result.next().getValue("name")); @@ -77,7 +77,7 @@ public void testInline() throws Exception { } @Test - public void testBinding() throws Exception { + public void testBinding() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBinding); query.setBinding("pattern", vf.createLiteral("@work.example")); TupleQueryResult result = query.evaluate(); @@ -87,7 +87,7 @@ public void testBinding() throws Exception { } @Test - public void testBindingFlags() throws Exception { + public void testBindingFlags() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBindingFlags); query.setBinding("pattern", vf.createLiteral("@Work.example")); query.setBinding("flags", vf.createLiteral("i")); @@ -98,7 +98,7 @@ public void testBindingFlags() throws Exception { } @Test - public void testExpr() throws Exception { + public void testExpr() { IRI pattern = vf.createIRI("http://example.org/ns#", "pattern"); IRI flags = vf.createIRI("http://example.org/ns#", "flags"); BNode bnode = vf.createBNode(); @@ -112,7 +112,7 @@ public void testExpr() throws Exception { } @BeforeEach - public void setUp() throws Exception { + public void setUp() { repository = createRepository(); vf = repository.getValueFactory(); hunt = vf.createLiteral("James Leigh Hunt"); @@ -122,7 +122,7 @@ public void setUp() throws Exception { conn = repository.getConnection(); } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { con.clear(); @@ -131,10 +131,10 @@ protected Repository createRepository() throws Exception { return repository; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); @AfterEach - public void tearDown() throws Exception { + public void tearDown() { conn.close(); conn = null; diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlSetBindingTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlSetBindingTest.java index cf204f47a18..021c697beca 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlSetBindingTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/SparqlSetBindingTest.java @@ -32,12 +32,12 @@ public abstract class SparqlSetBindingTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterAll - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -59,7 +59,7 @@ public static void afterClass() throws Exception { private IRI ringoRes; @Test - public void testBinding() throws Exception { + public void testBinding() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBinding); query.setBinding("name", ringo); TupleQueryResult result = query.evaluate(); @@ -69,7 +69,7 @@ public void testBinding() throws Exception { } @Test - public void testBindingSubselect() throws Exception { + public void testBindingSubselect() { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBindingSubselect); query.setBinding("x", ringoRes); TupleQueryResult result = query.evaluate(); @@ -79,7 +79,7 @@ public void testBindingSubselect() throws Exception { } @BeforeEach - public void setUp() throws Exception { + public void setUp() { repository = createRepository(); vf = repository.getValueFactory(); ringo = vf.createLiteral("Ringo Starr"); @@ -91,7 +91,7 @@ public void setUp() throws Exception { conn = repository.getConnection(); } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { con.clear(); @@ -100,10 +100,10 @@ protected Repository createRepository() throws Exception { return repository; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); @AfterEach - public void tearDown() throws Exception { + public void tearDown() { conn.close(); conn = null; diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/TupleQueryResultTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/TupleQueryResultTest.java index d0317d8c031..f0583585349 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/TupleQueryResultTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/TupleQueryResultTest.java @@ -91,7 +91,7 @@ public void tearDown() throws Exception { } } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { con.clear(); @@ -100,7 +100,7 @@ protected Repository createRepository() throws Exception { return repository; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); /* * build some simple SPARQL queries to use for testing the result set object. diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/DeadLockTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/DeadLockTest.java index 7f9905eea61..e02fb007d02 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/DeadLockTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/DeadLockTest.java @@ -31,12 +31,12 @@ public class DeadLockTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -68,7 +68,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { a.close(); } finally { diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/DeleteInsertTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/DeleteInsertTest.java index 2296daf1298..01405ca957b 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/DeleteInsertTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/DeleteInsertTest.java @@ -32,12 +32,12 @@ public class DeleteInsertTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -58,7 +58,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { con.close(); } finally { diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/IsolationLevelTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/IsolationLevelTest.java index ebbaaded814..04ca3a0a91b 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/IsolationLevelTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/IsolationLevelTest.java @@ -47,12 +47,12 @@ public class IsolationLevelTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -79,7 +79,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { store.shutDown(); } @@ -97,12 +97,12 @@ protected boolean isSupported(IsolationLevels level) throws RepositoryException } @Test - public void testNone() throws Exception { + public void testNone() { readPending(IsolationLevels.NONE); } @Test - public void testReadUncommitted() throws Exception { + public void testReadUncommitted() { rollbackTriple(IsolationLevels.READ_UNCOMMITTED); readPending(IsolationLevels.READ_UNCOMMITTED); } @@ -306,7 +306,7 @@ private void snapshotRead(IsolationLevel level) throws RepositoryException { insertTestStatement(con, i); } int counter = 0; - try (CloseableIteration stmts = con.getStatements(null, null, + try (CloseableIteration stmts = con.getStatements(null, null, null, false)) { while (stmts.hasNext()) { Statement st = stmts.next(); @@ -461,7 +461,7 @@ private void clear(Repository store) throws RepositoryException { protected long count(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws RepositoryException { - try (CloseableIteration stmts = con.getStatements(subj, pred, obj, + try (CloseableIteration stmts = con.getStatements(subj, pred, obj, includeInferred, contexts)) { long counter = 0; while (stmts.hasNext()) { @@ -473,7 +473,7 @@ protected long count(RepositoryConnection con, Resource subj, IRI pred, Value ob } protected Literal readLiteral(RepositoryConnection con, final IRI subj, final IRI pred) throws RepositoryException { - try (CloseableIteration stmts = con.getStatements(subj, pred, null, + try (CloseableIteration stmts = con.getStatements(subj, pred, null, false)) { if (!stmts.hasNext()) { return null; diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/LinearTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/LinearTest.java index 557d29dfbd4..3bc988eeda1 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/LinearTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/LinearTest.java @@ -44,12 +44,12 @@ public class LinearTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -120,7 +120,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { a.close(); } finally { @@ -133,7 +133,7 @@ public void tearDown() throws Exception { } @Test - public void test_independentPattern() throws Exception { + public void test_independentPattern() { a.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); assertEquals(1, size(a, PICASSO, RDF.TYPE, PAINTER, false)); @@ -147,7 +147,7 @@ public void test_independentPattern() throws Exception { } @Test - public void test_safePattern() throws Exception { + public void test_safePattern() { a.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); assertEquals(1, size(a, null, RDF.TYPE, PAINTER, false)); @@ -158,7 +158,7 @@ public void test_safePattern() throws Exception { } @Test - public void test_afterPattern() throws Exception { + public void test_afterPattern() { a.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); assertEquals(1, size(a, null, RDF.TYPE, PAINTER, false)); @@ -170,7 +170,7 @@ public void test_afterPattern() throws Exception { } @Test - public void test_afterInsertDataPattern() throws Exception { + public void test_afterInsertDataPattern() { a.begin(level); a.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { a }", NS).execute(); assertEquals(1, size(a, null, RDF.TYPE, PAINTER, false)); @@ -182,7 +182,7 @@ public void test_afterInsertDataPattern() throws Exception { } @Test - public void test_changedPattern() throws Exception { + public void test_changedPattern() { a.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); a.commit(); @@ -193,7 +193,7 @@ public void test_changedPattern() throws Exception { } @Test - public void test_safeQuery() throws Exception { + public void test_safeQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -214,7 +214,7 @@ public void test_safeQuery() throws Exception { } @Test - public void test_safeInsert() throws Exception { + public void test_safeInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -233,7 +233,7 @@ public void test_safeInsert() throws Exception { } @Test - public void test_safeOptionalQuery() throws Exception { + public void test_safeOptionalQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -257,7 +257,7 @@ public void test_safeOptionalQuery() throws Exception { } @Test - public void test_safeOptionalInsert() throws Exception { + public void test_safeOptionalInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -276,7 +276,7 @@ public void test_safeOptionalInsert() throws Exception { } @Test - public void test_safeFilterQuery() throws Exception { + public void test_safeFilterQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -298,7 +298,7 @@ public void test_safeFilterQuery() throws Exception { } @Test - public void test_safeFilterInsert() throws Exception { + public void test_safeFilterInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -318,7 +318,7 @@ public void test_safeFilterInsert() throws Exception { } @Test - public void test_safeRangeQuery() throws Exception { + public void test_safeRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, ARTEMISIA); a.add(REMBRANDT, PAINTS, DANAE); @@ -346,7 +346,7 @@ public void test_safeRangeQuery() throws Exception { } @Test - public void test_safeRangeInsert() throws Exception { + public void test_safeRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, ARTEMISIA); a.add(REMBRANDT, PAINTS, DANAE); @@ -372,14 +372,13 @@ public void test_safeRangeInsert() throws Exception { assertEquals(17, size(a, null, null, null, false)); } - private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx) - throws Exception { + private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx) { try (RepositoryResult statements = con.getStatements(subj, pred, obj, inf, ctx)) { return QueryResults.asList(statements).size(); } } - private List eval(String var, RepositoryConnection con, String qry) throws Exception { + private List eval(String var, RepositoryConnection con, String qry) { TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, qry, NS); try (TupleQueryResult result = tq.evaluate()) { List list = new ArrayList<>(); diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/ModificationTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/ModificationTest.java index 2e2988e8008..e060300405d 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/ModificationTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/ModificationTest.java @@ -31,12 +31,12 @@ public class ModificationTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -62,7 +62,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { con.close(); } finally { @@ -71,7 +71,7 @@ public void tearDown() throws Exception { } @Test - public void testAdd() throws Exception { + public void testAdd() { con.begin(level); con.add(PICASSO, RDF.TYPE, PAINTER); con.commit(); @@ -79,7 +79,7 @@ public void testAdd() throws Exception { } @Test - public void testAutoCommit() throws Exception { + public void testAutoCommit() { con.add(PICASSO, RDF.TYPE, PAINTER); con.close(); con = repo.getConnection(); @@ -87,7 +87,7 @@ public void testAutoCommit() throws Exception { } @Test - public void testInsertData() throws Exception { + public void testInsertData() { con.begin(level); con.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { a }", NS).execute(); con.commit(); @@ -95,7 +95,7 @@ public void testInsertData() throws Exception { } @Test - public void testInsertDataAutoCommit() throws Exception { + public void testInsertDataAutoCommit() { con.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { a }", NS).execute(); con.close(); con = repo.getConnection(); @@ -103,7 +103,7 @@ public void testInsertDataAutoCommit() throws Exception { } @Test - public void testRemove() throws Exception { + public void testRemove() { con.begin(level); con.add(PICASSO, RDF.TYPE, PAINTER); con.commit(); @@ -114,7 +114,7 @@ public void testRemove() throws Exception { } @Test - public void testAddIn() throws Exception { + public void testAddIn() { con.begin(level); con.add(PICASSO, RDF.TYPE, PAINTER, PICASSO); con.commit(); @@ -122,7 +122,7 @@ public void testAddIn() throws Exception { } @Test - public void testRemoveFrom() throws Exception { + public void testRemoveFrom() { con.begin(level); con.add(PICASSO, RDF.TYPE, PAINTER, PICASSO); con.commit(); @@ -133,7 +133,7 @@ public void testRemoveFrom() throws Exception { } @Test - public void testMove() throws Exception { + public void testMove() { con.begin(level); con.add(PICASSO, RDF.TYPE, PAINTER, PICASSO); con.commit(); @@ -146,7 +146,7 @@ public void testMove() throws Exception { } @Test - public void testMoveOut() throws Exception { + public void testMoveOut() { con.begin(level); con.add(PICASSO, RDF.TYPE, PAINTER, PICASSO); con.commit(); @@ -159,7 +159,7 @@ public void testMoveOut() throws Exception { } @Test - public void testCancel() throws Exception { + public void testCancel() { con.begin(level); con.add(PICASSO, RDF.TYPE, PAINTER, PICASSO); con.remove(PICASSO, RDF.TYPE, PAINTER, PICASSO); @@ -168,7 +168,7 @@ public void testCancel() throws Exception { } @Test - public void testRemoveDuplicate() throws Exception { + public void testRemoveDuplicate() { con.add(PICASSO, RDF.TYPE, PAINTER, PICASSO, PAINTER); assertTrue(con.hasStatement(PICASSO, RDF.TYPE, PAINTER, false, PAINTER)); assertTrue(con.hasStatement(PICASSO, RDF.TYPE, PAINTER, false, PICASSO)); diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/MonotonicTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/MonotonicTest.java index f34962ff71e..536dc70823a 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/MonotonicTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/MonotonicTest.java @@ -37,12 +37,12 @@ public class MonotonicTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -113,7 +113,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { a.close(); } finally { @@ -126,7 +126,7 @@ public void tearDown() throws Exception { } @Test - public void test_independentPattern() throws Exception { + public void test_independentPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -140,7 +140,7 @@ public void test_independentPattern() throws Exception { } @Test - public void test_safePattern() throws Exception { + public void test_safePattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -151,7 +151,7 @@ public void test_safePattern() throws Exception { } @Test - public void test_afterPattern() throws Exception { + public void test_afterPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -163,7 +163,7 @@ public void test_afterPattern() throws Exception { } @Test - public void test_afterInsertDataPattern() throws Exception { + public void test_afterInsertDataPattern() { a.begin(level); b.begin(level); a.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { a }", NS).execute(); @@ -175,7 +175,7 @@ public void test_afterInsertDataPattern() throws Exception { } @Test - public void test_changedPattern() throws Exception { + public void test_changedPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -187,7 +187,7 @@ public void test_changedPattern() throws Exception { } @Test - public void test_safeQuery() throws Exception { + public void test_safeQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -208,7 +208,7 @@ public void test_safeQuery() throws Exception { } @Test - public void test_safeInsert() throws Exception { + public void test_safeInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -227,7 +227,7 @@ public void test_safeInsert() throws Exception { } @Test - public void test_mergeQuery() throws Exception { + public void test_mergeQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -249,7 +249,7 @@ public void test_mergeQuery() throws Exception { } @Test - public void test_mergeInsert() throws Exception { + public void test_mergeInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -269,7 +269,7 @@ public void test_mergeInsert() throws Exception { } @Test - public void test_changedQuery() throws Exception { + public void test_changedQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -291,7 +291,7 @@ public void test_changedQuery() throws Exception { } @Test - public void test_changedInsert() throws Exception { + public void test_changedInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -311,7 +311,7 @@ public void test_changedInsert() throws Exception { } @Test - public void test_safeOptionalQuery() throws Exception { + public void test_safeOptionalQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -335,7 +335,7 @@ public void test_safeOptionalQuery() throws Exception { } @Test - public void test_safeOptionalInsert() throws Exception { + public void test_safeOptionalInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -354,7 +354,7 @@ public void test_safeOptionalInsert() throws Exception { } @Test - public void test_mergeOptionalQuery() throws Exception { + public void test_mergeOptionalQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -379,7 +379,7 @@ public void test_mergeOptionalQuery() throws Exception { } @Test - public void test_mergeOptionalInsert() throws Exception { + public void test_mergeOptionalInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -399,7 +399,7 @@ public void test_mergeOptionalInsert() throws Exception { } @Test - public void test_changedOptionalQuery() throws Exception { + public void test_changedOptionalQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -424,7 +424,7 @@ public void test_changedOptionalQuery() throws Exception { } @Test - public void test_changedOptionalInsert() throws Exception { + public void test_changedOptionalInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -444,7 +444,7 @@ public void test_changedOptionalInsert() throws Exception { } @Test - public void test_safeFilterQuery() throws Exception { + public void test_safeFilterQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -466,7 +466,7 @@ public void test_safeFilterQuery() throws Exception { } @Test - public void test_safeFilterInsert() throws Exception { + public void test_safeFilterInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -486,7 +486,7 @@ public void test_safeFilterInsert() throws Exception { } @Test - public void test_mergeOptionalFilterQuery() throws Exception { + public void test_mergeOptionalFilterQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -513,7 +513,7 @@ public void test_mergeOptionalFilterQuery() throws Exception { } @Test - public void test_mergeOptionalFilterInsert() throws Exception { + public void test_mergeOptionalFilterInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -536,7 +536,7 @@ public void test_mergeOptionalFilterInsert() throws Exception { } @Test - public void test_changedOptionalFilterQuery() throws Exception { + public void test_changedOptionalFilterQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -562,7 +562,7 @@ public void test_changedOptionalFilterQuery() throws Exception { } @Test - public void test_changedOptionalFilterInsert() throws Exception { + public void test_changedOptionalFilterInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -585,7 +585,7 @@ public void test_changedOptionalFilterInsert() throws Exception { } @Test - public void test_safeRangeQuery() throws Exception { + public void test_safeRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, ARTEMISIA); a.add(REMBRANDT, PAINTS, DANAE); @@ -613,7 +613,7 @@ public void test_safeRangeQuery() throws Exception { } @Test - public void test_safeRangeInsert() throws Exception { + public void test_safeRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, ARTEMISIA); a.add(REMBRANDT, PAINTS, DANAE); @@ -640,7 +640,7 @@ public void test_safeRangeInsert() throws Exception { } @Test - public void test_mergeRangeQuery() throws Exception { + public void test_mergeRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -669,7 +669,7 @@ public void test_mergeRangeQuery() throws Exception { } @Test - public void test_mergeRangeInsert() throws Exception { + public void test_mergeRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -697,7 +697,7 @@ public void test_mergeRangeInsert() throws Exception { } @Test - public void test_changedRangeQuery() throws Exception { + public void test_changedRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -726,7 +726,7 @@ public void test_changedRangeQuery() throws Exception { } @Test - public void test_changedRangeInsert() throws Exception { + public void test_changedRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -753,12 +753,11 @@ public void test_changedRangeInsert() throws Exception { assertEquals(16, size(a, null, null, null, false)); } - private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx) - throws Exception { + private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx) { return QueryResults.asList(con.getStatements(subj, pred, obj, inf, ctx)).size(); } - private List eval(String var, RepositoryConnection con, String qry) throws Exception { + private List eval(String var, RepositoryConnection con, String qry) { try (TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL, qry, NS).evaluate()) { List list = new ArrayList<>(); while (result.hasNext()) { diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/RemoveIsolationTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/RemoveIsolationTest.java index a9a6196d702..2b6bd984bb1 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/RemoveIsolationTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/RemoveIsolationTest.java @@ -38,12 +38,12 @@ public class RemoveIsolationTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -63,7 +63,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { con.close(); } finally { @@ -72,7 +72,7 @@ public void tearDown() throws Exception { } @Test - public void testRemoveOptimisticIsolation() throws Exception { + public void testRemoveOptimisticIsolation() { con.begin(level); con.add(f.createIRI("http://example.org/people/alice"), f.createIRI("http://example.org/ontology/name"), @@ -89,7 +89,7 @@ public void testRemoveOptimisticIsolation() throws Exception { } @Test - public void testRemoveIsolation() throws Exception { + public void testRemoveIsolation() { con.begin(level); con.add(f.createIRI("http://example.org/people/alice"), f.createIRI("http://example.org/ontology/name"), diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/SerializableTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/SerializableTest.java index cf2748ac918..8889c6d39fb 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/SerializableTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/SerializableTest.java @@ -47,12 +47,12 @@ public class SerializableTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -123,7 +123,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { a.close(); } finally { @@ -136,7 +136,7 @@ public void tearDown() throws Exception { } @Test - public void test_independentPattern() throws Exception { + public void test_independentPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -150,7 +150,7 @@ public void test_independentPattern() throws Exception { } @Test - public void test_safePattern() throws Exception { + public void test_safePattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -161,7 +161,7 @@ public void test_safePattern() throws Exception { } @Test - public void testPrepare_safePattern() throws Exception { + public void testPrepare_safePattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -172,7 +172,7 @@ public void testPrepare_safePattern() throws Exception { } @Test - public void test_afterPattern() throws Exception { + public void test_afterPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -184,7 +184,7 @@ public void test_afterPattern() throws Exception { } @Test - public void test_afterInsertDataPattern() throws Exception { + public void test_afterInsertDataPattern() { a.begin(level); b.begin(level); a.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { a }", NS).execute(); @@ -196,7 +196,7 @@ public void test_afterInsertDataPattern() throws Exception { } @Test - public void test_conflictPattern() throws Exception { + public void test_conflictPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -215,7 +215,7 @@ public void test_conflictPattern() throws Exception { } @Test - public void testPrepare_conflictPattern() throws Exception { + public void testPrepare_conflictPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -234,7 +234,7 @@ public void testPrepare_conflictPattern() throws Exception { } @Test - public void test_safeQuery() throws Exception { + public void test_safeQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -256,7 +256,7 @@ public void test_safeQuery() throws Exception { } @Test - public void test_safeInsert() throws Exception { + public void test_safeInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -275,7 +275,7 @@ public void test_safeInsert() throws Exception { } @Test - public void test_conflictQuery() throws Exception { + public void test_conflictQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -305,7 +305,7 @@ public void test_conflictQuery() throws Exception { } @Test - public void test_conflictInsert() throws Exception { + public void test_conflictInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -333,7 +333,7 @@ public void test_conflictInsert() throws Exception { } @Test - public void test_safeOptionalQuery() throws Exception { + public void test_safeOptionalQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -357,7 +357,7 @@ public void test_safeOptionalQuery() throws Exception { } @Test - public void test_safeOptionalInsert() throws Exception { + public void test_safeOptionalInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -376,7 +376,7 @@ public void test_safeOptionalInsert() throws Exception { } @Test - public void test_conflictOptionalQuery() throws Exception { + public void test_conflictOptionalQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -408,7 +408,7 @@ public void test_conflictOptionalQuery() throws Exception { } @Test - public void test_conflictOptionalInsert() throws Exception { + public void test_conflictOptionalInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -436,7 +436,7 @@ public void test_conflictOptionalInsert() throws Exception { } @Test - public void test_safeFilterQuery() throws Exception { + public void test_safeFilterQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -466,7 +466,7 @@ public void test_safeFilterQuery() throws Exception { } @Test - public void test_safeFilterInsert() throws Exception { + public void test_safeFilterInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -494,7 +494,7 @@ public void test_safeFilterInsert() throws Exception { } @Test - public void test_conflictOptionalFilterQuery() throws Exception { + public void test_conflictOptionalFilterQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -527,7 +527,7 @@ public void test_conflictOptionalFilterQuery() throws Exception { } @Test - public void test_conflictOptionalFilterInsert() throws Exception { + public void test_conflictOptionalFilterInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -558,7 +558,7 @@ public void test_conflictOptionalFilterInsert() throws Exception { } @Test - public void test_safeRangeQuery() throws Exception { + public void test_safeRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, ARTEMISIA); a.add(REMBRANDT, PAINTS, DANAE); @@ -594,7 +594,7 @@ public void test_safeRangeQuery() throws Exception { } @Test - public void test_safeRangeInsert() throws Exception { + public void test_safeRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, ARTEMISIA); a.add(REMBRANDT, PAINTS, DANAE); @@ -629,7 +629,7 @@ public void test_safeRangeInsert() throws Exception { } @Test - public void test_conflictRangeQuery() throws Exception { + public void test_conflictRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -665,7 +665,7 @@ public void test_conflictRangeQuery() throws Exception { } @Test - public void test_conflictRangeInsert() throws Exception { + public void test_conflictRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -700,12 +700,11 @@ public void test_conflictRangeInsert() throws Exception { assertEquals(13, size(a, null, null, null, false)); } - private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx) - throws Exception { + private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx) { return QueryResults.asList(con.getStatements(subj, pred, obj, inf, ctx)).size(); } - private List eval(String var, RepositoryConnection con, String qry) throws Exception { + private List eval(String var, RepositoryConnection con, String qry) { try (TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL, qry, NS).evaluate()) { List list = new ArrayList<>(); while (result.hasNext()) { diff --git a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/SnapshotTest.java b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/SnapshotTest.java index 4ab5de1dae6..0beb98f282f 100644 --- a/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/SnapshotTest.java +++ b/testsuites/repository/src/main/java/org/eclipse/rdf4j/testsuite/repository/optimistic/SnapshotTest.java @@ -40,12 +40,12 @@ public class SnapshotTest { @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -116,7 +116,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { a.close(); } finally { @@ -129,7 +129,7 @@ public void tearDown() throws Exception { } @Test - public void test_independentPattern() throws Exception { + public void test_independentPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -143,7 +143,7 @@ public void test_independentPattern() throws Exception { } @Test - public void test_safePattern() throws Exception { + public void test_safePattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -154,7 +154,7 @@ public void test_safePattern() throws Exception { } @Test - public void test_afterPattern() throws Exception { + public void test_afterPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -166,7 +166,7 @@ public void test_afterPattern() throws Exception { } @Test - public void test_afterInsertDataPattern() throws Exception { + public void test_afterInsertDataPattern() { a.begin(level); b.begin(level); a.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA { a }", NS).execute(); @@ -178,7 +178,7 @@ public void test_afterInsertDataPattern() throws Exception { } @Test - public void test_conflictPattern() throws Exception { + public void test_conflictPattern() { a.begin(level); b.begin(level); a.add(PICASSO, RDF.TYPE, PAINTER); @@ -196,7 +196,7 @@ public void test_conflictPattern() throws Exception { } @Test - public void test_safeQuery() throws Exception { + public void test_safeQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -217,7 +217,7 @@ public void test_safeQuery() throws Exception { } @Test - public void test_safeInsert() throws Exception { + public void test_safeInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -236,7 +236,7 @@ public void test_safeInsert() throws Exception { } @Test - public void test_mergeQuery() throws Exception { + public void test_mergeQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -258,7 +258,7 @@ public void test_mergeQuery() throws Exception { } @Test - public void test_mergeInsert() throws Exception { + public void test_mergeInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -278,7 +278,7 @@ public void test_mergeInsert() throws Exception { } @Test - public void test_conflictQuery() throws Exception { + public void test_conflictQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -307,7 +307,7 @@ public void test_conflictQuery() throws Exception { } @Test - public void test_conflictInsert() throws Exception { + public void test_conflictInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -334,7 +334,7 @@ public void test_conflictInsert() throws Exception { } @Test - public void test_safeOptionalQuery() throws Exception { + public void test_safeOptionalQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -358,7 +358,7 @@ public void test_safeOptionalQuery() throws Exception { } @Test - public void test_safeOptionalInsert() throws Exception { + public void test_safeOptionalInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -377,7 +377,7 @@ public void test_safeOptionalInsert() throws Exception { } @Test - public void test_mergeOptionalQuery() throws Exception { + public void test_mergeOptionalQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -402,7 +402,7 @@ public void test_mergeOptionalQuery() throws Exception { } @Test - public void test_mergeOptionalInsert() throws Exception { + public void test_mergeOptionalInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -422,7 +422,7 @@ public void test_mergeOptionalInsert() throws Exception { } @Test - public void test_conflictOptionalQuery() throws Exception { + public void test_conflictOptionalQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -454,7 +454,7 @@ public void test_conflictOptionalQuery() throws Exception { } @Test - public void test_conflictOptionalInsert() throws Exception { + public void test_conflictOptionalInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); @@ -481,7 +481,7 @@ public void test_conflictOptionalInsert() throws Exception { } @Test - public void test_safeFilterQuery() throws Exception { + public void test_safeFilterQuery() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -503,7 +503,7 @@ public void test_safeFilterQuery() throws Exception { } @Test - public void test_safeFilterInsert() throws Exception { + public void test_safeFilterInsert() { b.add(REMBRANDT, RDF.TYPE, PAINTER); b.add(REMBRANDT, PAINTS, NIGHTWATCH); b.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -523,7 +523,7 @@ public void test_safeFilterInsert() throws Exception { } @Test - public void test_mergeOptionalFilterQuery() throws Exception { + public void test_mergeOptionalFilterQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -549,7 +549,7 @@ public void test_mergeOptionalFilterQuery() throws Exception { } @Test - public void test_mergeOptionalFilterInsert() throws Exception { + public void test_mergeOptionalFilterInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -572,7 +572,7 @@ public void test_mergeOptionalFilterInsert() throws Exception { } @Test - public void test_conflictOptionalFilterQuery() throws Exception { + public void test_conflictOptionalFilterQuery() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -606,7 +606,7 @@ public void test_conflictOptionalFilterQuery() throws Exception { } @Test - public void test_conflictOptionalFilterInsert() throws Exception { + public void test_conflictOptionalFilterInsert() { a.add(PICASSO, RDF.TYPE, PAINTER); a.add(PICASSO, PAINTS, GUERNICA); a.add(PICASSO, PAINTS, JACQUELINE); @@ -636,7 +636,7 @@ public void test_conflictOptionalFilterInsert() throws Exception { } @Test - public void test_safeRangeQuery() throws Exception { + public void test_safeRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, ARTEMISIA); a.add(REMBRANDT, PAINTS, DANAE); @@ -664,7 +664,7 @@ public void test_safeRangeQuery() throws Exception { } @Test - public void test_safeRangeInsert() throws Exception { + public void test_safeRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, ARTEMISIA); a.add(REMBRANDT, PAINTS, DANAE); @@ -691,7 +691,7 @@ public void test_safeRangeInsert() throws Exception { } @Test - public void test_mergeRangeQuery() throws Exception { + public void test_mergeRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -720,7 +720,7 @@ public void test_mergeRangeQuery() throws Exception { } @Test - public void test_mergeRangeInsert() throws Exception { + public void test_mergeRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -748,7 +748,7 @@ public void test_mergeRangeInsert() throws Exception { } @Test - public void test_conflictRangeQuery() throws Exception { + public void test_conflictRangeQuery() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -784,7 +784,7 @@ public void test_conflictRangeQuery() throws Exception { } @Test - public void test_conflictRangeInsert() throws Exception { + public void test_conflictRangeInsert() { a.add(REMBRANDT, RDF.TYPE, PAINTER); a.add(REMBRANDT, PAINTS, NIGHTWATCH); a.add(REMBRANDT, PAINTS, ARTEMISIA); @@ -818,12 +818,11 @@ public void test_conflictRangeInsert() throws Exception { } } - private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx) - throws Exception { + private int size(RepositoryConnection con, Resource subj, IRI pred, Value obj, boolean inf, Resource... ctx) { return QueryResults.asList(con.getStatements(subj, pred, obj, inf, ctx)).size(); } - private List eval(String var, RepositoryConnection con, String qry) throws Exception { + private List eval(String var, RepositoryConnection con, String qry) { TupleQueryResult result; result = con.prepareTupleQuery(QueryLanguage.SPARQL, qry, NS).evaluate(); try { diff --git a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/NegativeParserTest.java b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/NegativeParserTest.java index 9c4788491c0..ea115c24dc6 100644 --- a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/NegativeParserTest.java +++ b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/NegativeParserTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.testsuite.rio; import java.io.InputStream; -import java.net.MalformedURLException; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.rio.RDFParseException; @@ -47,7 +46,7 @@ public class NegativeParserTest extends TestCase { *--------------*/ public NegativeParserTest(IRI testUri, String caseURI, String inputURL, String baseURL, RDFParser targetParser, - FailureMode failureMode) throws MalformedURLException { + FailureMode failureMode) { super(caseURI); this.testUri = testUri; this.inputURL = inputURL; diff --git a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/PositiveParserTest.java b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/PositiveParserTest.java index 3b62e7ec9bd..9a99761de8e 100644 --- a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/PositiveParserTest.java +++ b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/PositiveParserTest.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.testsuite.rio; import java.io.InputStream; -import java.net.MalformedURLException; import java.util.LinkedHashSet; import java.util.Set; @@ -51,7 +50,7 @@ public class PositiveParserTest extends TestCase { *--------------*/ public PositiveParserTest(IRI testUri, String testName, String inputURL, String outputURL, String baseURL, - RDFParser targetParser, RDFParser ntriplesParser) throws MalformedURLException { + RDFParser targetParser, RDFParser ntriplesParser) { super(testName); this.testUri = testUri; this.inputURL = inputURL; diff --git a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/nquads/AbstractNQuadsParserTest.java b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/nquads/AbstractNQuadsParserTest.java index 6a436b40f4a..92ea98419f0 100644 --- a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/nquads/AbstractNQuadsParserTest.java +++ b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/nquads/AbstractNQuadsParserTest.java @@ -73,7 +73,7 @@ public TestSuite createTestSuite() throws Exception { } private void parsePositiveNQuadsSyntaxTests(TestSuite suite, String fileBasePath, String testLocationBaseUri, - RepositoryConnection con) throws Exception { + RepositoryConnection con) { StringBuilder positiveQuery = new StringBuilder(); positiveQuery.append(" PREFIX mf: \n"); positiveQuery.append(" PREFIX qt: \n"); @@ -106,7 +106,7 @@ private void parsePositiveNQuadsSyntaxTests(TestSuite suite, String fileBasePath } private void parseNegativeNQuadsSyntaxTests(TestSuite suite, String fileBasePath, String testLocationBaseUri, - RepositoryConnection con) throws Exception { + RepositoryConnection con) { StringBuilder negativeQuery = new StringBuilder(); negativeQuery.append(" PREFIX mf: \n"); negativeQuery.append(" PREFIX qt: \n"); diff --git a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/ntriples/AbstractNTriplesParserTest.java b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/ntriples/AbstractNTriplesParserTest.java index 82911fa69ee..82cb99d5fc3 100644 --- a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/ntriples/AbstractNTriplesParserTest.java +++ b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/ntriples/AbstractNTriplesParserTest.java @@ -73,7 +73,7 @@ public TestSuite createTestSuite() throws Exception { } private void parsePositiveNTriplesSyntaxTests(TestSuite suite, String fileBasePath, String testLocationBaseUri, - RepositoryConnection con) throws Exception { + RepositoryConnection con) { StringBuilder positiveQuery = new StringBuilder(); positiveQuery.append(" PREFIX mf: \n"); positiveQuery.append(" PREFIX qt: \n"); @@ -106,7 +106,7 @@ private void parsePositiveNTriplesSyntaxTests(TestSuite suite, String fileBasePa } private void parseNegativeNTriplesSyntaxTests(TestSuite suite, String fileBasePath, String testLocationBaseUri, - RepositoryConnection con) throws Exception { + RepositoryConnection con) { StringBuilder negativeQuery = new StringBuilder(); negativeQuery.append(" PREFIX mf: \n"); negativeQuery.append(" PREFIX qt: \n"); diff --git a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/rdfjson/RDFJSONParserTestCase.java b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/rdfjson/RDFJSONParserTestCase.java index 856cf4a8959..4462254c663 100644 --- a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/rdfjson/RDFJSONParserTestCase.java +++ b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/rdfjson/RDFJSONParserTestCase.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.testsuite.rio.rdfjson; import java.io.InputStream; -import java.net.MalformedURLException; import java.util.LinkedHashSet; import java.util.Set; @@ -176,8 +175,7 @@ private class PositiveParserTest extends TestCase { * Constructors * *--------------*/ - public PositiveParserTest(String testName, String inputURL, String outputURL, String baseURL) - throws MalformedURLException { + public PositiveParserTest(String testName, String inputURL, String outputURL, String baseURL) { super(testName); this.inputURL = inputURL; if (outputURL != null) { @@ -256,7 +254,7 @@ private class NegativeParserTest extends TestCase { * Constructors * *--------------*/ - public NegativeParserTest(String caseURI, String inputURL, String baseURL) throws MalformedURLException { + public NegativeParserTest(String caseURI, String inputURL, String baseURL) { super(caseURI); this.inputURL = inputURL; this.baseURL = baseURL; diff --git a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/rdfxml/RDFXMLParserTestCase.java b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/rdfxml/RDFXMLParserTestCase.java index 8d601f450b0..52fc5b14d91 100644 --- a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/rdfxml/RDFXMLParserTestCase.java +++ b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/rdfxml/RDFXMLParserTestCase.java @@ -261,7 +261,7 @@ private static class CanonXMLValueFactory extends SimpleValueFactory { private final Canonicalizer c14n; - public CanonXMLValueFactory() throws InvalidCanonicalizerException, ParserConfigurationException { + public CanonXMLValueFactory() throws InvalidCanonicalizerException { org.apache.xml.security.Init.init(); c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); diff --git a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/trig/TriGParserTestCase.java b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/trig/TriGParserTestCase.java index 4b1ee2418a8..866a3f37901 100644 --- a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/trig/TriGParserTestCase.java +++ b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/trig/TriGParserTestCase.java @@ -88,7 +88,7 @@ public TestSuite createTestSuite() throws Exception { } private void parsePositiveTriGSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String testLocationBaseUri, RepositoryConnection con) throws Exception { + String testLocationBaseUri, RepositoryConnection con) { StringBuilder positiveQuery = new StringBuilder(); positiveQuery.append(" PREFIX mf: \n"); positiveQuery.append(" PREFIX qt: \n"); @@ -121,7 +121,7 @@ private void parsePositiveTriGSyntaxTests(TestSuite suite, String fileBasePath, } private void parseNegativeTriGSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String manifestBaseUrl, RepositoryConnection con) throws Exception { + String manifestBaseUrl, RepositoryConnection con) { StringBuilder negativeQuery = new StringBuilder(); negativeQuery.append(" PREFIX mf: \n"); negativeQuery.append(" PREFIX qt: \n"); @@ -154,7 +154,7 @@ private void parseNegativeTriGSyntaxTests(TestSuite suite, String fileBasePath, } private void parsePositiveTriGEvalTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String manifestBaseUrl, RepositoryConnection con) throws Exception { + String manifestBaseUrl, RepositoryConnection con) { StringBuilder positiveEvalQuery = new StringBuilder(); positiveEvalQuery.append(" PREFIX mf: \n"); positiveEvalQuery.append(" PREFIX qt: \n"); @@ -202,7 +202,7 @@ private void parsePositiveTriGEvalTests(TestSuite suite, String fileBasePath, St } private void parseNegativeTriGEvalTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String manifestBaseUrl, RepositoryConnection con) throws Exception { + String manifestBaseUrl, RepositoryConnection con) { StringBuilder negativeEvalQuery = new StringBuilder(); negativeEvalQuery.append(" PREFIX mf: \n"); negativeEvalQuery.append(" PREFIX qt: \n"); diff --git a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/turtle/TurtleParserTestCase.java b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/turtle/TurtleParserTestCase.java index b903cc9283b..f6c7268a91f 100644 --- a/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/turtle/TurtleParserTestCase.java +++ b/testsuites/rio/src/main/java/org/eclipse/rdf4j/testsuite/rio/turtle/TurtleParserTestCase.java @@ -102,7 +102,7 @@ public TestSuite createTestSuite() throws Exception { } private void parsePositiveTurtleSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String testLocationBaseUri, RepositoryConnection con) throws Exception { + String testLocationBaseUri, RepositoryConnection con) { StringBuilder positiveQuery = new StringBuilder(); positiveQuery.append(" PREFIX mf: \n"); positiveQuery.append(" PREFIX qt: \n"); @@ -135,7 +135,7 @@ private void parsePositiveTurtleSyntaxTests(TestSuite suite, String fileBasePath } private void parseNegativeTurtleSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String manifestBaseUrl, RepositoryConnection con) throws Exception { + String manifestBaseUrl, RepositoryConnection con) { StringBuilder negativeQuery = new StringBuilder(); negativeQuery.append(" PREFIX mf: \n"); negativeQuery.append(" PREFIX qt: \n"); @@ -168,7 +168,7 @@ private void parseNegativeTurtleSyntaxTests(TestSuite suite, String fileBasePath } private void parsePositiveTurtleEvalTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String manifestBaseUrl, RepositoryConnection con) throws Exception { + String manifestBaseUrl, RepositoryConnection con) { StringBuilder positiveEvalQuery = new StringBuilder(); positiveEvalQuery.append(" PREFIX mf: \n"); positiveEvalQuery.append(" PREFIX qt: \n"); @@ -211,7 +211,7 @@ private void parsePositiveTurtleEvalTests(TestSuite suite, String fileBasePath, } private void parseNegativeTurtleEvalTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String manifestBaseUrl, RepositoryConnection con) throws Exception { + String manifestBaseUrl, RepositoryConnection con) { StringBuilder negativeEvalQuery = new StringBuilder(); negativeEvalQuery.append(" PREFIX mf: \n"); negativeEvalQuery.append(" PREFIX qt: \n"); @@ -244,7 +244,7 @@ private void parseNegativeTurtleEvalTests(TestSuite suite, String fileBasePath, } private void parsePositiveNTriplesSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String manifestBaseUrl, RepositoryConnection con) throws Exception { + String manifestBaseUrl, RepositoryConnection con) { StringBuilder positiveQuery = new StringBuilder(); positiveQuery.append(" PREFIX mf: \n"); positiveQuery.append(" PREFIX qt: \n"); @@ -277,7 +277,7 @@ private void parsePositiveNTriplesSyntaxTests(TestSuite suite, String fileBasePa } private void parseNegativeNTriplesSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl, - String manifestBaseUrl, RepositoryConnection con) throws Exception { + String manifestBaseUrl, RepositoryConnection con) { StringBuilder negativeQuery = new StringBuilder(); negativeQuery.append(" PREFIX mf: \n"); negativeQuery.append(" PREFIX qt: \n"); diff --git a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/EvaluationStrategyTest.java b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/EvaluationStrategyTest.java index 10ebbc33316..542304f0e80 100644 --- a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/EvaluationStrategyTest.java +++ b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/EvaluationStrategyTest.java @@ -49,12 +49,12 @@ public abstract class EvaluationStrategyTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterAll - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } @@ -73,10 +73,9 @@ public static void afterClass() throws Exception { private IRI s2 = iri("urn:s2"); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { manager = RepositoryProvider.getRepositoryManager(tempDir); BaseSailConfig strictStoreConfig = getBaseSailConfig(); diff --git a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/InferencingTest.java b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/InferencingTest.java index 24b7325c67b..b4b69c17ca0 100644 --- a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/InferencingTest.java +++ b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/InferencingTest.java @@ -41,12 +41,12 @@ public abstract class InferencingTest { private static final Logger logger = LoggerFactory.getLogger(InferencingTest.class); @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @AfterAll - public static void afterClass() throws Exception { + public static void afterClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } /*-----------* diff --git a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/RDFNotifyingStoreTest.java b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/RDFNotifyingStoreTest.java index 908697a4ad0..9f15fd3d9d0 100644 --- a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/RDFNotifyingStoreTest.java +++ b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/RDFNotifyingStoreTest.java @@ -51,14 +51,14 @@ public abstract class RDFNotifyingStoreTest extends RDFStoreTest implements Sail protected abstract NotifyingSail createSail() throws SailException; @BeforeEach - public void addSailChangedListener() throws Exception { + public void addSailChangedListener() { // set self as listener ((NotifyingSail) sail).addSailChangedListener(this); } @Test - public void testNotifyingRemoveAndClear() throws Exception { + public void testNotifyingRemoveAndClear() { // Add some data to the repository con.begin(); con.addStatement(painter, RDF.TYPE, RDFS.CLASS); diff --git a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/RDFStoreTest.java b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/RDFStoreTest.java index 3e9672f906b..47549df7572 100644 --- a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/RDFStoreTest.java +++ b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/RDFStoreTest.java @@ -69,7 +69,7 @@ public abstract class RDFStoreTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @@ -149,7 +149,7 @@ public RDFStoreTest() { protected abstract Sail createSail(); @BeforeEach - public void setUp() throws Exception { + public void setUp() { sail = createSail(); con = sail.getConnection(); @@ -171,7 +171,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { try { if (con.isOpen()) { try { @@ -189,7 +189,7 @@ public void tearDown() throws Exception { } @Test - public void testEmptyRepository() throws Exception { + public void testEmptyRepository() { // repository should be empty assertEquals(0, countAllElements(), "Empty repository should not return any statements"); @@ -203,7 +203,7 @@ public void testEmptyRepository() throws Exception { } @Test - public void testValueRoundTrip1() throws Exception { + public void testValueRoundTrip1() { IRI subj = vf.createIRI(EXAMPLE_NS + PICASSO); IRI pred = vf.createIRI(EXAMPLE_NS + PAINTS); IRI obj = vf.createIRI(EXAMPLE_NS + GUERNICA); @@ -212,7 +212,7 @@ public void testValueRoundTrip1() throws Exception { } @Test - public void testValueRoundTrip2() throws Exception { + public void testValueRoundTrip2() { BNode subj = vf.createBNode(); IRI pred = vf.createIRI(EXAMPLE_NS + PAINTS); IRI obj = vf.createIRI(EXAMPLE_NS + GUERNICA); @@ -221,7 +221,7 @@ public void testValueRoundTrip2() throws Exception { } @Test - public void testValueRoundTrip3() throws Exception { + public void testValueRoundTrip3() { IRI subj = vf.createIRI(EXAMPLE_NS + PICASSO); IRI pred = vf.createIRI(EXAMPLE_NS + PAINTS); Literal obj = vf.createLiteral("guernica"); @@ -230,7 +230,7 @@ public void testValueRoundTrip3() throws Exception { } @Test - public void testValueRoundTrip4() throws Exception { + public void testValueRoundTrip4() { IRI subj = vf.createIRI(EXAMPLE_NS + PICASSO); IRI pred = vf.createIRI(EXAMPLE_NS + PAINTS); Literal obj = vf.createLiteral("guernica", "es"); @@ -239,7 +239,7 @@ public void testValueRoundTrip4() throws Exception { } @Test - public void testValueRoundTrip5() throws Exception { + public void testValueRoundTrip5() { IRI subj = vf.createIRI(EXAMPLE_NS + PICASSO); IRI pred = vf.createIRI(EXAMPLE_NS + PAINTS); Literal obj = vf.createLiteral(3); @@ -248,7 +248,7 @@ public void testValueRoundTrip5() throws Exception { } @Test - public void testDecimalRoundTrip() throws Exception { + public void testDecimalRoundTrip() { IRI subj = vf.createIRI(EXAMPLE_NS + PICASSO); IRI pred = vf.createIRI(EXAMPLE_NS + PAINTS); Literal obj = vf.createLiteral("3", XSD.DECIMAL); @@ -257,7 +257,7 @@ public void testDecimalRoundTrip() throws Exception { } @Test - public void testTimeZoneRoundTrip() throws Exception { + public void testTimeZoneRoundTrip() { IRI subj = vf.createIRI(EXAMPLE_NS + PICASSO); IRI pred = vf.createIRI(EXAMPLE_NS + PAINTS); Literal obj = vf.createLiteral("2006-08-23+00:00", CoreDatatype.XSD.DATE); @@ -272,7 +272,7 @@ public void testTimeZoneRoundTrip() throws Exception { } @Test - public void testLongURIRoundTrip() throws Exception { + public void testLongURIRoundTrip() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 512; i++) { sb.append(Character.toChars('A' + (i % 26))); @@ -285,7 +285,7 @@ public void testLongURIRoundTrip() throws Exception { } @Test - public void testLongLiteralRoundTrip() throws Exception { + public void testLongLiteralRoundTrip() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 512; i++) { sb.append(Character.toChars('A' + (i % 26))); @@ -298,7 +298,7 @@ public void testLongLiteralRoundTrip() throws Exception { } @Test - public void testReallyLongLiteralRoundTrip() throws Exception { + public void testReallyLongLiteralRoundTrip() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1024000; i++) { sb.append(Character.toChars('A' + (i % 26))); @@ -311,7 +311,7 @@ public void testReallyLongLiteralRoundTrip() throws Exception { } @Test - public void testLongLangRoundTrip() throws Exception { + public void testLongLangRoundTrip() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 512; i++) { sb.append(Character.toChars('A' + (i % 26))); @@ -328,7 +328,7 @@ private void testValueRoundTrip(Resource subj, IRI pred, Value obj) { con.addStatement(subj, pred, obj); con.commit(); - try (CloseableIteration stIter = con.getStatements(null, null, null, + try (CloseableIteration stIter = con.getStatements(null, null, null, false)) { assertTrue(stIter.hasNext()); @@ -342,7 +342,7 @@ private void testValueRoundTrip(Resource subj, IRI pred, Value obj) { ParsedTupleQuery tupleQuery = QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, "SELECT * WHERE { ?S ?P ?O. FILTER(?P = <" + pred.stringValue() + ">)}", null); - CloseableIteration iter; + CloseableIteration iter; iter = con.evaluate(tupleQuery.getTupleExpr(), null, EmptyBindingSet.getInstance(), false); try { @@ -416,7 +416,7 @@ public void testSize() { } @Test - public void testAddData() throws Exception { + public void testAddData() { // Add some data to the repository con.begin(); con.addStatement(painter, RDF.TYPE, RDFS.CLASS); @@ -504,7 +504,7 @@ public void testAddWhileQuerying() { ParsedTupleQuery tupleQuery = QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, "SELECT ?C WHERE { [] a ?C }", null); - CloseableIteration iter; + CloseableIteration iter; iter = con.evaluate(tupleQuery.getTupleExpr(), null, EmptyBindingSet.getInstance(), false); con.begin(); @@ -539,7 +539,7 @@ public void testAddWhileQuerying() { } @Test - public void testRemoveAndClear() throws Exception { + public void testRemoveAndClear() { // Add some data to the repository con.begin(); con.addStatement(painter, RDF.TYPE, RDFS.CLASS); @@ -589,7 +589,7 @@ public void testClose() { } @Test - public void testContexts() throws Exception { + public void testContexts() { con.begin(); // Add schema data to the repository, no context con.addStatement(painter, RDF.TYPE, RDFS.CLASS); @@ -659,7 +659,7 @@ public void testQueryBindings() { TupleExpr tupleExpr = tupleQuery.getTupleExpr(); MapBindingSet bindings = new MapBindingSet(2); - CloseableIteration iter; + CloseableIteration iter; iter = con.evaluate(tupleExpr, null, bindings, false); int resultCount = verifyQueryResult(iter, 1); @@ -727,7 +727,7 @@ public void testGetNamespaces() { con.setNamespace("rdf", RDF.NAMESPACE); con.commit(); - try (CloseableIteration namespaces = con.getNamespaces()) { + try (CloseableIteration namespaces = con.getNamespaces()) { assertTrue(namespaces.hasNext()); Namespace rdf = namespaces.next(); assertEquals("rdf", rdf.getPrefix()); @@ -755,7 +755,7 @@ public void testClearNamespaces() { } @Test - public void testRemoveNamespaces() throws Exception { + public void testRemoveNamespaces() { con.begin(); con.setNamespace("rdf", RDF.NAMESPACE); con.removeNamespace("rdf"); @@ -819,7 +819,7 @@ public void testGetContextIDs() { } @Test - public void testOldURI() throws Exception { + public void testOldURI() { assertEquals(0, countAllElements()); con.begin(); con.addStatement(painter, RDF.TYPE, RDFS.CLASS); @@ -962,7 +962,7 @@ public void testDuplicateCountMultipleTimes() { con.commit(); } - private T first(CloseableIteration iter) throws X { + private T first(CloseableIteration iter) throws X { try (iter) { if (iter.hasNext()) { return iter.next(); @@ -980,7 +980,7 @@ protected int countAllElements() { return countElements(con.getStatements(null, null, null, false)); } - private int countElements(CloseableIteration iter) throws X { + private int countElements(CloseableIteration iter) throws X { int count = 0; try (iter) { @@ -1000,7 +1000,7 @@ protected int countQueryResults(String query) { return countElements(con.evaluate(tupleQuery.getTupleExpr(), null, EmptyBindingSet.getInstance(), false)); } - private int verifyQueryResult(CloseableIteration resultIter, + private int verifyQueryResult(CloseableIteration resultIter, int expectedBindingCount) throws QueryEvaluationException { int resultCount = 0; diff --git a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailConcurrencyTest.java b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailConcurrencyTest.java index 796a5499a1e..0823aab17e3 100644 --- a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailConcurrencyTest.java +++ b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailConcurrencyTest.java @@ -75,7 +75,7 @@ public abstract class SailConcurrencyTest { *---------*/ @BeforeEach - public void setUp() throws Exception { + public void setUp() { store = createSail(); store.init(); vf = store.getValueFactory(); @@ -84,7 +84,7 @@ public void setUp() throws Exception { protected abstract Sail createSail() throws SailException; @AfterEach - public void tearDown() throws Exception { + public void tearDown() { store.shutDown(); } @@ -269,7 +269,7 @@ public void testGetContextIDs() throws Exception { try { try (SailConnection connection = store.getConnection()) { while (continueRunning) { - try (CloseableIteration contextIter = connection + try (CloseableIteration contextIter = connection .getContextIDs()) { while (contextIter.hasNext()) { Resource context = contextIter.next(); diff --git a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailInterruptTest.java b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailInterruptTest.java index 09bbbff442e..a1f6ea127f9 100644 --- a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailInterruptTest.java +++ b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailInterruptTest.java @@ -35,7 +35,7 @@ public abstract class SailInterruptTest { @BeforeAll - public static void setUpClass() throws Exception { + public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } @@ -49,7 +49,7 @@ public static void afterClass() throws Exception { private ValueFactory vf; @BeforeEach - public void setUp() throws Exception { + public void setUp() { store = createSail(); store.init(); vf = store.getValueFactory(); @@ -58,7 +58,7 @@ public void setUp() throws Exception { protected abstract Sail createSail() throws SailException; @AfterEach - public void tearDown() throws Exception { + public void tearDown() { store.shutDown(); } @@ -118,7 +118,7 @@ private void insertTestStatement(SailConnection connection, int seed) throws Sai private void iterateStatements() throws SailException { try (SailConnection con = store.getConnection(); - CloseableIteration iter = con.getStatements(null, null, null, true)) { + CloseableIteration iter = con.getStatements(null, null, null, true)) { while (iter.hasNext()) { iter.next(); } diff --git a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailIsolationLevelTest.java b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailIsolationLevelTest.java index 342b40087a8..47b4f201b3f 100644 --- a/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailIsolationLevelTest.java +++ b/testsuites/sail/src/main/java/org/eclipse/rdf4j/testsuite/sail/SailIsolationLevelTest.java @@ -82,7 +82,7 @@ public static void afterClass() { *---------*/ @BeforeEach - public void setUp() throws Exception { + public void setUp() { store = createSail(); store.init(); vf = store.getValueFactory(); @@ -90,7 +90,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { store.shutDown(); } @@ -110,12 +110,12 @@ protected boolean isSupported(IsolationLevels level) throws SailException { } @Test - public void testNone() throws Exception { + public void testNone() { readPending(IsolationLevels.NONE); } @Test - public void testReadUncommitted() throws Exception { + public void testReadUncommitted() { rollbackTriple(IsolationLevels.READ_UNCOMMITTED); readPending(IsolationLevels.READ_UNCOMMITTED); readPendingWhileActive(IsolationLevels.READ_UNCOMMITTED); @@ -301,7 +301,7 @@ private void readPendingWhileActive(IsolationLevel level) throws SailException { try (SailConnection con = store.getConnection()) { // open an iteration outside the transaction and leave it open while another transaction is begun and // committed - try (CloseableIteration unusedStatements = con.getStatements(null, null, + try (CloseableIteration unusedStatements = con.getStatements(null, null, null, true)) { con.begin(level); con.addStatement(RDF.NIL, RDF.TYPE, RDF.LIST); @@ -450,7 +450,7 @@ private void snapshotRead(IsolationLevel level) throws SailException { insertTestStatement(con, i); } int counter = 0; - try (CloseableIteration stmts = con.getStatements(null, null, null, + try (CloseableIteration stmts = con.getStatements(null, null, null, false)) { while (stmts.hasNext()) { Statement st = stmts.next(); @@ -603,7 +603,7 @@ private void clear(Sail store) throws SailException { protected long count(SailConnection con, Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { - try (CloseableIteration stmts = con.getStatements(subj, pred, obj, + try (CloseableIteration stmts = con.getStatements(subj, pred, obj, includeInferred, contexts)) { long counter = 0; while (stmts.hasNext()) { @@ -615,7 +615,7 @@ protected long count(SailConnection con, Resource subj, IRI pred, Value obj, boo } protected Literal readLiteral(SailConnection con, final IRI subj, final IRI pred) throws SailException { - try (CloseableIteration stmts = con.getStatements(subj, pred, null, + try (CloseableIteration stmts = con.getStatements(subj, pred, null, false)) { if (!stmts.hasNext()) { return null; diff --git a/testsuites/shacl/src/main/java/org/eclipse/rdf4j/testsuite/shacl/manifest/AbstractSHACLTest.java b/testsuites/shacl/src/main/java/org/eclipse/rdf4j/testsuite/shacl/manifest/AbstractSHACLTest.java index 4785051bcae..145b988385c 100644 --- a/testsuites/shacl/src/main/java/org/eclipse/rdf4j/testsuite/shacl/manifest/AbstractSHACLTest.java +++ b/testsuites/shacl/src/main/java/org/eclipse/rdf4j/testsuite/shacl/manifest/AbstractSHACLTest.java @@ -78,11 +78,11 @@ public AbstractSHACLTest(String testURI, String label, Model shapesGraph, Model *---------*/ @Override - public void setUp() throws Exception { + public void setUp() { dataRep = createRepository(shapesGraph); } - protected Repository createRepository(Model shapesGraph) throws Exception { + protected Repository createRepository(Model shapesGraph) { Repository repo = new SailRepository(newSail()); try (RepositoryConnection conn = repo.getConnection()) { conn.clear(); @@ -100,7 +100,7 @@ protected Repository createRepository(Model shapesGraph) throws Exception { protected abstract Sail newSail(); @Override - public void tearDown() throws Exception { + public void tearDown() { if (dataRep != null) { dataRep.shutDown(); dataRep = null; @@ -108,7 +108,7 @@ public void tearDown() throws Exception { } @Override - public void runTest() throws Exception { + public void runTest() { try { upload(dataRep, dataGraph); assertTrue(conforms); diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/ComplexSPARQLQueryTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/ComplexSPARQLQueryTest.java deleted file mode 100644 index fe17a28ef5d..00000000000 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/ComplexSPARQLQueryTest.java +++ /dev/null @@ -1,2624 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.testsuite.query.parser.sparql; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.eclipse.rdf4j.model.util.Statements.statement; -import static org.eclipse.rdf4j.model.util.Values.iri; -import static org.eclipse.rdf4j.model.util.Values.literal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.util.List; -import java.util.Set; -import java.util.stream.Stream; - -import org.eclipse.rdf4j.model.BNode; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Literal; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.base.CoreDatatype; -import org.eclipse.rdf4j.model.vocabulary.DCAT; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.model.vocabulary.FOAF; -import org.eclipse.rdf4j.model.vocabulary.OWL; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.eclipse.rdf4j.model.vocabulary.RDFS; -import org.eclipse.rdf4j.model.vocabulary.SESAME; -import org.eclipse.rdf4j.model.vocabulary.XSD; -import org.eclipse.rdf4j.query.AbstractTupleQueryResultHandler; -import org.eclipse.rdf4j.query.Binding; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.GraphQuery; -import org.eclipse.rdf4j.query.GraphQueryResult; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.QueryLanguage; -import org.eclipse.rdf4j.query.QueryResults; -import org.eclipse.rdf4j.query.TupleQuery; -import org.eclipse.rdf4j.query.TupleQueryResult; -import org.eclipse.rdf4j.query.impl.MapBindingSet; -import org.eclipse.rdf4j.query.impl.SimpleBinding; -import org.eclipse.rdf4j.query.impl.SimpleDataset; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.rio.RDFFormat; -import org.eclipse.rdf4j.rio.RDFParseException; -import org.eclipse.rdf4j.rio.Rio; -import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQL11ManifestTest; -import org.eclipse.rdf4j.testsuite.sparql.RepositorySPARQLComplianceTestSuite; -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.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A set of compliance tests on SPARQL query functionality which can not be easily executed using the - * {@link SPARQL11ManifestTest} format. This includes tests on queries with non-deterministic output (e.g. - * GROUP_CONCAT). - * - * @deprecated use {@link RepositorySPARQLComplianceTestSuite} instead. - * @author Jeen Broekstra - */ -@Deprecated(since = "4.0.2", forRemoval = true) -public abstract class ComplexSPARQLQueryTest { - - @BeforeAll - public static void setUpClass() { - System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); - } - - @AfterAll - public static void afterClass() throws Exception { - System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); - } - - protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private Repository rep; - - protected RepositoryConnection conn; - - protected ValueFactory f; - - protected static final String EX_NS = "http://example.org/"; - - private IRI bob; - - private IRI alice; - - private IRI mary; - - /** - * @throws java.lang.Exception - */ - @BeforeEach - public void setUp() throws Exception { - logger.debug("setting up test"); - this.rep = newRepository(); - - f = rep.getValueFactory(); - conn = rep.getConnection(); - - conn.clear(); // clear existing data from repo - - bob = f.createIRI(EX_NS, "bob"); - alice = f.createIRI(EX_NS, "alice"); - mary = f.createIRI(EX_NS, "mary"); - - logger.debug("test setup complete."); - } - - /** - * @throws java.lang.Exception - */ - @AfterEach - public void tearDown() throws Exception { - try { - if (conn != null) { - conn.close(); - } - } finally { - if (rep != null) { - rep.shutDown(); - } - } - } - - @Test - public void testNullContext1() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = " SELECT * " + - " FROM DEFAULT " + - " WHERE { ?s ?p ?o } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - Resource s = (Resource) bs.getValue("s"); - - assertNotNull(s); - assertNotEquals(bob, s); // should not be present in default - // graph - assertNotEquals(alice, s); // should not be present in - // default - // graph - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testSES2373SubselectOptional() { - conn.prepareUpdate(QueryLanguage.SPARQL, - "insert data {" + " ." + " 1 ." + " ." - + " ." + " 2 ." + " ." - + " ." + " 3 ." + " ." - + " ." + " 4 ." + " ." - + " ." + " 5 ." + " ." + "}") - .execute(); - - String qb = "select ?x { \n" + - " { select ?v { ?v filter (?v = ) } }.\n" + - " optional { select ?val { ?v ?val .} }\n" + - " ?v ?x \n" + - "}\n"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult result = tq.evaluate()) { - assertTrue("The query should return a result", result.hasNext()); - BindingSet b = result.next(); - assertTrue("?x is from the mandatory part of the query and should be bound", b.hasBinding("x")); - } - } - - @Test - public void testSES2154SubselectOptional() { - - String ub = "insert data { \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " \"01\" . \n" + - " \"02\" . \n" + - " \"03\" . \n" + - " \"04\" . \n" + - " \"05\" . \n" + - " \"06\" . \n" + - " \"07\" . \n" + - " \"08\" . \n" + - " \"09\" . \n" + - " \"10\" . \n" + - " \"11\" . \n" + - " \"12\" . \n" + - "} \n"; - - conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); - - String qb = "SELECT ?s ?label\n" + - "WHERE { \n" + - " ?s a \n .\n" + - " OPTIONAL { {SELECT ?label WHERE { \n" + - " ?s ?label . \n" + - " } ORDER BY ?label LIMIT 2 \n" + - " }\n" + - " }\n" + - "}\n" + - "ORDER BY ?s\n" + - "LIMIT 10 \n"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertTrue("The query should return a result", evaluate.hasNext()); - - List result = QueryResults.asList(evaluate); - assertEquals(10, result.size()); - for (BindingSet bs : result) { - Literal label = (Literal) bs.getValue("label"); - assertTrue("wrong label value (expected '01' or '02', but got '" + label.stringValue() + "')", - label.stringValue().equals("01") || label.stringValue().equals("02")); - } - } - } - - @Test - public void testNullContext2() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - " SELECT * " + - " FROM rdf4j:nil " + - " WHERE { ?s ?p ?o } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - Resource s = (Resource) bs.getValue("s"); - - assertNotNull(s); - assertNotEquals(bob, s); // should not be present in default - // graph - assertNotEquals(alice, s); // should not be present in - // default - // graph - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testSesameNilAsGraph() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - " SELECT * " + - " WHERE { GRAPH rdf4j:nil { ?s ?p ?o } } "; -// query.append(" WHERE { ?s ?p ?o } "); - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try { - List result = QueryResults.asList(tq.evaluate()); - - // nil graph should not be empty - assertThat(result.size()).isGreaterThan(1); - - for (BindingSet bs : result) { - Resource s = (Resource) bs.getValue("s"); - - assertNotNull(s); - assertThat(s).withFailMessage("%s should not be present in nil graph", bob).isNotEqualTo(bob); - assertThat(s).withFailMessage("%s should not be present in nil graph", alice).isNotEqualTo(alice); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testDescribeA() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:a"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI a = f.createIRI("http://example.org/a"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set objects = result.filter(a, p, null).objects(); - assertNotNull(objects); - for (Value object : objects) { - if (object instanceof BNode) { - assertTrue(result.contains((Resource) object, null, null)); - assertEquals(2, result.filter((Resource) object, null, null).size()); - } - } - } - } - - @Test - public void testDescribeAWhere() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI a = f.createIRI("http://example.org/a"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set objects = result.filter(a, p, null).objects(); - assertNotNull(objects); - for (Value object : objects) { - if (object instanceof BNode) { - assertTrue(result.contains((Resource) object, null, null)); - assertEquals(2, result.filter((Resource) object, null, null).size()); - } - } - } - } - - @Test - public void testDescribeWhere() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ?x WHERE {?x rdfs:label ?y . } "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI a = vf.createIRI("http://example.org/a"); - IRI b = vf.createIRI("http://example.org/b"); - IRI c = vf.createIRI("http://example.org/c"); - IRI e = vf.createIRI("http://example.org/e"); - IRI f = vf.createIRI("http://example.org/f"); - IRI p = vf.createIRI("http://example.org/p"); - - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - assertTrue(result.contains(a, p, null)); - assertTrue(result.contains(b, RDFS.LABEL, null)); - assertTrue(result.contains(c, RDFS.LABEL, null)); - assertTrue(result.contains(null, p, b)); - assertTrue(result.contains(e, RDFS.LABEL, null)); - assertTrue(result.contains(null, p, e)); - assertFalse(result.contains(f, null, null)); - Set objects = result.filter(a, p, null).objects(); - assertNotNull(objects); - for (Value object : objects) { - if (object instanceof BNode) { - assertTrue(result.contains((Resource) object, null, null)); - assertEquals(2, result.filter((Resource) object, null, null).size()); - } - } - } - } - - @Test - public void testDescribeB() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:b"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI b = f.createIRI("http://example.org/b"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set subjects = result.filter(null, p, b).subjects(); - assertNotNull(subjects); - for (Value subject : subjects) { - if (subject instanceof BNode) { - assertTrue(result.contains(null, null, subject)); - } - } - } - } - - @Test - public void testDescribeD() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:d"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI d = f.createIRI("http://example.org/d"); - IRI p = f.createIRI("http://example.org/p"); - IRI e = f.createIRI("http://example.org/e"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertNotNull(result); - assertTrue(result.contains(null, p, e)); - assertFalse(result.contains(e, null, null)); - Set objects = result.filter(d, p, null).objects(); - assertNotNull(objects); - for (Value object : objects) { - if (object instanceof BNode) { - Set childObjects = result.filter((BNode) object, null, null).objects(); - assertNotNull(childObjects); - for (Value childObject : childObjects) { - if (childObject instanceof BNode) { - assertTrue(result.contains((BNode) childObject, null, null)); - } - } - } - } - } - } - - @Test - public void testDescribeF() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:f"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI f = vf.createIRI("http://example.org/f"); - IRI p = vf.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertNotNull(result); - assertEquals(4, result.size()); - Set objects = result.filter(f, p, null).objects(); - assertNotNull(objects); - for (Value object : objects) { - if (object instanceof BNode) { - Set childObjects = result.filter((BNode) object, null, null).objects(); - assertNotNull(childObjects); - for (Value childObject : childObjects) { - if (childObject instanceof BNode) { - assertTrue(result.contains((BNode) childObject, null, null)); - } - } - } - } - } - } - - @Test - public void testDescribeMultipleA() { - String update = "insert data { . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + - "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); - - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - assertTrue(result.contains(urn1, p1, null)); - assertTrue(result.contains(null, blank, urn1)); - assertTrue(result.contains(urn2, p2, null)); - } - } - - @Test - public void testDescribeMultipleB() { - String update = "insert data { . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + - "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertTrue(result.contains(urn1, p1, null)); - assertTrue(result.contains(urn1, blank, null)); - assertTrue(result.contains(urn2, p2, null)); - } - } - - @Test - public void testDescribeMultipleC() { - String update = "insert data { . [] . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + - "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertTrue(result.contains(urn1, p1, null)); - assertTrue(result.contains(urn1, blank, null)); - assertTrue(result.contains(null, blank, urn1)); - assertTrue(result.contains(urn2, p2, null)); - } - } - - @Test - public void testDescribeMultipleD() { - String update = "insert data { . [] . . [] . . [] .} "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + - "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI urn4 = vf.createIRI("urn:4"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertTrue(result.contains(urn1, p1, null)); - assertTrue(result.contains(null, blank, urn1)); - assertTrue(result.contains(urn2, p2, null)); - assertTrue(result.contains(urn4, p2, null)); - assertTrue(result.contains(urn4, blank, null)); - } - } - - @Test - public void testGroupByEmpty() { - // see issue https://github.com/eclipse/rdf4j/issues/573 - String query = "select ?x where {?x ?p ?o} group by ?x"; - - TupleQuery tq = conn.prepareTupleQuery(query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); - } - } - - @Test - public void testGroupConcatDistinct() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - - String query = getNamespaceDeclarations() + - "SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)" + - "WHERE { ex:groupconcat-test ?p ?l . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - Value concat = bs.getValue("concat"); - - assertTrue(concat instanceof Literal); - - String lexValue = ((Literal) concat).getLabel(); - - int occ = countCharOccurrences(lexValue, 'a'); - assertEquals(1, occ); - occ = countCharOccurrences(lexValue, 'b'); - assertEquals(1, occ); - occ = countCharOccurrences(lexValue, 'c'); - assertEquals(1, occ); - occ = countCharOccurrences(lexValue, 'd'); - assertEquals(1, occ); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testSameTermRepeatInOptional() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - " SELECT ?l ?opt1 ?opt2 " + - " FROM ex:optional-sameterm-graph " + - " WHERE { " + - " ?s ex:p ex:A ; " + - " { " + - " { " + - " ?s ?p ?l ." + - " FILTER(?p = rdfs:label) " + - " } " + - " OPTIONAL { " + - " ?s ?p ?opt1 . " + - " FILTER (?p = ex:prop1) " + - " } " + - " OPTIONAL { " + - " ?s ?p ?opt2 . " + - " FILTER (?p = ex:prop2) " + - " } " + - " }" + - " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - // System.out.println(bs); - - Value l = bs.getValue("l"); - assertTrue(l instanceof Literal); - assertEquals("label", ((Literal) l).getLabel()); - - Value opt1 = bs.getValue("opt1"); - assertNull(opt1); - - Value opt2 = bs.getValue("opt2"); - assertNull(opt2); - } - assertEquals(1, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testSES1121VarNamesInOptionals() throws Exception { - // Verifying that variable names have no influence on order of optionals - // in query. See SES-1121. - - loadTestData("/testdata-query/dataset-ses1121.trig"); - - String query1 = getNamespaceDeclarations() + - " SELECT DISTINCT *\n" + - " WHERE { GRAPH ?g { \n" + - " OPTIONAL { ?var35 ex:p ?b . } \n " + - " OPTIONAL { ?b ex:q ?c . } \n " + - " } \n" + - " } \n"; - - String query2 = getNamespaceDeclarations() + - " SELECT DISTINCT *\n" + - " WHERE { GRAPH ?g { \n" + - " OPTIONAL { ?var35 ex:p ?b . } \n " + - " OPTIONAL { ?b ex:q ?var2 . } \n " + - " } \n" + - " } \n"; - - TupleQuery tq1 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query1); - TupleQuery tq2 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query2); - - try (TupleQueryResult result1 = tq1.evaluate(); TupleQueryResult result2 = tq2.evaluate()) { - assertNotNull(result1); - assertNotNull(result2); - - List qr1 = QueryResults.asList(result1); - List qr2 = QueryResults.asList(result2); - - // System.out.println(qr1); - // System.out.println(qr2); - - // if optionals are not kept in same order, query results will be - // different size. - assertEquals(qr1.size(), qr2.size()); - - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testSES1081SameTermWithValues() throws Exception { - loadTestData("/testdata-query/dataset-ses1081.trig"); - String query = "PREFIX ex: \n" + - " SELECT * \n" + - " WHERE { \n " + - " ?s ex:p ?a . \n" + - " FILTER sameTerm(?a, ?e) \n " + - " VALUES ?e { ex:b } \n " + - " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - Value s = bs.getValue("s"); - Value a = bs.getValue("a"); - - assertNotNull(s); - assertNotNull(a); - assertEquals(f.createIRI("http://example.org/a"), s); - assertEquals(f.createIRI("http://example.org/b"), a); - } - assertEquals(1, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testSES1898LeftJoinSemantics1() throws Exception { - loadTestData("/testdata-query/dataset-ses1898.trig"); - String query = " PREFIX : " + - " SELECT * WHERE { " + - " ?s :p1 ?v1 . " + - " OPTIONAL {?s :p2 ?v2 } ." + - " ?s :p3 ?v2 . " + - " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(0, count); - } - } - - @Test - public void testSES1073InverseSymmetricPattern() { - IRI a = f.createIRI("http://example.org/a"); - IRI b1 = f.createIRI("http://example.org/b1"); - IRI b2 = f.createIRI("http://example.org/b2"); - IRI c1 = f.createIRI("http://example.org/c1"); - IRI c2 = f.createIRI("http://example.org/c2"); - IRI a2b = f.createIRI("http://example.org/a2b"); - IRI b2c = f.createIRI("http://example.org/b2c"); - conn.add(a, a2b, b1); - conn.add(a, a2b, b2); - conn.add(b1, b2c, c1); - conn.add(b2, b2c, c2); - String query = "select * "; - query += "where{ "; - query += "?c1 ^/^// ?c2 . "; - query += " } "; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(4, count); - } - } - - @Test - public void testSES1970CountDistinctWildcard() throws Exception { - loadTestData("/testdata-query/dataset-ses1970.trig"); - - String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - assertTrue(result.hasNext()); - BindingSet s = result.next(); - Literal count = (Literal) s.getValue("c"); - assertNotNull(count); - - assertEquals(3, count.intValue()); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testSES1685propPathSameVar() throws Exception { - final String queryStr = "PREFIX : SELECT ?x WHERE {?x :p+ ?x}"; - - conn.add(new StringReader("@prefix : . :a :p :b . :b :p :a ."), "", RDFFormat.TURTLE); - - TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr); - - try (Stream result = query.evaluate().stream()) { - long count = result.count(); - assertEquals(2, count); - } - } - - @Test - public void testSES2104ConstructBGPSameURI() throws Exception { - final String queryStr = "PREFIX : CONSTRUCT {:x :p :x } WHERE {} "; - - conn.add(new StringReader("@prefix : . :a :p :b . "), "", RDFFormat.TURTLE); - - final IRI x = conn.getValueFactory().createIRI("urn:x"); - final IRI p = conn.getValueFactory().createIRI("urn:p"); - - GraphQuery query = conn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr); - try (GraphQueryResult evaluate = query.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertNotNull(result); - assertFalse(result.isEmpty()); - assertTrue(result.contains(x, p, x)); - } - } - - @Test - public void testSES1898LeftJoinSemantics2() throws Exception { - loadTestData("/testdata-query/dataset-ses1898.trig"); - String query = " PREFIX : " + - " SELECT * WHERE { " + - " ?s :p1 ?v1 . " + - " ?s :p3 ?v2 . " + - " OPTIONAL {?s :p2 ?v2 } ." + - " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(1, count); - } - } - - @Test - public void testIdenticalVariablesInStatementPattern() { - conn.add(alice, f.createIRI("http://purl.org/dc/elements/1.1/publisher"), bob); - - String queryBuilder = "SELECT ?publisher " + - "{ ?publisher ?publisher }"; - - conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder) - .evaluate(new AbstractTupleQueryResultHandler() { - - @Override - public void handleSolution(BindingSet bindingSet) { - fail("nobody is self published"); - } - }); - } - - @Test - public void testInComparison1() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" + - " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - BindingSet bs = result.next(); - Value y = bs.getValue("y"); - assertNotNull(y); - assertTrue(y instanceof Literal); - assertEquals(f.createLiteral("1", CoreDatatype.XSD.INTEGER), y); - } - } - - @Test - public void testInComparison2() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" + - " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); - } - } - - @Test - public void testInComparison3() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" + - " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - BindingSet bs = result.next(); - Value y = bs.getValue("y"); - assertNotNull(y); - assertTrue(y instanceof Literal); - assertEquals(f.createLiteral("1", XSD.INTEGER), y); - } - } - - @Test - public void testSES2121URIFunction() { - String query = "SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI uri = (IRI) bs.getValue("uri"); - assertNull("uri result for invalid URI should be unbound", uri); - } - - query = "BASE SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; - tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI uri = (IRI) bs.getValue("uri"); - assertNotNull("uri result for valid URI reference should be bound", uri); - } - } - - @Test - public void test27NormalizeIRIFunction() { - String query = "SELECT (IRI(\"../bar\") as ?Iri) WHERE {}"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query, "http://example.com/foo/"); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI actual = (IRI) bs.getValue("Iri"); - IRI expected = f.createIRI("http://example.com/bar"); - assertEquals("IRI result for relative IRI should be normalized", expected, actual); - } - } - - @Test - public void testSES869ValueOfNow() { - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, - "SELECT ?p ( NOW() as ?n ) { BIND (NOW() as ?p ) }"); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - BindingSet bs = result.next(); - Value p = bs.getValue("p"); - Value n = bs.getValue("n"); - - assertNotNull(p); - assertNotNull(n); - assertEquals(p, n); - } - } - - @Test - public void testSES2136() throws Exception { - loadTestData("/testcases-sparql-1.1-w3c/bindings/data02.ttl"); - String query = "PREFIX : \n" + - "SELECT ?s ?o { \n" + - " { SELECT * WHERE { ?s ?p ?o . } }\n" + - " VALUES (?o) { (:b) }\n" + - "}\n"; - - ValueFactory vf = conn.getValueFactory(); - final IRI a = vf.createIRI("http://example.org/a"); - final IRI b = vf.createIRI("http://example.org/b"); - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - assertFalse("only one result expected", result.hasNext()); - assertEquals(a, bs.getValue("s")); - assertEquals(b, bs.getValue("o")); - } - } - - @Test - public void testRegexCaseNonAscii() { - String query = "ask {filter (regex(\"Валовой\", \"валовой\", \"i\")) }"; - - assertTrue("case-insensitive match on Cyrillic should succeed", conn.prepareBooleanQuery(query).evaluate()); - - query = "ask {filter (regex(\"Валовой\", \"валовой\")) }"; - - assertFalse("case-sensitive match on Cyrillic should fail", conn.prepareBooleanQuery(query).evaluate()); - - } - - @Test - public void testValuesInOptional() throws Exception { - loadTestData("/testdata-query/dataset-ses1692.trig"); - String query = " PREFIX : \n" + - " SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - // System.out.println(bs); - IRI a = (IRI) bs.getValue("a"); - assertNotNull(a); - Value isX = bs.getValue("isX"); - Literal name = (Literal) bs.getValue("name"); - assertNotNull(name); - if (a.stringValue().endsWith("a1")) { - assertNotNull(isX); - } else if (a.stringValue().endsWith(("a2"))) { - assertNull(isX); - } - } - assertEquals(2, count); - } - } - - /** - * See https://github.com/eclipse/rdf4j/issues/3072 - * - */ - @Test - public void testValuesAfterOptional() throws Exception { - String data = "@prefix rdfs: . \n" - + "@prefix : . \n" - + ":r1 a rdfs:Resource . \n" - + ":r2 a rdfs:Resource ; rdfs:label \"a label\" . \n"; - - String query = "" - + "prefix rdfs: \n" - + "prefix : \n" - + "\n" - + "select ?resource ?label where { \n" - + " ?resource a rdfs:Resource . \n" - + " optional { ?resource rdfs:label ?label } \n" - + " values ?label { undef } \n" - + "}"; - - conn.add(new StringReader(data), RDFFormat.TURTLE); - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - assertThat(result).hasSize(2); - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1978 - */ - @Test - public void testMaxAggregateWithGroupEmptyResult() { - String query = "select ?s (max(?o) as ?omax) {\n" + - " ?s ?p ?o .\n" + - " }\n" + - " group by ?s\n"; - - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); - } - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1978 - */ - @Test - public void testMaxAggregateWithoutGroupEmptySolution() { - String query = "select (max(?o) as ?omax) {\n" + - " ?s ?p ?o .\n" + - " }\n"; - - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); - } - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1978 - */ - @Test - public void testMinAggregateWithGroupEmptyResult() { - String query = "select ?s (min(?o) as ?omin) {\n" + - " ?s ?p ?o .\n" + - " }\n" + - " group by ?s\n"; - - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); - } - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1978 - */ - @Test - public void testMinAggregateWithoutGroupEmptySolution() { - String query = "select (min(?o) as ?omin) {\n" + - " ?s ?p ?o .\n" + - " }\n"; - - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); - } - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1978 - */ - @Test - public void testSampleAggregateWithGroupEmptyResult() { - String query = "select ?s (sample(?o) as ?osample) {\n" + - " ?s ?p ?o .\n" + - " }\n" + - " group by ?s\n"; - - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); - } - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1978 - */ - @Test - public void testSampleAggregateWithoutGroupEmptySolution() { - String query = "select (sample(?o) as ?osample) {\n" + - " ?s ?p ?o .\n" + - " }\n"; - - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); - } - } - - @Test - public void testSES2052If1() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = "SELECT ?p \n" + - "WHERE { \n" + - " ?s ?p ?o . \n" + - " FILTER(IF(BOUND(?p), ?p = , false)) \n" + - "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - while (result.hasNext()) { - BindingSet bs = result.next(); - - IRI p = (IRI) bs.getValue("p"); - assertNotNull(p); - assertEquals(RDF.TYPE, p); - } - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testSES2052If2() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = "SELECT ?p \n" + - "WHERE { \n" + - " ?s ?p ?o . \n" + - " FILTER(IF(!BOUND(?p), false , ?p = )) \n" + - "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - while (result.hasNext()) { - BindingSet bs = result.next(); - - IRI p = (IRI) bs.getValue("p"); - assertNotNull(p); - assertEquals(RDF.TYPE, p); - } - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testSameTermRepeatInUnion() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = "PREFIX foaf:\n" + - "SELECT * {\n" + - " {\n" + - " ?sameTerm foaf:mbox ?mbox\n" + - " FILTER sameTerm(?sameTerm,$william)\n" + - " } UNION {\n" + - " ?x foaf:knows ?sameTerm\n" + - " FILTER sameTerm(?sameTerm,$william)\n" + - " }\n" + - "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - tq.setBinding("william", conn.getValueFactory().createIRI("http://example.org/william")); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - // System.out.println(bs); - - Value mbox = bs.getValue("mbox"); - Value x = bs.getValue("x"); - - assertTrue(mbox instanceof Literal || x instanceof IRI); - } - assertEquals(3, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testSameTermRepeatInUnionAndOptional() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - - String query = getNamespaceDeclarations() + - "SELECT * {\n" + - " {\n" + - " ex:a ?p ?prop1\n" + - " FILTER (?p = ex:prop1)\n" + - " } UNION {\n" + - " ?s ex:p ex:A ; " + - " { " + - " { " + - " ?s ?p ?l ." + - " FILTER(?p = rdfs:label) " + - " } " + - " OPTIONAL { " + - " ?s ?p ?opt1 . " + - " FILTER (?p = ex:prop1) " + - " } " + - " OPTIONAL { " + - " ?s ?p ?opt2 . " + - " FILTER (?p = ex:prop2) " + - " } " + - " }" + - " }\n" + - "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - // System.out.println(bs); - - Value prop1 = bs.getValue("prop1"); - Value l = bs.getValue("l"); - - assertTrue(prop1 instanceof Literal || l instanceof Literal); - if (l instanceof Literal) { - Value opt1 = bs.getValue("opt1"); - assertNull(opt1); - - Value opt2 = bs.getValue("opt2"); - assertNull(opt2); - } - } - assertEquals(2, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testPropertyPathInTree() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - - String query = getNamespaceDeclarations() + - " SELECT ?node ?name " + - " FROM ex:tree-graph " + - " WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - // System.out.println(bs); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testFilterRegexBoolean() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - - // test case for issue SES-1050 - String query = getNamespaceDeclarations() + - " SELECT *" + - " WHERE { " + - " ?x foaf:name ?name ; " + - " foaf:mbox ?mbox . " + - " FILTER(EXISTS { " + - " FILTER(REGEX(?name, \"Bo\") && REGEX(?mbox, \"bob\")) " + - // query.append(" FILTER(REGEX(?mbox, \"bob\")) "); - " } )" + - " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(1, count); - } - } - - @Test - public void testGroupConcatNonDistinct() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - "SELECT (GROUP_CONCAT(?l) AS ?concat)" + - "WHERE { ex:groupconcat-test ?p ?l . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - Value concat = bs.getValue("concat"); - - assertTrue(concat instanceof Literal); - - String lexValue = ((Literal) concat).getLabel(); - - int occ = countCharOccurrences(lexValue, 'a'); - assertEquals(1, occ); - occ = countCharOccurrences(lexValue, 'b'); - assertEquals(2, occ); - occ = countCharOccurrences(lexValue, 'c'); - assertEquals(2, occ); - occ = countCharOccurrences(lexValue, 'd'); - assertEquals(1, occ); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithBinding1() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("parent", OWL.THING); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(4, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithBinding2() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - - // query without initializing ?child first. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("parent", OWL.THING); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(4, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithBinding3() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", f.createIRI(EX_NS, "C")); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithBinding4() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", this.alice); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", f.createIRI(EX_NS, "C")); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithBinding5() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", this.alice, this.bob); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - // System.out.println("--- testArbitraryLengthPathWithBinding5 - // ---"); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - - // System.out.println(bs); - - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", f.createIRI(EX_NS, "C")); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithBinding6() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", this.alice, this.bob, this.mary); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - // System.out.println("--- testArbitraryLengthPathWithBinding6 - // ---"); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - - // System.out.println(bs); - - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", f.createIRI(EX_NS, "C")); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithBinding7() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", this.alice, this.bob, this.mary); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - SimpleDataset dt = new SimpleDataset(); - dt.addDefaultGraph(this.alice); - tq.setDataset(dt); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - // System.out.println("--- testArbitraryLengthPathWithBinding7 - // ---"); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - - // System.out.println(bs); - - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", f.createIRI(EX_NS, "C")); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithBinding8() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", this.alice, this.bob, this.mary); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - SimpleDataset dt = new SimpleDataset(); - dt.addDefaultGraph(this.alice); - dt.addDefaultGraph(this.bob); - tq.setDataset(dt); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - // System.out.println("--- testArbitraryLengthPathWithBinding8 - // ---"); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - - // System.out.println(bs); - - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", f.createIRI(EX_NS, "C")); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithFilter1() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(4, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithFilter2() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(4, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see SES-1091 - * @throws Exception - */ - @Test - public void testArbitraryLengthPathWithFilter3() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = ) }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * @see GH-2727 - */ - @Test - public void testNestedInversePropertyPathWithZeroLength() { - String insert = "insert data {\n" - + " .\n" - + " .\n" - + " .\n" - + " .\n" - + " .\n" - + " .\n" - + "}"; - - String query = "select * where { \n" - + " (^)? ?o .\n" - + "}"; - - conn.prepareUpdate(insert).execute(); - - TupleQuery tq = conn.prepareTupleQuery(query); - - List result = QueryResults.asList(tq.evaluate()); - assertThat(result).hasSize(4); - } - - @Test - public void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception { - - String data = " .\n" + - " .\n" + - " .\n" + - " .\n" + - " .\n"; - - conn.begin(); - conn.add(new StringReader(data), "", RDFFormat.NTRIPLES); - conn.commit(); - - String query = getNamespaceDeclarations() + - "SELECT ?x \n" + - "WHERE { ?x */ . \n" + - " ?x */ . \n" + - "} \n"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - - assertNotNull(result); - assertTrue(result.hasNext()); - - Value x = result.next().getValue("x"); - assertNotNull(x); - assertTrue(x instanceof IRI); - assertEquals("urn:s1", x.stringValue()); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testSES1991UUIDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); - String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(UUID() as ?uid) } LIMIT 2"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - IRI uuid1 = (IRI) result.next().getValue("uid"); - IRI uuid2 = (IRI) result.next().getValue("uid"); - - assertNotNull(uuid1); - assertNotNull(uuid2); - assertNotEquals(uuid1, uuid2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testSES1991STRUUIDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); - String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(STRUUID() as ?uid) } LIMIT 2"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - Literal uid1 = (Literal) result.next().getValue("uid"); - Literal uid2 = (Literal) result.next().getValue("uid"); - - assertNotNull(uid1); - assertNotEquals(uid1, uid2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testSES1991RANDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); - String query = "SELECT ?r WHERE {?s ?p ?o . BIND(RAND() as ?r) } LIMIT 3"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - Literal r1 = (Literal) result.next().getValue("r"); - Literal r2 = (Literal) result.next().getValue("r"); - Literal r3 = (Literal) result.next().getValue("r"); - - assertNotNull(r1); - - // there is a small chance that two successive calls to the random - // number generator will generate the exact same value, so we check - // for - // three successive calls (still theoretically possible to be - // identical, but phenomenally unlikely). - assertFalse(r1.equals(r2) && r1.equals(r3)); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testSES1991NOWEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); - String query = "SELECT ?d WHERE {?s ?p ?o . BIND(NOW() as ?d) } LIMIT 2"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - Literal d1 = (Literal) result.next().getValue("d"); - Literal d2 = (Literal) result.next().getValue("d"); - - assertNotNull(d1); - assertEquals(d1, d2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testSES2024PropertyPathAnonVarSharing() throws Exception { - loadTestData("/testdata-query/dataset-ses2024.trig"); - String query = "PREFIX : SELECT * WHERE { ?x1 :p/:lit ?l1 . ?x1 :diff ?x2 . ?x2 :p/:lit ?l2 . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - BindingSet bs = result.next(); - Literal l1 = (Literal) bs.getValue("l1"); - Literal l2 = (Literal) bs.getValue("l2"); - - assertNotNull(l1); - assertNotEquals(l1, l2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - @Test - public void testPropertyPathNegationInversion() throws Exception { - String data = "@prefix : .\n" - + ":Mary :parentOf :Jim.\n" - + ":Jim :knows :Jane.\n" - + ":Jane :worksFor :IBM."; - - conn.add(new StringReader(data), "", RDFFormat.TURTLE); - String query1 = "prefix : ASK WHERE { :IBM ^(:|!:) :Jane } "; - - assertTrue(conn.prepareBooleanQuery(query1).evaluate()); - - String query2 = "prefix : ASK WHERE { :IBM ^(:|!:) ?a } "; - assertTrue(conn.prepareBooleanQuery(query2).evaluate()); - - String query3 = "prefix : ASK WHERE { :IBM (^(:|!:))* :Mary } "; - assertTrue(conn.prepareBooleanQuery(query3).evaluate()); - - } - - @Test - public void testSES2361UndefMin() { - String query = "SELECT (MIN(?v) as ?min) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("1", result.next().getValue("min").stringValue()); - assertFalse(result.hasNext()); - } - } - - @Test - public void testSES2361UndefMax() { - String query = "SELECT (MAX(?v) as ?max) WHERE { VALUES ?v { 1 2 7 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("7", result.next().getValue("max").stringValue()); - assertFalse(result.hasNext()); - } - } - - @Test - public void testSES2361UndefCount() { - String query = "SELECT (COUNT(?v) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("4", result.next().getValue("c").stringValue()); - assertFalse(result.hasNext()); - } - } - - @Test - public void testSES2361UndefCountWildcard() { - String query = "SELECT (COUNT(*) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("4", result.next().getValue("c").stringValue()); - assertFalse(result.hasNext()); - } - } - - @Test - public void testSES2361UndefSum() { - String query = "SELECT (SUM(?v) as ?s) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("10", result.next().getValue("s").stringValue()); - assertFalse(result.hasNext()); - } - } - - @Test - public void testSES2336NegatedPropertyPathMod() throws Exception { - loadTestData("/testdata-query/dataset-ses2336.trig"); - String query = "prefix : select * where { ?s a :Test ; !:p? ?o . }"; - - ValueFactory vf = conn.getValueFactory(); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult evaluate = tq.evaluate()) { - List result = QueryResults.asList(evaluate); - assertNotNull(result); - - IRI a = vf.createIRI(EX_NS, "a"); - IRI b = vf.createIRI(EX_NS, "b"); - IRI c = vf.createIRI(EX_NS, "c"); - IRI d = vf.createIRI(EX_NS, "d"); - IRI e = vf.createIRI(EX_NS, "e"); - IRI test = vf.createIRI(EX_NS, "Test"); - - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", a))); - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", test))); - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", c))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", d))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", e))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", test))); - - assertFalse(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", b))); - - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - @Test - public void testSES1979MinMaxInf() throws Exception { - loadTestData("/testdata-query/dataset-ses1979.trig"); - String query = "prefix : select (min(?o) as ?min) (max(?o) as ?max) where { ?s :float ?o }"; - - ValueFactory vf = conn.getValueFactory(); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult evaluate = tq.evaluate()) { - List result = QueryResults.asList(evaluate); - assertNotNull(result); - assertEquals(1, result.size()); - - assertEquals(vf.createLiteral(Float.NEGATIVE_INFINITY), result.get(0).getValue("min")); - assertEquals(vf.createLiteral(Float.POSITIVE_INFINITY), result.get(0).getValue("max")); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1018 - */ - @Test - public void testBindError() { - - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - - String qb = "SELECT * \n" + - "WHERE { \n" + - " VALUES (?NAValue) { () } \n " + - " BIND(IF(?NAValue != , ?NAValue, ?notBoundVar) as ?ValidNAValue) \n " + - " { ?disjClass (owl:disjointWith|^owl:disjointWith)? ?disjClass2 . }\n" + - "}\n"; - - List result = QueryResults.asList(conn.prepareTupleQuery(qb).evaluate()); - - assertEquals("query should return 2 solutions", 2, result.size()); - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1405 - */ - @Test - public void testBindScope() { - String query = "SELECT * {\n" + - " { BIND (\"a\" AS ?a) }\n" + - " { BIND (?a AS ?b) } \n" + - "}"; - - TupleQuery q = conn.prepareTupleQuery(query); - List result = QueryResults.asList(q.evaluate()); - - assertEquals(1, result.size()); - - assertEquals(conn.getValueFactory().createLiteral("a"), result.get(0).getValue("a")); - assertNull(result.get(0).getValue("b")); - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1642 - */ - @Test - public void testBindScopeUnion() { - - ValueFactory f = conn.getValueFactory(); - String query = "prefix ex: \n" + - "select * {\n" + - " bind(ex:v1 as ?v)\n" + - " bind(strafter(str(?v),str(ex:)) as ?b)\n" + - " {\n" + - " bind(?b as ?b1)\n" + - " } union {\n" + - " bind(?b as ?b2)\n" + - " }\n" + - "}"; - - TupleQuery q = conn.prepareTupleQuery(query); - List result = QueryResults.asList(q.evaluate()); - - assertEquals(2, result.size()); - - IRI v1 = f.createIRI("http://example.org/v1"); - Literal b = f.createLiteral("v1"); - for (BindingSet bs : result) { - assertThat(bs.getValue("v")).isEqualTo(v1); - assertThat(bs.getValue("b1")).isNull(); - assertThat(bs.getValue("b2")).isNull(); - } - - } - - @Test - public void testSES2250BindErrors() { - - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - - String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" - + " BIND (iri(?blank) as ?biri)" + " ?biri ?p2 ?o2 ." + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertFalse("The query should not return a result", evaluate.hasNext()); - } - } - - @Test - public void testSES2250BindErrorsInPath() { - - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - - String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" - + " BIND (iri(?blank) as ?biri)" + " ?biri * ?o2 ." + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertFalse("The query should not return a result", evaluate.hasNext()); - } - } - - @Test - public void testEmptyUnion() { - String query = "PREFIX : " + "SELECT ?visibility WHERE {" - + "OPTIONAL { SELECT ?var WHERE { :s a :MyType . BIND (:s as ?var ) .} } ." - + "BIND (IF(BOUND(?var), 'VISIBLE', 'HIDDEN') as ?visibility)" + "}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); - } - } - - /** - * https://github.com/eclipse/rdf4j/issues/1026 - */ - @Test - public void testFilterExistsExternalValuesClause() { - String ub = "insert data {\n" + - " a .\n" + - " a .\n" + - " .\n" + - " .\n" + - "}"; - conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); - - String query = "select ?s {\n" + " ?s a* .\n" - + " FILTER EXISTS {?s ?o}\n" - + "} limit 100 values ?o {}"; - - TupleQuery tq = conn.prepareTupleQuery(query); - - List result = QueryResults.asList(tq.evaluate()); - assertEquals("single result expected", 1, result.size()); - assertEquals("http://subj1", result.get(0).getValue("s").stringValue()); - } - - @Test - public void testValuesClauseNamedGraph() throws Exception { - String ex = "http://example.org/"; - String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n" - + "@prefix ex: <" + ex + "> .\n" - + "ex:graph1 {\n" + - " ex:Person1 rdf:type foaf:Person ;\n" + - " foaf:name \"Person 1\" . ex:Person2 rdf:type foaf:Person ;\n" + - " foaf:name \"Person 2\" . ex:Person3 rdf:type foaf:Person ;\n" + - " foaf:name \"Person 3\" .\n" + - "}"; - - conn.add(new StringReader(data), "", RDFFormat.TRIG); - - String query = "SELECT ?person ?name ?__index \n" - + "WHERE { " - + " VALUES (?person ?name ?__index) { \n" - + " ( UNDEF \"0\") \n" - + " ( UNDEF \"2\") } \n" - + " GRAPH { ?person ?name . } }"; - - TupleQuery q = conn.prepareTupleQuery(query); - - List result = QueryResults.asList(q.evaluate()); - assertThat(result).hasSize(2); - } - - @Test - public void testValuesCartesianProduct() { - final String queryString = "" - + "select ?x ?y where { " - + " values ?x { undef 67 } " - + " values ?y { undef 42 } " - + "}"; - final TupleQuery tupleQuery = conn.prepareTupleQuery(queryString); - - List bindingSets = QueryResults.asList(tupleQuery.evaluate()); - assertThat(bindingSets).hasSize(4); - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1267 - */ - @Test - public void testSeconds() { - String qry = "PREFIX xsd: " - + "SELECT (SECONDS(\"2011-01-10T14:45:13\"^^xsd:dateTime) AS ?sec) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("13", result.next().getValue("sec").stringValue()); - assertFalse(result.hasNext()); - } - } - - /** - * See https://github.com/eclipse/rdf4j/issues/1267 - */ - @Test - public void testSecondsMilliseconds() { - String qry = "PREFIX xsd: " - + "SELECT (SECONDS(\"2011-01-10T14:45:13.815-05:00\"^^xsd:dateTime) AS ?sec) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("13.815", result.next().getValue("sec").stringValue()); - assertFalse(result.hasNext()); - } - } - - @Test - public void testConstructModifiers() throws Exception { - loadTestData("/testdata-query/dataset-construct-modifiers.ttl"); - String qry = "PREFIX foaf: \n" - + "PREFIX site: \n" - + "CONSTRUCT { \n" - + " ?iri foaf:name ?name . \n" - + " ?iri foaf:nick ?nick . \n" - + "} \n" - + "WHERE { \n" - + " ?iri foaf:name ?name ; \n" - + " site:hits ?hits ; \n" - + " foaf:nick ?nick . \n" - + "} \n" - + "ORDER BY desc(?hits) \n" - + "LIMIT 3"; - Statement[] correctResult = { - statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/name"), literal("Alice"), null), - statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Al"), null), - - statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/name"), literal("Eve"), null), - statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Ev"), null), - - statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/name"), literal("Bob"), null), - statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Bo"), null), - }; - GraphQuery gq = conn.prepareGraphQuery(qry); - try (GraphQueryResult result = gq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - int resultNo = 0; - while (result.hasNext()) { - Statement st = result.next(); - assertThat(resultNo).isLessThan(correctResult.length); - assertEquals(correctResult[resultNo], st); - resultNo++; - } - assertEquals(correctResult.length, resultNo); - } - } - - /** - * See https://github.com/eclipse/rdf4j/issues/3011 - */ - @Test - public void testConstruct_CyclicPathWithJoin() { - IRI test = iri("urn:test"), a = iri("urn:a"), b = iri("urn:b"), c = iri("urn:c"); - conn.add(test, RDF.TYPE, DCAT.CATALOG); - - String query = "PREFIX dcat: \n" - + "\n" - + "CONSTRUCT {\n" - + " ?x .\n" - + " ?x ?x .\n" - + "}\n" - + "WHERE {\n" - + " ?x a dcat:Catalog .\n" - + "}"; - - Model result = QueryResults.asModel(conn.prepareGraphQuery(query).evaluate()); - - assertThat(result.contains(a, b, test)).isTrue(); - assertThat(result.contains(test, c, test)).isTrue(); - } - - @Test - public void testSelectBindOnly() { - String query = "select ?b1 ?b2 ?b3\n" - + "where {\n" - + " bind(1 as ?b1)\n" - + "}"; - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - - assertThat(result.size()).isEqualTo(1); - BindingSet solution = result.get(0); - - assertThat(solution.getValue("b1")).isEqualTo(literal("1", CoreDatatype.XSD.INTEGER)); - assertThat(solution.getValue("b2")).isNull(); - assertThat(solution.getValue("b3")).isNull(); - - } - - private boolean containsSolution(List result, Binding... solution) { - final MapBindingSet bs = new MapBindingSet(); - for (Binding b : solution) { - bs.addBinding(b); - } - return result.contains(bs); - } - - /* private / protected methods */ - - private int countCharOccurrences(String string, char ch) { - int count = 0; - for (int i = 0; i < string.length(); i++) { - if (string.charAt(i) == ch) { - count++; - } - } - return count; - } - - /** - * Get a set of useful namespace prefix declarations. - * - * @return namespace prefix declarations for dc, foaf and ex. - */ - protected String getNamespaceDeclarations() { - return "PREFIX dc: <" + DCTERMS.NAMESPACE + "> \n" + - "PREFIX foaf: <" + FOAF.NAMESPACE + "> \n" + - "PREFIX sesame: <" + SESAME.NAMESPACE + "> \n" + - "PREFIX ex: <" + EX_NS + "> \n" + - "\n"; - } - - protected abstract Repository newRepository() throws Exception; - - protected void loadTestData(String dataFile, Resource... contexts) - throws RDFParseException, RepositoryException, IOException { - logger.debug("loading dataset {}", dataFile); - try (InputStream dataset = ComplexSPARQLQueryTest.class.getResourceAsStream(dataFile)) { - conn.add(dataset, "", Rio.getParserFormatForFileName(dataFile).orElseThrow(Rio.unsupportedFormat(dataFile)), - contexts); - } - logger.debug("dataset loaded."); - } -} diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/SPARQLUpdateTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/SPARQLUpdateTest.java index b062b3e18e3..8db2c5e358b 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/SPARQLUpdateTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/SPARQLUpdateTest.java @@ -101,10 +101,9 @@ public void setUp() throws Exception { } /** - * @throws java.lang.Exception */ @AfterEach - public void tearDown() throws Exception { + public void tearDown() { logger.debug("tearing down..."); con.close(); con = null; @@ -118,7 +117,7 @@ public void tearDown() throws Exception { /* test methods */ @Test - public void testDeleteFromDefaultGraph() throws Exception { + public void testDeleteFromDefaultGraph() { con.add(RDF.FIRST, RDF.FIRST, RDF.FIRST); con.add(RDF.FIRST, RDF.FIRST, RDF.FIRST, RDF.ALT); @@ -137,7 +136,7 @@ public void testDeleteFromDefaultGraph() throws Exception { } @Test - public void testDeleteFromDefaultGraphUsingWith() throws Exception { + public void testDeleteFromDefaultGraphUsingWith() { con.add(RDF.FIRST, RDF.FIRST, RDF.FIRST); con.add(RDF.FIRST, RDF.FIRST, RDF.FIRST, RDF.ALT); @@ -156,7 +155,7 @@ public void testDeleteFromDefaultGraphUsingWith() throws Exception { } @Test - public void testInsertWhereInvalidTriple() throws Exception { + public void testInsertWhereInvalidTriple() { String update = getNamespaceDeclarations() + "INSERT {?name a foaf:Person. ?x a . } WHERE { ?x foaf:name ?name }"; @@ -173,7 +172,7 @@ public void testInsertWhereInvalidTriple() throws Exception { } @Test - public void testDeleteWhereInvalidTriple() throws Exception { + public void testDeleteWhereInvalidTriple() { String update = getNamespaceDeclarations() + "DELETE {?name a foaf:Person. ?x foaf:name ?name } WHERE { ?x foaf:name ?name }"; @@ -188,7 +187,7 @@ public void testDeleteWhereInvalidTriple() throws Exception { } @Test - public void testDeleteInsertWhereInvalidTriple() throws Exception { + public void testDeleteInsertWhereInvalidTriple() { String update = getNamespaceDeclarations() + "DELETE {?name a foaf:Person} INSERT {?name a foaf:Agent} WHERE { ?x foaf:name ?name }"; @@ -202,7 +201,7 @@ public void testDeleteInsertWhereInvalidTriple() throws Exception { } @Test - public void testInsertWhere() throws Exception { + public void testInsertWhere() { logger.debug("executing test InsertWhere"); String update = getNamespaceDeclarations() + "INSERT {?x rdfs:label ?y . } WHERE {?x foaf:name ?y }"; @@ -219,7 +218,7 @@ public void testInsertWhere() throws Exception { } @Test - public void testInsertWhereWithBinding() throws Exception { + public void testInsertWhereWithBinding() { logger.debug("executing test testInsertWhereWithBinding"); String update = getNamespaceDeclarations() + "INSERT {?x rdfs:label ?y . } WHERE {?x foaf:name ?y }"; @@ -237,7 +236,7 @@ public void testInsertWhereWithBinding() throws Exception { } @Test - public void testInsertWhereWithBindings2() throws Exception { + public void testInsertWhereWithBindings2() { logger.debug("executing test testInsertWhereWithBindings2"); String update = getNamespaceDeclarations() + "INSERT {?x rdfs:label ?z . } WHERE {?x foaf:name ?y }"; @@ -256,7 +255,7 @@ public void testInsertWhereWithBindings2() throws Exception { } @Test - public void testInsertEmptyWhere() throws Exception { + public void testInsertEmptyWhere() { logger.debug("executing test testInsertEmptyWhere"); String update = getNamespaceDeclarations() + "INSERT { <" + bob + "> rdfs:label \"Bob\" . } WHERE { }"; @@ -271,7 +270,7 @@ public void testInsertEmptyWhere() throws Exception { } @Test - public void testInsertEmptyWhereWithBinding() throws Exception { + public void testInsertEmptyWhereWithBinding() { logger.debug("executing test testInsertEmptyWhereWithBinding"); String update = getNamespaceDeclarations() + "INSERT {?x rdfs:label ?y . } WHERE { }"; @@ -288,7 +287,7 @@ public void testInsertEmptyWhereWithBinding() throws Exception { } @Test - public void testInsertNonMatchingWhere() throws Exception { + public void testInsertNonMatchingWhere() { logger.debug("executing test testInsertNonMatchingWhere"); String update = getNamespaceDeclarations() + "INSERT { ?x rdfs:label ?y . } WHERE { ?x rdfs:comment ?y }"; @@ -303,7 +302,7 @@ public void testInsertNonMatchingWhere() throws Exception { } @Test - public void testInsertNonMatchingWhereWithBindings() throws Exception { + public void testInsertNonMatchingWhereWithBindings() { logger.debug("executing test testInsertNonMatchingWhereWithBindings"); String update = getNamespaceDeclarations() + "INSERT { ?x rdfs:label ?y . } WHERE { ?x rdfs:comment ?y }"; @@ -320,7 +319,7 @@ public void testInsertNonMatchingWhereWithBindings() throws Exception { } @Test - public void testInsertWhereWithBindings() throws Exception { + public void testInsertWhereWithBindings() { logger.debug("executing test testInsertWhereWithBindings"); String update = getNamespaceDeclarations() + "INSERT { ?x rdfs:comment ?z . } WHERE { ?x foaf:name ?y }"; @@ -341,7 +340,7 @@ public void testInsertWhereWithBindings() throws Exception { } @Test - public void testInsertWhereWithOptional() throws Exception { + public void testInsertWhereWithOptional() { logger.debug("executing testInsertWhereWithOptional"); String update = getNamespaceDeclarations() + @@ -377,7 +376,7 @@ public void testInsertWhereWithOptional() throws Exception { } @Test - public void testInsertWhereWithBlankNode() throws Exception { + public void testInsertWhereWithBlankNode() { logger.debug("executing testInsertWhereWithBlankNode"); String update = getNamespaceDeclarations() + @@ -426,7 +425,7 @@ public void testInsertWhereWithBlankNode() throws Exception { } @Test - public void testDeleteInsertWhere() throws Exception { + public void testDeleteInsertWhere() { logger.debug("executing test DeleteInsertWhere"); String update = getNamespaceDeclarations() + "DELETE { ?x foaf:name ?y } INSERT {?x rdfs:label ?y . } WHERE {?x foaf:name ?y }"; @@ -447,7 +446,7 @@ public void testDeleteInsertWhere() throws Exception { } @Test - public void testDeleteWhereOptional() throws Exception { + public void testDeleteWhereOptional() { logger.debug("executing test testDeleteWhereOptional"); String update = getNamespaceDeclarations() + " DELETE { ?x foaf:name ?y; foaf:mbox ?mbox. } " + @@ -475,7 +474,7 @@ public void testDeleteWhereOptional() throws Exception { } @Test - public void testDeleteInsertWhereWithBindings() throws Exception { + public void testDeleteInsertWhereWithBindings() { logger.debug("executing test testDeleteInsertWhereWithBindings"); String update = getNamespaceDeclarations() + "DELETE { ?x foaf:name ?y } INSERT {?x rdfs:label ?y . } WHERE {?x foaf:name ?y }"; @@ -497,7 +496,7 @@ public void testDeleteInsertWhereWithBindings() throws Exception { } @Test - public void testDeleteInsertWhereWithBindings2() throws Exception { + public void testDeleteInsertWhereWithBindings2() { logger.debug("executing test testDeleteInsertWhereWithBindings2"); String update = getNamespaceDeclarations() + "DELETE { ?x foaf:name ?y } INSERT {?x rdfs:label ?z . } WHERE {?x foaf:name ?y }"; @@ -519,7 +518,7 @@ public void testDeleteInsertWhereWithBindings2() throws Exception { } @Test - public void testDeleteInsertWhereLoopingBehavior() throws Exception { + public void testDeleteInsertWhereLoopingBehavior() { logger.debug("executing test testDeleteInsertWhereLoopingBehavior"); String update = getNamespaceDeclarations() + " DELETE { ?x ex:age ?y } INSERT {?x ex:age ?z }" + @@ -546,7 +545,7 @@ public void testDeleteInsertWhereLoopingBehavior() throws Exception { } @Test - public void testAutoCommitHandling() throws Exception { + public void testAutoCommitHandling() { logger.debug("executing test testAutoCommitHandling"); StringBuilder update = new StringBuilder(); @@ -596,7 +595,7 @@ public void testAutoCommitHandling() throws Exception { } @Test - public void testConsecutiveUpdatesInSameTransaction() throws Exception { + public void testConsecutiveUpdatesInSameTransaction() { // this tests if consecutive updates in the same transaction behave // correctly. See issue SES-930 logger.debug("executing test testConsecutiveUpdatesInSameTransaction"); @@ -639,7 +638,7 @@ public void testConsecutiveUpdatesInSameTransaction() throws Exception { } @Test - public void testInsertTransformedWhere() throws Exception { + public void testInsertTransformedWhere() { logger.debug("executing test InsertTransformedWhere"); String update = getNamespaceDeclarations() + @@ -657,7 +656,7 @@ public void testInsertTransformedWhere() throws Exception { } @Test - public void testInsertWhereGraph() throws Exception { + public void testInsertWhereGraph() { logger.debug("executing testInsertWhereGraph"); String update = getNamespaceDeclarations() + "INSERT {GRAPH ?g {?x rdfs:label ?y . }} WHERE {GRAPH ?g {?x foaf:name ?y }}"; @@ -674,7 +673,7 @@ public void testInsertWhereGraph() throws Exception { } @Test - public void testInsertWhereUsing() throws Exception { + public void testInsertWhereUsing() { logger.debug("executing testInsertWhereUsing"); String update = getNamespaceDeclarations() + @@ -692,7 +691,7 @@ public void testInsertWhereUsing() throws Exception { } @Test - public void testInsertWhereUsingWith() throws Exception { + public void testInsertWhereUsingWith() { logger.debug("executing testInsertWhereUsingWith"); String update = getNamespaceDeclarations() + @@ -709,7 +708,7 @@ public void testInsertWhereUsingWith() throws Exception { } @Test - public void testInsertWhereWith() throws Exception { + public void testInsertWhereWith() { logger.debug("executing testInsertWhereWith"); String update = getNamespaceDeclarations() + @@ -727,7 +726,7 @@ public void testInsertWhereWith() throws Exception { } @Test - public void testDeleteWhereShortcut() throws Exception { + public void testDeleteWhereShortcut() { logger.debug("executing testDeleteWhereShortcut"); String update = getNamespaceDeclarations() + @@ -750,7 +749,7 @@ public void testDeleteWhereShortcut() throws Exception { } @Test - public void testDeleteWhere() throws Exception { + public void testDeleteWhere() { logger.debug("executing testDeleteWhere"); String update = getNamespaceDeclarations() + @@ -770,7 +769,7 @@ public void testDeleteWhere() throws Exception { } @Test - public void testDeleteTransformedWhere() throws Exception { + public void testDeleteTransformedWhere() { logger.debug("executing testDeleteTransformedWhere"); String update = getNamespaceDeclarations() + @@ -794,7 +793,7 @@ public void testDeleteTransformedWhere() throws Exception { } @Test - public void testInsertData() throws Exception { + public void testInsertData() { logger.debug("executing testInsertData"); String update = getNamespaceDeclarations() + @@ -815,7 +814,7 @@ public void testInsertData() throws Exception { } @Test - public void testInsertData2() throws Exception { + public void testInsertData2() { logger.debug("executing testInsertData2"); String update = getNamespaceDeclarations() + @@ -836,7 +835,7 @@ public void testInsertData2() throws Exception { } @Test - public void testInsertDataLangTaggedLiteral() throws Exception { + public void testInsertDataLangTaggedLiteral() { logger.debug("executing testInsertDataLangTaggedLiteral"); String update = getNamespaceDeclarations() + @@ -855,7 +854,7 @@ public void testInsertDataLangTaggedLiteral() throws Exception { } @Test - public void testInsertDataGraph1() throws Exception { + public void testInsertDataGraph1() { logger.debug("executing testInsertDataGraph1"); String update = "INSERT DATA { \n" + @@ -874,7 +873,7 @@ public void testInsertDataGraph1() throws Exception { } @Test - public void testInsertDataGraph2() throws Exception { + public void testInsertDataGraph2() { logger.debug("executing testInsertDataGraph2"); String update = "INSERT DATA { \n" + @@ -893,7 +892,7 @@ public void testInsertDataGraph2() throws Exception { } @Test - public void testInsertDataGraph3() throws Exception { + public void testInsertDataGraph3() { logger.debug("executing testInsertDataGraph3"); String update = "INSERT DATA { \n" + @@ -919,7 +918,7 @@ public void testInsertDataGraph3() throws Exception { } @Test - public void testInsertDataBlankNode() throws Exception { + public void testInsertDataBlankNode() { logger.debug("executing testInsertDataBlankNode"); String update = getNamespaceDeclarations() + @@ -967,7 +966,7 @@ public void testInsertDataBlankNode() throws Exception { } @Test - public void testInsertDataMultiplePatterns() throws Exception { + public void testInsertDataMultiplePatterns() { logger.debug("executing testInsertData"); String update = getNamespaceDeclarations() + @@ -991,7 +990,7 @@ public void testInsertDataMultiplePatterns() throws Exception { } @Test - public void testInsertDataInGraph() throws Exception { + public void testInsertDataInGraph() { logger.debug("executing testInsertDataInGraph"); String update = getNamespaceDeclarations() + @@ -1012,7 +1011,7 @@ public void testInsertDataInGraph() throws Exception { } @Test - public void testInsertDataInGraph2() throws Exception { + public void testInsertDataInGraph2() { logger.debug("executing testInsertDataInGraph2"); String update = getNamespaceDeclarations() + @@ -1032,7 +1031,7 @@ public void testInsertDataInGraph2() throws Exception { } @Test - public void testDeleteData() throws Exception { + public void testDeleteData() { logger.debug("executing testDeleteData"); String update = getNamespaceDeclarations() + "DELETE DATA { ex:alice foaf:knows ex:bob. } "; @@ -1047,7 +1046,7 @@ public void testDeleteData() throws Exception { } @Test - public void testDeleteDataUnicode() throws Exception { + public void testDeleteDataUnicode() { IRI i18n = con.getValueFactory().createIRI(EX_NS, "東京"); con.add(i18n, FOAF.KNOWS, bob); @@ -1066,7 +1065,7 @@ public void testDeleteDataUnicode() throws Exception { } @Test - public void testDeleteDataMultiplePatterns() throws Exception { + public void testDeleteDataMultiplePatterns() { logger.debug("executing testDeleteData"); String update = getNamespaceDeclarations() + "DELETE DATA { ex:alice foaf:knows ex:bob. ex:alice foaf:mbox \"alice@example.org\" .} "; @@ -1083,7 +1082,7 @@ public void testDeleteDataMultiplePatterns() throws Exception { } @Test - public void testDeleteDataFromGraph() throws Exception { + public void testDeleteDataFromGraph() { logger.debug("executing testDeleteDataFromGraph"); String update = getNamespaceDeclarations() + @@ -1099,7 +1098,7 @@ public void testDeleteDataFromGraph() throws Exception { } @Test - public void testDeleteDataFromWrongGraph() throws Exception { + public void testDeleteDataFromWrongGraph() { logger.debug("executing testDeleteDataFromWrongGraph"); String update = getNamespaceDeclarations() + @@ -1118,7 +1117,7 @@ public void testDeleteDataFromWrongGraph() throws Exception { } @Test - public void testCreateNewGraph() throws Exception { + public void testCreateNewGraph() { logger.debug("executing testCreateNewGraph"); StringBuilder update = new StringBuilder(); @@ -1138,7 +1137,7 @@ public void testCreateNewGraph() throws Exception { } @Test - public void testCreateExistingGraph() throws Exception { + public void testCreateExistingGraph() { logger.debug("executing testCreateExistingGraph"); String update = getNamespaceDeclarations() + @@ -1159,7 +1158,7 @@ public void testCreateExistingGraph() throws Exception { } @Test - public void testCopyToDefault() throws Exception { + public void testCopyToDefault() { logger.debug("executing testCopyToDefault"); String update = getNamespaceDeclarations() + "COPY GRAPH <" + graph1.stringValue() + "> TO DEFAULT"; @@ -1176,7 +1175,7 @@ public void testCopyToDefault() throws Exception { } @Test - public void testCopyToExistingNamed() throws Exception { + public void testCopyToExistingNamed() { logger.debug("executing testCopyToExistingNamed"); String update = getNamespaceDeclarations() + @@ -1192,7 +1191,7 @@ public void testCopyToExistingNamed() throws Exception { } @Test - public void testCopyToNewNamed() throws Exception { + public void testCopyToNewNamed() { logger.debug("executing testCopyToNewNamed"); String update = getNamespaceDeclarations() + @@ -1206,7 +1205,7 @@ public void testCopyToNewNamed() throws Exception { } @Test - public void testCopyFromDefault() throws Exception { + public void testCopyFromDefault() { logger.debug("executing testCopyFromDefault"); String update = getNamespaceDeclarations() + @@ -1225,7 +1224,7 @@ public void testCopyFromDefault() throws Exception { } @Test - public void testCopyFromDefaultToDefault() throws Exception { + public void testCopyFromDefaultToDefault() { logger.debug("executing testCopyFromDefaultToDefault"); String update = getNamespaceDeclarations() + @@ -1241,7 +1240,7 @@ public void testCopyFromDefaultToDefault() throws Exception { } @Test - public void testAddToDefault() throws Exception { + public void testAddToDefault() { logger.debug("executing testAddToDefault"); String update = getNamespaceDeclarations() + @@ -1259,7 +1258,7 @@ public void testAddToDefault() throws Exception { } @Test - public void testAddToExistingNamed() throws Exception { + public void testAddToExistingNamed() { logger.debug("executing testAddToExistingNamed"); String update = getNamespaceDeclarations() + @@ -1274,7 +1273,7 @@ public void testAddToExistingNamed() throws Exception { } @Test - public void testAddToNewNamed() throws Exception { + public void testAddToNewNamed() { logger.debug("executing testAddToNewNamed"); String update = getNamespaceDeclarations() + @@ -1288,7 +1287,7 @@ public void testAddToNewNamed() throws Exception { } @Test - public void testAddFromDefault() throws Exception { + public void testAddFromDefault() { logger.debug("executing testAddFromDefault"); String update = getNamespaceDeclarations() + @@ -1310,7 +1309,7 @@ public void testAddFromDefault() throws Exception { } @Test - public void testAddFromDefaultToDefault() throws Exception { + public void testAddFromDefaultToDefault() { logger.debug("executing testAddFromDefaultToDefault"); String update = getNamespaceDeclarations() + @@ -1326,7 +1325,7 @@ public void testAddFromDefaultToDefault() throws Exception { } @Test - public void testMoveToDefault() throws Exception { + public void testMoveToDefault() { logger.debug("executing testMoveToDefault"); String update = getNamespaceDeclarations() + @@ -1344,7 +1343,7 @@ public void testMoveToDefault() throws Exception { } @Test - public void testMoveToNewNamed() throws Exception { + public void testMoveToNewNamed() { logger.debug("executing testMoveToNewNamed"); String update = getNamespaceDeclarations() + "MOVE GRAPH ex:graph1 TO ex:graph3"; @@ -1357,7 +1356,7 @@ public void testMoveToNewNamed() throws Exception { } @Test - public void testMoveFromDefault() throws Exception { + public void testMoveFromDefault() { logger.debug("executing testMoveFromDefault"); String update = getNamespaceDeclarations() + "MOVE DEFAULT TO ex:graph3"; @@ -1375,7 +1374,7 @@ public void testMoveFromDefault() throws Exception { } @Test - public void testMoveFromDefaultToDefault() throws Exception { + public void testMoveFromDefaultToDefault() { logger.debug("executing testMoveFromDefaultToDefault"); String update = getNamespaceDeclarations() + "MOVE DEFAULT TO DEFAULT"; @@ -1390,7 +1389,7 @@ public void testMoveFromDefaultToDefault() throws Exception { } @Test - public void testClearAll() throws Exception { + public void testClearAll() { logger.debug("executing testClearAll"); String update = "CLEAR ALL"; @@ -1402,7 +1401,7 @@ public void testClearAll() throws Exception { } @Test - public void testClearDefault() throws Exception { + public void testClearDefault() { logger.debug("executing testClearDefault"); String update = "CLEAR DEFAULT"; @@ -1423,7 +1422,7 @@ public void testClearDefault() throws Exception { } @Test - public void testClearGraph() throws Exception { + public void testClearGraph() { logger.debug("executing testClearGraph"); String update = getNamespaceDeclarations() + "CLEAR GRAPH <" + graph1.stringValue() + "> "; @@ -1437,7 +1436,7 @@ public void testClearGraph() throws Exception { } @Test - public void testClearNamed() throws Exception { + public void testClearNamed() { logger.debug("executing testClearNamed"); String update = "CLEAR NAMED"; @@ -1451,7 +1450,7 @@ public void testClearNamed() throws Exception { } @Test - public void testDropAll() throws Exception { + public void testDropAll() { logger.debug("executing testDropAll"); String update = "DROP ALL"; @@ -1463,7 +1462,7 @@ public void testDropAll() throws Exception { } @Test - public void testDropDefault() throws Exception { + public void testDropDefault() { logger.debug("executing testDropDefault"); String update = "DROP DEFAULT"; @@ -1485,7 +1484,7 @@ public void testDropDefault() throws Exception { } @Test - public void testDropGraph() throws Exception { + public void testDropGraph() { logger.debug("executing testDropGraph"); String update = getNamespaceDeclarations() + "DROP GRAPH <" + graph1.stringValue() + "> "; @@ -1499,7 +1498,7 @@ public void testDropGraph() throws Exception { } @Test - public void testDropNamed() throws Exception { + public void testDropNamed() { logger.debug("executing testDropNamed"); String update = "DROP NAMED"; @@ -1513,7 +1512,7 @@ public void testDropNamed() throws Exception { } @Test - public void testUpdateSequenceDeleteInsert() throws Exception { + public void testUpdateSequenceDeleteInsert() { logger.debug("executing testUpdateSequenceDeleteInsert"); String update = getNamespaceDeclarations() + @@ -1538,7 +1537,7 @@ public void testUpdateSequenceDeleteInsert() throws Exception { } @Test - public void testUpdateSequenceInsertDelete() throws Exception { + public void testUpdateSequenceInsertDelete() { logger.debug("executing testUpdateSequenceInsertDelete"); String update = getNamespaceDeclarations() + @@ -1563,7 +1562,7 @@ public void testUpdateSequenceInsertDelete() throws Exception { } @Test - public void testUpdateSequenceInsertDelete2() throws Exception { + public void testUpdateSequenceInsertDelete2() { logger.debug("executing testUpdateSequenceInsertDelete2"); String update = getNamespaceDeclarations() + @@ -1636,7 +1635,7 @@ public void testUpdateSequenceInsertDeleteExample9() throws Exception { } @Test - public void testUpdateSequenceWithRelativeIRI() throws Exception { + public void testUpdateSequenceWithRelativeIRI() { logger.debug("executing testUpdateSequenceWithRelativeIRI"); String update = "base \n" + "prefix em: \n" // + "insert {\n" // @@ -1742,9 +1741,8 @@ protected String getNamespaceDeclarations() { * Creates, initializes and clears a repository. * * @return an initialized empty repository. - * @throws Exception */ - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repository = newRepository(); try (RepositoryConnection con = repository.getConnection()) { con.clear(); @@ -1758,7 +1756,6 @@ protected Repository createRepository() throws Exception { * specific Repository type and configuration. * * @return a new (uninitialized) Repository - * @throws Exception */ - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxTest.java index 5ed721001ad..0eb9d8c7afe 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxTest.java @@ -176,7 +176,7 @@ protected void runTest() throws Exception { protected abstract ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException; - public static Test suite() throws Exception { + public static Test suite() { return new TestSuite(); } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11UpdateComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11UpdateComplianceTest.java index 44aff3bdb82..91d092aa503 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11UpdateComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11UpdateComplianceTest.java @@ -173,7 +173,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { if (dataRep != null) { dataRep.shutDown(); dataRep = null; diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLComplianceTest.java index 5ea1e457c90..83131e831f6 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLComplianceTest.java @@ -196,7 +196,7 @@ protected void setIgnoredTests(List ignoredTests) { this.ignoredTests = ignoredTests; } - protected void compareGraphs(Iterable queryResult, Iterable expectedResult) throws Exception { + protected void compareGraphs(Iterable queryResult, Iterable expectedResult) { if (!Models.isomorphic(expectedResult, queryResult)) { StringBuilder message = new StringBuilder(128); message.append("\n============ "); diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java index e83213821f1..54b6647e679 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java @@ -123,7 +123,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { if (dataRepository != null) { dataRepository.shutDown(); dataRepository = null; diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryTest.java index 287eb0f99da..a388f8220b2 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryTest.java @@ -154,7 +154,7 @@ protected void setUp() throws Exception { } } - protected final Repository createRepository() throws Exception { + protected final Repository createRepository() { Repository repo = newRepository(); try (RepositoryConnection con = repo.getConnection()) { con.clear(); @@ -163,10 +163,10 @@ protected final Repository createRepository() throws Exception { return repo; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); @Override - protected void tearDown() throws Exception { + protected void tearDown() { if (dataRep != null) { dataRep.shutDown(); dataRep = null; @@ -227,8 +227,7 @@ protected void runTest() throws Exception { } } - protected final void compareTupleQueryResults(TupleQueryResult queryResult, TupleQueryResult expectedResult) - throws Exception { + protected final void compareTupleQueryResults(TupleQueryResult queryResult, TupleQueryResult expectedResult) { // Create MutableTupleQueryResult to be able to re-iterate over the // results MutableTupleQueryResult queryResultTable = new MutableTupleQueryResult(queryResult); @@ -367,7 +366,7 @@ protected final void printBindingSet(BindingSet bs, StringBuilder appendable) { appendable.append("\n"); } - protected final void compareGraphs(Set queryResult, Set expectedResult) throws Exception { + protected final void compareGraphs(Set queryResult, Set expectedResult) { if (!Models.isomorphic(expectedResult, queryResult)) { // Don't use RepositoryUtil.difference, it reports incorrect diffs /* diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLUpdateConformanceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLUpdateConformanceTest.java index aa451ad3e35..ff242f45df3 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLUpdateConformanceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLUpdateConformanceTest.java @@ -168,7 +168,7 @@ protected void setUp() throws Exception { } } - protected Repository createRepository() throws Exception { + protected Repository createRepository() { Repository repo = newRepository(); Repositories.consume(repo, con -> { con.clear(); @@ -178,10 +178,10 @@ protected Repository createRepository() throws Exception { return repo; } - protected abstract Repository newRepository() throws Exception; + protected abstract Repository newRepository(); @Override - protected void tearDown() throws Exception { + protected void tearDown() { if (dataRep != null) { dataRep.shutDown(); dataRep = null; @@ -225,8 +225,7 @@ protected void runTest() throws Exception { } } - private void compareGraphs(Iterable actual, Iterable expected) - throws Exception { + private void compareGraphs(Iterable actual, Iterable expected) { if (!Models.isomorphic(expected, actual)) { StringBuilder message = new StringBuilder(128); message.append("\n============ "); diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java index 39b73a5c6f7..08d3e9f3b0c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java @@ -17,7 +17,6 @@ import java.net.URL; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.common.transaction.IsolationLevel; import org.eclipse.rdf4j.common.transaction.TransactionSetting; import org.eclipse.rdf4j.model.IRI; @@ -71,7 +70,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { try { conn.close(); } finally { @@ -412,15 +411,8 @@ public void add(Iterable statements, Resource... contexts) } @Override - @Deprecated(since = "4.1.0", forRemoval = true) - public void add(Iteration statements, Resource... contexts) - throws RepositoryException, E { - delegate.add(statements, contexts); - } - - @Override - public void add(CloseableIteration statements, - Resource... contexts) throws RepositoryException, E { + public void add(CloseableIteration statements, + Resource... contexts) throws RepositoryException { delegate.add(statements, contexts); } @@ -446,15 +438,8 @@ public void remove(Iterable statements, Resource... context } @Override - @Deprecated(since = "4.1.0", forRemoval = true) - public void remove(Iteration statements, Resource... contexts) - throws RepositoryException, E { - delegate.remove(statements, contexts); - } - - @Override - public void remove(CloseableIteration statements, - Resource... contexts) throws RepositoryException, E { + public void remove(CloseableIteration statements, + Resource... contexts) throws RepositoryException { delegate.remove(statements, contexts); } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java index cae08df81b9..0a25c45a38b 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java @@ -135,7 +135,7 @@ public void testSampleAggregateWithoutGroupEmptySolution() { public void testSES2361UndefMin() { String query = "SELECT (MIN(?v) as ?min) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); assertThat(result.next().getValue("min").stringValue()).isEqualTo("1"); assertThat(result.hasNext()).isFalse(); @@ -146,10 +146,10 @@ public void testSES2361UndefMin() { public void testSES2361UndefMax() { String query = "SELECT (MAX(?v) as ?max) WHERE { VALUES ?v { 1 2 7 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); assertThat(result.next().getValue("max").stringValue()).isEqualTo("7"); - assertThat(result).isEmpty(); + assertThat((Iterable) result).isEmpty(); } } @@ -157,10 +157,10 @@ public void testSES2361UndefMax() { public void testSES2361UndefCount() { String query = "SELECT (COUNT(?v) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); - assertThat(result).isEmpty(); + assertThat((Iterable) result).isEmpty(); } } @@ -168,10 +168,10 @@ public void testSES2361UndefCount() { public void testSES2361UndefCountWildcard() { String query = "SELECT (COUNT(*) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); - assertThat(result).isEmpty(); + assertThat((Iterable) result).isEmpty(); } } @@ -179,10 +179,10 @@ public void testSES2361UndefCountWildcard() { public void testSES2361UndefSum() { String query = "SELECT (SUM(?v) as ?s) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); assertThat(result.next().getValue("s").stringValue()).isEqualTo("10"); - assertThat(result).isEmpty(); + assertThat((Iterable) result).isEmpty(); } } @@ -195,7 +195,7 @@ public void testSES1979MinMaxInf() throws Exception { try (TupleQueryResult evaluate = tq.evaluate()) { List result = QueryResults.asList(evaluate); - assertThat(result).isNotNull().hasSize(1); + assertThat((Iterable) result).isNotNull().hasSize(1); assertThat(result.get(0).getValue("min")).isEqualTo(literal(Float.NEGATIVE_INFINITY)); assertThat(result.get(0).getValue("max")).isEqualTo(literal(Float.POSITIVE_INFINITY)); } catch (QueryEvaluationException e) { @@ -216,7 +216,7 @@ public void testGroupConcatDistinct() throws Exception { TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); try (TupleQueryResult result = tq.evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); while (result.hasNext()) { BindingSet bs = result.next(); @@ -254,7 +254,7 @@ public void testGroupConcatNonDistinct() throws Exception { TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); try (TupleQueryResult result = tq.evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); while (result.hasNext()) { BindingSet bs = result.next(); @@ -291,7 +291,7 @@ public void testSES1970CountDistinctWildcard() throws Exception { TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); try (TupleQueryResult result = tq.evaluate()) { - assertThat(result).isNotNull(); + assertThat((Iterable) result).isNotNull(); assertThat(result.hasNext()).isTrue(); BindingSet s = result.next(); @@ -433,7 +433,7 @@ public void testDistinctMax() { } /** - * @see https://github.com/eclipse/rdf4j/issues/4290 + * @see https://github.com/eclipse/rdf4j/issues/4290 */ @Test public void testCountOrderBy_ImplicitGroup() { diff --git a/tools/config/src/test/java/org/eclipse/rdf4j/common/app/AppVersionTest.java b/tools/config/src/test/java/org/eclipse/rdf4j/common/app/AppVersionTest.java index 5b5379df4be..3c64a12bffb 100644 --- a/tools/config/src/test/java/org/eclipse/rdf4j/common/app/AppVersionTest.java +++ b/tools/config/src/test/java/org/eclipse/rdf4j/common/app/AppVersionTest.java @@ -22,7 +22,7 @@ public class AppVersionTest { @Test - public void testCreateFromString() throws Exception { + public void testCreateFromString() { AppVersion v = AppVersion.parse("1.0.3"); assertEquals(1, v.getMajor()); @@ -32,7 +32,7 @@ public void testCreateFromString() throws Exception { } @Test - public void testCreateFromStringSnapshot() throws Exception { + public void testCreateFromStringSnapshot() { AppVersion v; v = AppVersion.parse("2.8.0-beta3-SNAPSHOT"); assertEquals(2, v.getMajor()); @@ -43,7 +43,7 @@ public void testCreateFromStringSnapshot() throws Exception { } @Test - public void testCreateFromStringMilestone() throws Exception { + public void testCreateFromStringMilestone() { AppVersion v; v = AppVersion.parse("1.0M1"); assertEquals(1, v.getMajor()); @@ -54,7 +54,7 @@ public void testCreateFromStringMilestone() throws Exception { } @Test - public void testCreateFromStringBeta() throws Exception { + public void testCreateFromStringBeta() { AppVersion v; v = AppVersion.parse("1.0.0-beta3"); assertEquals(1, v.getMajor()); @@ -64,7 +64,7 @@ public void testCreateFromStringBeta() throws Exception { } @Test - public void testCreateFromStringModifier() throws Exception { + public void testCreateFromStringModifier() { AppVersion v; v = AppVersion.parse("1.0.0-M1"); assertEquals(1, v.getMajor()); @@ -74,7 +74,7 @@ public void testCreateFromStringModifier() throws Exception { } @Test - public void testCreateFromStringModifierMilestone() throws Exception { + public void testCreateFromStringModifierMilestone() { AppVersion v; v = AppVersion.parse("1.0.0-GAMMA"); assertEquals(1, v.getMajor()); @@ -84,14 +84,14 @@ public void testCreateFromStringModifierMilestone() throws Exception { } @Test - public void testCurrentVersion() throws Exception { + public void testCurrentVersion() { AppVersion v; v = AppVersion.parse(RDF4J.getVersion()); assertEquals(RDF4J.getVersion(), v.toString()); } @Test - public void testCompare1() throws Exception { + public void testCompare1() { AppVersion v1 = AppVersion.parse("1.0M1"); AppVersion v2 = AppVersion.parse("1.0"); @@ -99,7 +99,7 @@ public void testCompare1() throws Exception { } @Test - public void testCompare2() throws Exception { + public void testCompare2() { AppVersion v1 = AppVersion.parse("1.0M1-SNAPSHOT"); AppVersion v2 = AppVersion.parse("1.0M1"); diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/Command.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/Command.java index d0eccb930b0..4d3a501c66d 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/Command.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/Command.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.console; -import java.io.IOException; - /** * Abstraction of console commands. * @@ -22,9 +20,8 @@ public interface Command { * Execute the given parameters. * * @param parameters parameters typed by user - * @throws IOException if a problem occurs reading or writing */ - void execute(String... parameters) throws IOException; + void execute(String... parameters); /** * Return the names of the settings used. diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/Console.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/Console.java index 76e860a5668..7d799847e7f 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/Console.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/Console.java @@ -360,9 +360,8 @@ public void start() throws IOException { * * @param command * @return true when exit/quit command is entered - * @throws IOException */ - private boolean executeCommand(String command) throws IOException { + private boolean executeCommand(String command) { boolean exit = false; // only try to parse the command if non-empty. diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/ConsoleIO.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/ConsoleIO.java index c7253419788..e5bb8e6fe00 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/ConsoleIO.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/ConsoleIO.java @@ -104,9 +104,8 @@ public OutputStream getOutputStream() { * Read a command from input * * @return one line of input, or null on error - * @throws IOException */ - protected String readCommand() throws IOException { + protected String readCommand() { try { String line = input.readLine(getPrompt()); if (line == null) { @@ -144,9 +143,8 @@ private String getPrompt() { * Reads multiple lines from the input until a line that with a '.' on its own is read. * * @return input string - * @throws IOException */ - public String readMultiLineInput() throws IOException { + public String readMultiLineInput() { return readMultiLineInput("> "); } @@ -155,9 +153,8 @@ public String readMultiLineInput() throws IOException { * * @param prompt * @return input string - * @throws IOException */ - public String readMultiLineInput(String prompt) throws IOException { + public String readMultiLineInput(String prompt) { String line = input.readLine(prompt); String result = null; @@ -185,9 +182,8 @@ public String readMultiLineInput(String prompt) throws IOException { * * @param message one or multiple messages * @return input string - * @throws IOException */ - public String readln(String... message) throws IOException { + public String readln(String... message) { String prompt = !quiet && message.length > 0 && message[0] != null ? message[0] : ""; String result = input.readLine(prompt); @@ -202,9 +198,8 @@ public String readln(String... message) throws IOException { * * @param prompt prompt to display * @return password string - * @throws IOException */ - public String readPassword(final String prompt) throws IOException { + public String readPassword(final String prompt) { String result = input.readLine(prompt, '*'); if (echo && !result.isEmpty()) { writeln("************"); @@ -280,9 +275,8 @@ public void writeParseError(String prefix, long lineNo, long colNo, String msg) * @param msg confirmation question * @param defaultValue true when default is yes * @return true when continue - * @throws IOException */ - public boolean askProceed(String msg, boolean defaultValue) throws IOException { + public boolean askProceed(String msg, boolean defaultValue) { final String defaultString = defaultValue ? "yes" : "no"; boolean result = force ? true : (cautious ? false : defaultValue); diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/LockRemover.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/LockRemover.java index 6d8a1e0beb3..949b1ce107b 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/LockRemover.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/LockRemover.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.console; -import java.io.IOException; - import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.repository.RepositoryLockedException; @@ -29,11 +27,10 @@ public class LockRemover { * @param repo * @param consoleIO * @return true if lock was removed - * @throws IOException * @throws RepositoryException */ public static boolean tryToRemoveLock(Repository repo, ConsoleIO consoleIO) - throws IOException, RepositoryException { + throws RepositoryException { boolean lockRemoved = false; LockManager lockManager = new DirectoryLockManager(repo.getDataDir()); @@ -52,9 +49,8 @@ public static boolean tryToRemoveLock(Repository repo, ConsoleIO consoleIO) * @param rle * @param consoleIO * @return true if lock was removed - * @throws IOException */ - public static boolean tryToRemoveLock(RepositoryLockedException rle, ConsoleIO consoleIO) throws IOException { + public static boolean tryToRemoveLock(RepositoryLockedException rle, ConsoleIO consoleIO) { boolean lockRemoved = false; if (rle.getCause() instanceof SailLockedException) { diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Clear.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Clear.java index b6bb436f059..4a756fb021f 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Clear.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Clear.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.console.command; -import java.io.IOException; - import org.eclipse.rdf4j.console.ConsoleIO; import org.eclipse.rdf4j.console.ConsoleState; import org.eclipse.rdf4j.console.LockRemover; @@ -101,8 +99,6 @@ private void clear(Repository repository, Resource[] contexts) { } } catch (RepositoryException re) { writeError("Unable to restart repository", re); - } catch (IOException ioe) { - writeError("Unable to remove lock", ioe); } } catch (RepositoryException e) { writeError("Failed to clear repository", e); diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Connect.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Connect.java index 3dd742829ff..f3ad9f3ccb1 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Connect.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Connect.java @@ -132,14 +132,10 @@ private boolean connectRemote(final String url, final String user, final String writeError("Authentication for user '" + user + "' failed"); } else { // Ask user for credentials - try { - writeln("Authentication required"); - final String username = consoleIO.readln("Username: "); - final String password = consoleIO.readPassword("Password: "); - connectRemote(url, username, password); - } catch (IOException ioe) { - writeError("Failed to read user credentials", ioe); - } + writeln("Authentication required"); + final String username = consoleIO.readln("Username: "); + final String password = consoleIO.readPassword("Password: "); + connectRemote(url, username, password); } } catch (IOException | RepositoryException e) { writeError("Failed to access the server", e); diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/ConsoleCommand.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/ConsoleCommand.java index 7191de67e76..182a412f757 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/ConsoleCommand.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/ConsoleCommand.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.console.command; -import java.io.IOException; import java.util.Map; import org.eclipse.rdf4j.console.Command; @@ -123,7 +122,7 @@ public ConsoleCommand(ConsoleIO consoleIO, ConsoleState state, Map valueMap, final Map> variableMap, - Map multilineInput) throws IOException { + Map multilineInput) { if (!variableMap.isEmpty()) { writeln("Please specify values for the following variables:"); } diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Disconnect.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Disconnect.java index 3c906e402e2..256674cf4ba 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Disconnect.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Disconnect.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.console.command; -import java.io.IOException; - import org.eclipse.rdf4j.console.ConsoleIO; import org.eclipse.rdf4j.console.ConsoleState; import org.eclipse.rdf4j.repository.manager.RepositoryManager; @@ -72,7 +70,7 @@ public void execute(boolean verbose) { } @Override - public void execute(String... parameters) throws IOException { + public void execute(String... parameters) { execute(true); } } diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Drop.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Drop.java index e6f07502ddf..e4d28b0eaf6 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Drop.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Drop.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.console.command; -import java.io.IOException; - import org.eclipse.rdf4j.console.ConsoleIO; import org.eclipse.rdf4j.console.ConsoleState; import org.eclipse.rdf4j.repository.RepositoryException; @@ -52,7 +50,7 @@ public Drop(ConsoleIO consoleIO, ConsoleState state, Close close) { } @Override - public void execute(String... tokens) throws IOException { + public void execute(String... tokens) { if (tokens.length < 2) { writeln(getHelpLong()); } else { @@ -77,12 +75,11 @@ public void execute(String... tokens) throws IOException { * Try to drop a repository after confirmation from user * * @param repoID repository ID - * @throws IOException * @throws RepositoryException * @throws RepositoryConfigException */ private void dropRepository(final String repoID) - throws IOException, RepositoryException, RepositoryConfigException { + throws RepositoryException, RepositoryConfigException { boolean proceed = askProceed("WARNING: you are about to drop repository '" + repoID + "'.", true); if (proceed && !state.getManager().isSafeToRemove(repoID)) { proceed = askProceed("WARNING: dropping this repository may break another that is proxying it.", diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Federate.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Federate.java index 493332e3893..cc7e04c0a9d 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Federate.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Federate.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.console.command; -import java.io.IOException; -import java.net.MalformedURLException; import java.util.Arrays; import java.util.Deque; import java.util.HashSet; @@ -67,10 +65,9 @@ public Federate(ConsoleIO consoleIO, ConsoleState state) { * Executes a 'federate' command for the RDF4J Console. * * @param parameters the expectations for the tokens in this array are fully documented in {@link PrintHelp} . - * @throws java.io.IOException */ @Override - public void execute(String... parameters) throws IOException { + public void execute(String... parameters) { if (parameters.length < 4) { writeln(getHelpLong()); } else { @@ -123,9 +120,9 @@ private void federate(String fedID, Deque memberIDs) { manager.addRepositoryConfig(config); writeln("Federation created."); } - } catch (RepositoryConfigException | RepositoryException | MalformedURLException rce) { + } catch (RepositoryConfigException | RepositoryException rce) { writeError("Federation failed", rce); - } catch (RDF4JException | IOException rce) { + } catch (RDF4JException rce) { writeError("I/O exception on federation", rce); } } diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Load.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Load.java index d67b1205e6d..3e780507c8c 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Load.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Load.java @@ -173,8 +173,6 @@ private void handleReadOnlyException(Repository repository, RepositoryReadOnlyEx } } catch (RepositoryException e) { writeError("Unable to restart repository", e); - } catch (IOException e) { - writeError("Unable to remove lock", e); } } diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Open.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Open.java index 13401bf6221..9f3f0212a02 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Open.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Open.java @@ -10,8 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.console.command; -import java.io.IOException; - import org.eclipse.rdf4j.console.ConsoleIO; import org.eclipse.rdf4j.console.ConsoleState; import org.eclipse.rdf4j.console.LockRemover; @@ -85,14 +83,10 @@ public void openRepository(final String repoID) { writeln("Opened repository '" + repoID + "'"); } } catch (RepositoryLockedException e) { - try { - if (LockRemover.tryToRemoveLock(e, consoleIO)) { - openRepository(repoID); - } else { - writeError(OPEN_FAILURE, e); - } - } catch (IOException ioe) { - writeError("Unable to remove lock", ioe); + if (LockRemover.tryToRemoveLock(e, consoleIO)) { + openRepository(repoID); + } else { + writeError(OPEN_FAILURE, e); } } catch (RepositoryConfigException | RepositoryException e) { writeError(OPEN_FAILURE, e); diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/QueryEvaluator.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/QueryEvaluator.java index f5c163d257f..06cfde2e29a 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/QueryEvaluator.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/QueryEvaluator.java @@ -68,7 +68,7 @@ public abstract class QueryEvaluator extends ConsoleCommand { private final TupleAndGraphQueryEvaluator evaluator; private final List sparqlQueryStart = Arrays - .asList(new String[] { "select", "construct", "describe", "ask", "prefix", "base" }); + .asList("select", "construct", "describe", "ask", "prefix", "base"); private final long MAX_INPUT = 1_000_000; @@ -238,14 +238,10 @@ private String readMultiline(QueryLanguage queryLn, String queryText) { if (!str.isEmpty()) { return str; } - try { - writeln("Enter multi-line " + queryLn.getName() + " query " - + "(terminate with line containing single '.')"); - return consoleIO.readMultiLineInput(); - } catch (IOException e) { - writeError("Failed to read query", e); - } - return null; + + writeln("Enter multi-line " + queryLn.getName() + " query " + + "(terminate with line containing single '.')"); + return consoleIO.readMultiLineInput(); } /** diff --git a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Show.java b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Show.java index 63507b44a44..114fe4525af 100644 --- a/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Show.java +++ b/tools/console/src/main/java/org/eclipse/rdf4j/console/command/Show.java @@ -119,7 +119,7 @@ private void showNamespaces() { } try (RepositoryConnection con = repository.getConnection()) { - try (CloseableIteration namespaces = con.getNamespaces()) { + try (CloseableIteration namespaces = con.getNamespaces()) { if (namespaces.hasNext()) { writeln(OUTPUT_SEPARATOR); while (namespaces.hasNext()) { @@ -147,7 +147,7 @@ private void showContexts() { } try (RepositoryConnection con = repository.getConnection()) { - try (CloseableIteration contexts = con.getContextIDs()) { + try (CloseableIteration contexts = con.getContextIDs()) { if (contexts.hasNext()) { writeln(OUTPUT_SEPARATOR); while (contexts.hasNext()) { diff --git a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/AbstractCommandTest.java b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/AbstractCommandTest.java index c36e43ba31e..c6e439ef2a6 100644 --- a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/AbstractCommandTest.java +++ b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/AbstractCommandTest.java @@ -91,7 +91,7 @@ public class AbstractCommandTest { }).collect(Collectors.toMap(m -> (String) m[0], m -> (ConsoleSetting) m[1])); @AfterEach - public void tearDown() throws Exception { + public void tearDown() { if (manager != null) { manager.shutDown(); } diff --git a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/ConvertTest.java b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/ConvertTest.java index a3a0208f811..cdd79de05d0 100644 --- a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/ConvertTest.java +++ b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/ConvertTest.java @@ -51,7 +51,7 @@ public void tearDown() { } @Test - public final void testConvert() throws IOException { + public final void testConvert() { File json = new File(locationFile, "alien.jsonld"); cmd.execute("convert", from.getAbsolutePath(), json.getAbsolutePath()); @@ -67,7 +67,7 @@ public final void testConvert() throws IOException { } @Test - public final void testConvertWorkDir() throws IOException { + public final void testConvertWorkDir() { setWorkingDir(cmd); File json = new File(locationFile, "alien.jsonld"); @@ -96,7 +96,7 @@ public final void testConvertParseError() throws IOException { } @Test - public final void testConvertInvalidFormat() throws IOException { + public final void testConvertInvalidFormat() { File qyx = new File(locationFile, "alien.qyx"); cmd.execute("convert", from.toString(), qyx.toString()); verify(mockConsoleIO).writeError("No RDF writer for " + qyx.toString()); diff --git a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/DropTest.java b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/DropTest.java index f3a0b80bb21..d16355c84c7 100644 --- a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/DropTest.java +++ b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/DropTest.java @@ -50,13 +50,13 @@ public void setUp() throws UnsupportedEncodingException, IOException, RDF4JExcep drop = new Drop(mockConsoleIO, mockConsoleState, new Close(mockConsoleIO, mockConsoleState)); } - private void setUserDropConfirm(boolean confirm) throws IOException { + private void setUserDropConfirm(boolean confirm) { when(mockConsoleIO.askProceed(startsWith("WARNING: you are about to drop repository '"), anyBoolean())) .thenReturn(confirm); } @Test - public final void testSafeDrop() throws RepositoryException, IOException { + public final void testSafeDrop() throws RepositoryException { setUserDropConfirm(true); assertThat(manager.isSafeToRemove(PROXY_ID)).isTrue(); drop.execute("drop", PROXY_ID); @@ -67,7 +67,7 @@ public final void testSafeDrop() throws RepositoryException, IOException { } @Test - public final void testUnsafeDropCancel() throws RepositoryException, IOException { + public final void testUnsafeDropCancel() throws RepositoryException { setUserDropConfirm(true); assertThat(manager.isSafeToRemove(MEMORY_MEMBER_ID1)).isFalse(); when(mockConsoleIO.askProceed(startsWith("WARNING: dropping this repository may break"), anyBoolean())) @@ -77,7 +77,7 @@ public final void testUnsafeDropCancel() throws RepositoryException, IOException } @Test - public final void testUserAbortedUnsafeDropBeforeWarning() throws IOException { + public final void testUserAbortedUnsafeDropBeforeWarning() { setUserDropConfirm(false); drop.execute("drop", MEMORY_MEMBER_ID1); verify(mockConsoleIO, never()).askProceed(startsWith("WARNING: dropping this repository may break"), diff --git a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/FederateTest.java b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/FederateTest.java index f4935a6f28f..7f9d7b27490 100644 --- a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/FederateTest.java +++ b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/FederateTest.java @@ -76,7 +76,7 @@ public void setUp() throws Exception { when(mockConsoleIO.readln("Federation Description (optional): ")).thenReturn(FED_DESCRIPTION); } - private void execute(String... args) throws Exception { + private void execute(String... args) { List execArgs = new ArrayList<>(args.length + 1); execArgs.add("federate"); Collections.addAll(execArgs, args); @@ -84,93 +84,93 @@ private void execute(String... args) throws Exception { } @Test - public void testNoArgumentsPrintsHelp() throws Exception { + public void testNoArgumentsPrintsHelp() { execute(); verify(mockConsoleIO).writeln(federate.getHelpLong()); } @Test - public void testOneArgumentPrintsHelp() throws Exception { + public void testOneArgumentPrintsHelp() { execute(FED_ID); verify(mockConsoleIO).writeln(federate.getHelpLong()); } @Test - public void testTwoArgumentsPrintsHelp() throws Exception { + public void testTwoArgumentsPrintsHelp() { execute(FED_ID, MEMORY_MEMBER_ID1); verify(mockConsoleIO).writeln(federate.getHelpLong()); } @Test - public void testInvalidArgumentPrintsError() throws Exception { + public void testInvalidArgumentPrintsError() { execute("type=memory", FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID2); verifyFailure(); } @Test - public void testDuplicateMembersPrintsError() throws Exception { + public void testDuplicateMembersPrintsError() { execute(FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID1); verifyFailure(); } @Test - public void testFedSameAsMemberPrintsError() throws Exception { + public void testFedSameAsMemberPrintsError() { execute(FED_ID, MEMORY_MEMBER_ID1, FED_ID, MEMORY_MEMBER_ID1); verifyFailure(); } @Test - public void testFedAlreadyExistsPrintsSpecificError() throws Exception { + public void testFedAlreadyExistsPrintsSpecificError() { execute(MEMORY_MEMBER_ID1, FED_ID, MEMORY_MEMBER_ID2); verifyFailure(MEMORY_MEMBER_ID1 + " already exists."); } @Test - public void testNonexistentMemberPrintsSpecificError() throws Exception { + public void testNonexistentMemberPrintsSpecificError() { execute(FED_ID, MEMORY_MEMBER_ID1, "FreeLunch"); verifyFailure("FreeLunch does not exist."); } @Test - public void testFederateMemoryMembersSuccess() throws Exception { + public void testFederateMemoryMembersSuccess() { execute(FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID2); verifySuccess(ProxyRepositoryFactory.REPOSITORY_TYPE, ProxyRepositoryFactory.REPOSITORY_TYPE); long expectedSize = getSize(MEMORY_MEMBER_ID1) + getSize(MEMORY_MEMBER_ID2); assertThat(getSize(FED_ID)).isEqualTo(expectedSize); } - private long getSize(String memberID) throws Exception { + private long getSize(String memberID) { try (RepositoryConnection connection = manager.getRepository(memberID).getConnection()) { return connection.size(); } } @Test - public void testFederateSucceedsWithHTTPandSPARQLmembers() throws Exception { + public void testFederateSucceedsWithHTTPandSPARQLmembers() { execute(FED_ID, HTTP_MEMBER_ID, SPARQL_MEMBER_ID); verifySuccess(HTTPRepositoryFactory.REPOSITORY_TYPE, SPARQLRepositoryFactory.REPOSITORY_TYPE); } @Test - public void testFederateHTTPtypeSucceeds() throws Exception { + public void testFederateHTTPtypeSucceeds() { execute(FED_ID, HTTP_MEMBER_ID, HTTP2_MEMBER_ID); verifySuccess(HTTPRepositoryFactory.REPOSITORY_TYPE, HTTPRepositoryFactory.REPOSITORY_TYPE); } @Test - public void testFederateSPARQLtypeSucceeds() throws Exception { + public void testFederateSPARQLtypeSucceeds() { execute(FED_ID, SPARQL_MEMBER_ID, SPARQL2_MEMBER_ID); verifySuccess(SPARQLRepositoryFactory.REPOSITORY_TYPE, SPARQLRepositoryFactory.REPOSITORY_TYPE); } @Test - public void testFullyHeterogeneousSuccess() throws Exception { + public void testFullyHeterogeneousSuccess() { execute(FED_ID, SPARQL_MEMBER_ID, MEMORY_MEMBER_ID1, HTTP_MEMBER_ID); verifySuccess(SPARQLRepositoryFactory.REPOSITORY_TYPE, ProxyRepositoryFactory.REPOSITORY_TYPE, HTTPRepositoryFactory.REPOSITORY_TYPE); } - private void verifySuccess(String... memberTypes) throws Exception { + private void verifySuccess(String... memberTypes) { assertThat(manager.hasRepositoryConfig(FED_ID)).isTrue(); verify(mockConsoleIO, times(1)).readln("Federation Description (optional): "); verify(mockConsoleIO, times(1)).writeln("Federation created."); @@ -183,7 +183,7 @@ private void verifySuccess(String... memberTypes) throws Exception { assertThat(members.filter(null, FEDX.REPOSITORY_NAME, null).objects()).hasSameSizeAs(memberTypes); } - private void verifyFailure(String... error) throws Exception { + private void verifyFailure(String... error) { if (error.length > 0) { verify(mockConsoleIO).writeError(error[0]); } else { diff --git a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/SparqlTest.java b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/SparqlTest.java index 7e9d28c9bbe..e1ba9f63ffc 100644 --- a/tools/console/src/test/java/org/eclipse/rdf4j/console/command/SparqlTest.java +++ b/tools/console/src/test/java/org/eclipse/rdf4j/console/command/SparqlTest.java @@ -55,13 +55,13 @@ public void setUp() throws IOException, RDF4JException { } @Test - public final void testSelectError() throws IOException { + public final void testSelectError() { cmd.executeQuery("select ?s ?p ?o where { ?s ?p ?o }", "select"); verify(mockConsoleIO, never()).writeError(anyString()); } @Test - public final void testSelectMissingBindings() throws IOException { + public final void testSelectMissingBindings() { cmd.executeQuery("select ?s ?p ?o where { ?s a foaf:Organization }", "select"); verify(mockConsoleIO, never()).writeError(anyString()); } @@ -124,7 +124,7 @@ public final void testOutputFileConstructWorkdir() throws IOException { } @Test - public final void testOutputFileWrongFormat() throws IOException { + public final void testOutputFileWrongFormat() { File f = new File(locationFile, "out.ttl"); // SELECT should use sparql result format, not a triple file format diff --git a/tools/console/src/test/java/org/eclipse/rdf4j/console/setting/LogLevelTest.java b/tools/console/src/test/java/org/eclipse/rdf4j/console/setting/LogLevelTest.java index 266cee6433b..312e1a4254d 100644 --- a/tools/console/src/test/java/org/eclipse/rdf4j/console/setting/LogLevelTest.java +++ b/tools/console/src/test/java/org/eclipse/rdf4j/console/setting/LogLevelTest.java @@ -39,7 +39,7 @@ public void setUp() { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { ((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(originalLevel); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/FedXConnection.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/FedXConnection.java index d802cb7d3a2..8a719cf05ce 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/FedXConnection.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/FedXConnection.java @@ -99,7 +99,7 @@ public void setTransactionSettings(TransactionSetting... settings) { } @Override - protected CloseableIteration evaluateInternal(TupleExpr query, + protected CloseableIteration evaluateInternal(TupleExpr query, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { final TupleExpr originalQuery = query; @@ -164,7 +164,7 @@ protected CloseableIteration eva queryBindings = actualQueryBindings; } - CloseableIteration res = null; + CloseableIteration res = null; try { res = strategy.evaluate(query, queryBindings); @@ -174,8 +174,7 @@ protected CloseableIteration eva if (originalQuery instanceof PassThroughTupleExpr && res instanceof EmptyIteration) { ((PassThroughTupleExpr) originalQuery).setPassedThrough(true); } - res = new StopRemainingExecutionsOnCloseIteration(res, queryInfo); - return res; + return new StopRemainingExecutionsOnCloseIteration(res, queryInfo); } catch (Throwable t) { if (res != null) { res.close(); @@ -234,7 +233,7 @@ protected void commitInternal() throws SailException { } @Override - protected CloseableIteration getContextIDsInternal() throws SailException { + protected CloseableIteration getContextIDsInternal() throws SailException { FederationEvalStrategy strategy = federationContext.createStrategy(new SimpleDataset()); WorkerUnionBase union = new SynchronousWorkerUnion<>(new QueryInfo("getContextIDsInternal", null, @@ -244,7 +243,7 @@ protected CloseableIteration getContextIDsInt for (Endpoint e : federation.getMembers()) { union.addTask(new ParallelTask<>() { @Override - public CloseableIteration performTask() throws Exception { + public CloseableIteration performTask() { try (RepositoryConnection conn = e.getConnection()) { // we need to materialize the contexts as they are only accessible // while the connection is open @@ -268,7 +267,7 @@ public void cancel() { return new DistinctIteration<>(new ExceptionConvertingIteration<>(union) { @Override - protected SailException convert(Exception e) { + protected SailException convert(RuntimeException e) { return new SailException(e); } }); @@ -282,14 +281,14 @@ protected String getNamespaceInternal(String prefix) throws SailException { } @Override - protected CloseableIteration getNamespacesInternal() throws SailException { + protected CloseableIteration getNamespacesInternal() throws SailException { // do not support this feature, but also do not throw an exception // as this method is expected for the RDF4J workbench to work return new EmptyIteration<>(); } @Override - protected CloseableIteration getStatementsInternal(Resource subj, IRI pred, + protected CloseableIteration getStatementsInternal(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws SailException { try { @@ -298,12 +297,12 @@ protected CloseableIteration getStatementsIn QueryInfo queryInfo = new QueryInfo(subj, pred, obj, 0, includeInferred, federationContext, strategy, dataset); federationContext.getMonitoringService().monitorQuery(queryInfo); - CloseableIteration res = null; + CloseableIteration res = null; try { res = strategy.getStatements(queryInfo, subj, pred, obj, contexts); return new ExceptionConvertingIteration<>(res) { @Override - protected SailException convert(Exception e) { + protected SailException convert(RuntimeException e) { return new SailException(e); } }; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/FedXFactory.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/FedXFactory.java index 522ff1debc4..6e686ac131e 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/FedXFactory.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/FedXFactory.java @@ -53,10 +53,9 @@ public class FedXFactory { * * @return the configured FedX federation {@link Sail} wrapped in a {@link FedXRepository} * - * @throws Exception */ public static FedXRepository createSparqlFederation( - List sparqlEndpoints) throws Exception { + List sparqlEndpoints) { return newFederation().withSparqlEndpoints(sparqlEndpoints).create(); } @@ -68,10 +67,8 @@ public static FedXRepository createSparqlFederation( * * @return the configured FedX federation {@link Sail} wrapped in a {@link FedXRepository} * - * @throws Exception */ - public static FedXRepository createFederation(File dataConfig) - throws Exception { + public static FedXRepository createFederation(File dataConfig) { return newFederation().withMembers(dataConfig).create(); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/BoundFiltersNode.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/BoundFiltersNode.java index c30bb64e82e..872d9565c59 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/BoundFiltersNode.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/BoundFiltersNode.java @@ -43,6 +43,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + @Override public String getSignature() { StringBuilder sb = new StringBuilder(64); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/CheckStatementPattern.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/CheckStatementPattern.java index 9c14ba86f3d..eb2f4de62e1 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/CheckStatementPattern.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/CheckStatementPattern.java @@ -178,7 +178,7 @@ public void setTotalTimeNanosActual(long totalTimeNanosActual) { } @Override - public CloseableIteration evaluate(BindingSet bindings) + public CloseableIteration evaluate(BindingSet bindings) throws QueryEvaluationException { StatementPattern st = (StatementPattern) stmt; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ConjunctiveFilterExpr.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ConjunctiveFilterExpr.java index f3b3526f2c2..3e2a9857c64 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ConjunctiveFilterExpr.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ConjunctiveFilterExpr.java @@ -15,6 +15,7 @@ import java.util.List; import org.eclipse.rdf4j.query.algebra.AbstractQueryModelNode; +import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; /** @@ -72,4 +73,9 @@ public void visitChildren(QueryModelVisitor visitor) } } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new UnsupportedOperationException(); + } + } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ExclusiveGroup.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ExclusiveGroup.java index 6a7311e7f15..d89b93e8a5b 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ExclusiveGroup.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ExclusiveGroup.java @@ -25,6 +25,7 @@ import org.eclipse.rdf4j.query.MalformedQueryException; import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.AbstractQueryModelNode; +import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; import org.eclipse.rdf4j.repository.RepositoryException; @@ -91,6 +92,11 @@ public void visitChildren(QueryModelVisitor visitor) } } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new UnsupportedOperationException(); + } + @Override public void visit(QueryModelVisitor visitor) throws X { @@ -160,7 +166,7 @@ public boolean hasFreeVarsFor(BindingSet bindings) { } @Override - public CloseableIteration evaluate(BindingSet bindings) + public CloseableIteration evaluate(BindingSet bindings) throws QueryEvaluationException { try { diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ExclusiveStatement.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ExclusiveStatement.java index facb480d32b..7b8080aa8a6 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ExclusiveStatement.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/ExclusiveStatement.java @@ -47,10 +47,10 @@ public StatementSource getOwner() { } @Override - public CloseableIteration evaluate( + public CloseableIteration evaluate( BindingSet bindings) throws QueryEvaluationException { - CloseableIteration res = null; + CloseableIteration res = null; try { diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FedXService.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FedXService.java index 9da8dd3092a..d425c1bc72a 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FedXService.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FedXService.java @@ -74,6 +74,15 @@ public void visitChildren(QueryModelVisitor visitor) th expr.visit(visitor); } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + if (expr == current) { + expr = (Service) replacement; + } else { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + } + @Override public FedXService clone() { return (FedXService) super.clone(); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FedXStatementPattern.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FedXStatementPattern.java index 13e1928bcaf..5499e7d8520 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FedXStatementPattern.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FedXStatementPattern.java @@ -18,8 +18,10 @@ import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.algebra.AbstractQueryModelNode; +import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; import org.eclipse.rdf4j.query.algebra.StatementPattern; +import org.eclipse.rdf4j.query.algebra.Var; import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -177,13 +179,16 @@ public void addBoundFilter(String varName, Value value) { // visit Var nodes and set value for matching var names if (getSubjectVar().getName().equals(varName)) { - getSubjectVar().setValue(value); + Var var = getSubjectVar(); + var.replaceWith(new Var(var.getName(), value, var.isAnonymous(), var.isConstant())); } if (getPredicateVar().getName().equals(varName)) { - getPredicateVar().setValue(value); + Var var = getPredicateVar(); + var.replaceWith(new Var(var.getName(), value, var.isAnonymous(), var.isConstant())); } if (getObjectVar().getName().equals(varName)) { - getObjectVar().setValue(value); + Var var = getObjectVar(); + var.replaceWith(new Var(var.getName(), value, var.isAnonymous(), var.isConstant())); } boundFilters.addBinding(varName, value); @@ -244,5 +249,10 @@ public void visit(QueryModelVisitor visitor) throws X { public void visitChildren(QueryModelVisitor visitor) throws X { // no-op } + + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } } } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FilterExpr.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FilterExpr.java index 11694f423f7..4ab1508c9cb 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FilterExpr.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/FilterExpr.java @@ -15,6 +15,7 @@ import org.eclipse.rdf4j.query.algebra.AbstractQueryModelNode; import org.eclipse.rdf4j.query.algebra.Compare; import org.eclipse.rdf4j.query.algebra.Compare.CompareOp; +import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; import org.eclipse.rdf4j.query.algebra.ValueExpr; @@ -49,6 +50,15 @@ public void visitChildren(QueryModelVisitor visitor) expr.visit(visitor); } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + if (expr == current) { + expr = (ValueExpr) replacement; + } else { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + } + public ValueExpr getExpression() { return expr; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/NTuple.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/NTuple.java index ab318f31159..fa0cb4b00b4 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/NTuple.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/NTuple.java @@ -99,7 +99,7 @@ public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) args.set(index, (TupleExpr) replacement); replacement.setParentNode(this); } else { - super.replaceChildNode(current, replacement); + throw new IllegalArgumentException("Node is not a child node: " + current); } } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/PassThroughTupleExpr.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/PassThroughTupleExpr.java index deff3bf110c..ca7b8c47954 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/PassThroughTupleExpr.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/PassThroughTupleExpr.java @@ -18,6 +18,7 @@ import org.eclipse.rdf4j.federated.util.QueryAlgebraUtil; import org.eclipse.rdf4j.query.TupleQueryResultHandler; import org.eclipse.rdf4j.query.algebra.AbstractQueryModelNode; +import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; import org.eclipse.rdf4j.query.algebra.TupleExpr; @@ -57,6 +58,11 @@ public void visitChildren(QueryModelVisitor visitor) th } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new UnsupportedOperationException(); + } + public TupleQueryResultHandler getResultHandler() { return resultHandler; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/SingleSourceQuery.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/SingleSourceQuery.java index f34643fb8cd..d0f43eecb00 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/SingleSourceQuery.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/SingleSourceQuery.java @@ -15,6 +15,7 @@ import org.eclipse.rdf4j.federated.endpoint.Endpoint; import org.eclipse.rdf4j.federated.structures.QueryInfo; import org.eclipse.rdf4j.query.algebra.AbstractQueryModelNode; +import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; import org.eclipse.rdf4j.query.algebra.TupleExpr; @@ -68,6 +69,11 @@ public void visitChildren(QueryModelVisitor visitor) parsedQuery.visit(visitor); } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new UnsupportedOperationException(); + } + @Override public String getSignature() { return super.getSignature() + " @" + source.getId(); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementSource.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementSource.java index 00cce321f59..ae70a174d14 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementSource.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementSource.java @@ -11,6 +11,7 @@ package org.eclipse.rdf4j.federated.algebra; import org.eclipse.rdf4j.query.algebra.AbstractQueryModelNode; +import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.QueryModelVisitor; /** @@ -49,6 +50,11 @@ public void visitChildren(QueryModelVisitor visitor) th // no-op } + @Override + public void replaceChildNode(QueryModelNode current, QueryModelNode replacement) { + throw new IllegalArgumentException("Node is not a child node: " + current); + } + @Override public String getSignature() { StringBuilder sb = new StringBuilder(64); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementSourcePattern.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementSourcePattern.java index 5f6a36bb72e..efb528f6b0c 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementSourcePattern.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementSourcePattern.java @@ -55,7 +55,7 @@ public void addStatementSource(StatementSource statementSource) { } @Override - public CloseableIteration evaluate(BindingSet bindings) + public CloseableIteration evaluate(BindingSet bindings) throws QueryEvaluationException { WorkerUnionBase union = null; @@ -88,7 +88,7 @@ public CloseableIteration evaluate(Binding queryInfo.getDataset()); } catch (IllegalQueryException e1) { /* all vars are bound, this must be handled as a check query, can occur in joins */ - CloseableIteration res = handleStatementSourcePatternCheck( + CloseableIteration res = handleStatementSourcePatternCheck( bindings); if (boundFilters != null && !(res instanceof EmptyIteration)) { res = new InsertBindingsIteration(res, boundFilters); @@ -129,7 +129,7 @@ public CloseableIteration evaluate(Binding } } - protected CloseableIteration handleStatementSourcePatternCheck( + protected CloseableIteration handleStatementSourcePatternCheck( BindingSet bindings) throws RepositoryException, MalformedQueryException, QueryEvaluationException { // if at least one source has statements, we can return this binding set as result diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementTupleExpr.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementTupleExpr.java index ab70c0f524b..d98ef61ca31 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementTupleExpr.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/algebra/StatementTupleExpr.java @@ -53,7 +53,7 @@ public interface StatementTupleExpr extends FedXTupleExpr { * * @throws QueryEvaluationException */ - CloseableIteration evaluate(BindingSet bindings) + CloseableIteration evaluate(BindingSet bindings) throws QueryEvaluationException; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/cache/EndpointEntry.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/cache/EndpointEntry.java index 3632defe700..e6b826614b5 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/cache/EndpointEntry.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/cache/EndpointEntry.java @@ -33,7 +33,7 @@ public boolean doesProvideStatements() { return doesProvideStatements; } - public CloseableIteration getStatements() { + public CloseableIteration getStatements() { throw new UnsupportedOperationException("This operation is not yet supported."); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/endpoint/provider/SailSourceEvaluationStrategyFactory.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/endpoint/provider/SailSourceEvaluationStrategyFactory.java index 0f6965e7fef..533d05b1179 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/endpoint/provider/SailSourceEvaluationStrategyFactory.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/endpoint/provider/SailSourceEvaluationStrategyFactory.java @@ -24,12 +24,14 @@ import org.eclipse.rdf4j.query.algebra.ValueExpr; import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy; import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategyFactory; +import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.QueryOptimizerPipeline; import org.eclipse.rdf4j.query.algebra.evaluation.QueryValueEvaluationStep; import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedService; import org.eclipse.rdf4j.query.algebra.evaluation.impl.EvaluationStatistics; +import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; import org.eclipse.rdf4j.query.algebra.evaluation.optimizer.BindingAssignerOptimizer; /** @@ -118,15 +120,19 @@ public TupleExpr optimize(TupleExpr expr, EvaluationStatistics evaluationStatist } @Override - public CloseableIteration evaluate(Service expr, String serviceUri, - CloseableIteration bindings) throws QueryEvaluationException { - return delegate.evaluate(expr, serviceUri, bindings); + public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) + throws QueryEvaluationException { + return delegate.evaluate(expr, bindings); } @Override - public CloseableIteration evaluate(TupleExpr expr, BindingSet bindings) - throws QueryEvaluationException { - return delegate.evaluate(expr, bindings); + public QueryEvaluationStep precompile(TupleExpr expr) { + return delegate.precompile(expr); + } + + @Override + public QueryEvaluationStep precompile(TupleExpr expr, QueryEvaluationContext context) { + return delegate.precompile(expr, context); } @Override diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/FederationEvalStrategy.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/FederationEvalStrategy.java index 7617941bc38..14fbdbd9dc6 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/FederationEvalStrategy.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/FederationEvalStrategy.java @@ -97,10 +97,12 @@ import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedService; import org.eclipse.rdf4j.query.algebra.evaluation.federation.ServiceJoinIterator; +import org.eclipse.rdf4j.query.algebra.evaluation.impl.DefaultEvaluationStrategy; import org.eclipse.rdf4j.query.algebra.evaluation.impl.EvaluationStatistics; import org.eclipse.rdf4j.query.algebra.evaluation.impl.QueryEvaluationContext; import org.eclipse.rdf4j.query.algebra.evaluation.impl.StrictEvaluationStrategy; import org.eclipse.rdf4j.query.algebra.evaluation.iterator.BadlyDesignedLeftJoinIterator; +import org.eclipse.rdf4j.query.algebra.evaluation.iterator.DescribeIteration; import org.eclipse.rdf4j.query.algebra.evaluation.iterator.HashJoinIteration; import org.eclipse.rdf4j.query.algebra.evaluation.optimizer.ConstantOptimizer; import org.eclipse.rdf4j.query.algebra.evaluation.optimizer.DisjunctiveConstraintOptimizer; @@ -136,11 +138,11 @@ public FederationEvalStrategy(FederationContext federationContext) { super(new org.eclipse.rdf4j.query.algebra.evaluation.TripleSource() { @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( Resource subj, IRI pred, Value obj, Resource... contexts) throws QueryEvaluationException { throw new FedXRuntimeException( - "Federation Strategy does not support org.openrdf.query.algebra.evaluation.TripleSource#getStatements." + "Federation Strategy does not support org.eclipse.rdf4j.query.algebra.evaluation.TripleSource#getStatements." + " If you encounter this exception, please report it."); } @@ -314,8 +316,9 @@ protected void optimizeExclusiveExpressions(TupleExpr query, QueryInfo queryInfo new ExclusiveTupleExprOptimizer().optimize(query); } + @Deprecated(forRemoval = true) @Override - public CloseableIteration evaluate( + public CloseableIteration evaluate( TupleExpr expr, BindingSet bindings) throws QueryEvaluationException { @@ -425,7 +428,7 @@ public QueryEvaluationStep precompile( * @throws MalformedQueryException * @throws QueryEvaluationException */ - public CloseableIteration getStatements(QueryInfo queryInfo, Resource subj, + public CloseableIteration getStatements(QueryInfo queryInfo, Resource subj, IRI pred, Value obj, Resource... contexts) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -472,7 +475,7 @@ public CloseableIteration getStatements(Que return union; } - public CloseableIteration evaluateService(FedXService service, + public CloseableIteration evaluateService(FedXService service, BindingSet bindings) throws QueryEvaluationException { ParallelServiceExecutor pe = new ParallelServiceExecutor(service, this, bindings, federationContext); @@ -480,7 +483,7 @@ public CloseableIteration evaluateService( return pe; } - public CloseableIteration evaluateSingleSourceQuery(SingleSourceQuery query, + public CloseableIteration evaluateSingleSourceQuery(SingleSourceQuery query, BindingSet bindings) throws QueryEvaluationException { try { @@ -494,7 +497,7 @@ public CloseableIteration evaluateSingleSo } - public CloseableIteration evaluateNJoin(NJoin join, BindingSet bindings) + public CloseableIteration evaluateNJoin(NJoin join, BindingSet bindings) throws QueryEvaluationException { return precompile(join).evaluate(bindings); @@ -508,8 +511,7 @@ protected QueryEvaluationStep prepareNJoin(NJoin join, QueryEvaluationContext co ControlledWorkerScheduler joinScheduler = federationContext.getManager().getJoinScheduler(); return bindings -> { - boolean completed = false; - CloseableIteration result = null; + CloseableIteration result = null; try { result = resultProvider.evaluate(bindings); @@ -517,11 +519,11 @@ protected QueryEvaluationStep prepareNJoin(NJoin join, QueryEvaluationContext co result = executeJoin(joinScheduler, result, join.getArg(i), join.getJoinVariables(i), bindings, join.getQueryInfo()); } - completed = true; - } finally { - if (!completed && result != null) { + } catch (Throwable t) { + if (result != null) { result.close(); } + throw t; } return result; }; @@ -537,7 +539,7 @@ protected QueryEvaluationStep prepareNJoin(NJoin join, QueryEvaluationContext co * @throws QueryEvaluationException * @see StrictEvaluationStrategy#evaluate(org.eclipse.rdf4j.query.algebra.LeftJoin, BindingSet) */ - protected CloseableIteration evaluateLeftJoin(FedXLeftJoin leftJoin, + protected CloseableIteration evaluateLeftJoin(FedXLeftJoin leftJoin, final BindingSet bindings) throws QueryEvaluationException { return precompile(leftJoin).evaluate(bindings); @@ -558,7 +560,7 @@ protected QueryEvaluationStep prepareLeftJoin(FedXLeftJoin leftJoin, QueryEvalua final QueryEvaluationStep rightES = precompile(leftJoin.getRightArg(), context); @Override - public CloseableIteration evaluate(BindingSet bindings) { + public CloseableIteration evaluate(BindingSet bindings) { String[] hashJoinAttributeNames = HashJoinIteration.hashJoinAttributeNames(leftJoin); return new HashJoinIteration(leftES, rightES, bindings, true, hashJoinAttributeNames, context); } @@ -620,7 +622,7 @@ private Set retainAll(Set problemVars, Set leftBindingNa return problemVars; } - public CloseableIteration evaluateNaryUnion(NUnion union, BindingSet bindings) + public CloseableIteration evaluateNaryUnion(NUnion union, BindingSet bindings) throws QueryEvaluationException { return precompile(union).evaluate(bindings); } @@ -666,12 +668,12 @@ public QueryEvaluationStep prepareNaryUnion(NUnion union, QueryEvaluationContext * @return the result * @throws QueryEvaluationException */ - protected abstract CloseableIteration executeJoin( + protected abstract CloseableIteration executeJoin( ControlledWorkerScheduler joinScheduler, - CloseableIteration leftIter, TupleExpr rightArg, + CloseableIteration leftIter, TupleExpr rightArg, Set joinVariables, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException; - public abstract CloseableIteration evaluateExclusiveGroup( + public abstract CloseableIteration evaluateExclusiveGroup( ExclusiveGroup group, BindingSet bindings) throws RepositoryException, MalformedQueryException, QueryEvaluationException; @@ -686,7 +688,7 @@ public abstract CloseableIteration evaluat * @throws MalformedQueryException * @throws QueryEvaluationException */ - protected CloseableIteration evaluateExclusiveTupleExpr( + protected CloseableIteration evaluateExclusiveTupleExpr( ExclusiveTupleExpr expr, BindingSet bindings) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -740,7 +742,7 @@ protected QueryEvaluationStep prepareExclusiveTupleExpr( * @return the result iteration * @throws QueryEvaluationException */ - public abstract CloseableIteration evaluateBoundJoinStatementPattern( + public abstract CloseableIteration evaluateBoundJoinStatementPattern( StatementTupleExpr stmt, final List bindings) throws QueryEvaluationException; /** @@ -752,7 +754,7 @@ public abstract CloseableIteration evaluat * @return the result iteration * @throws QueryEvaluationException */ - public abstract CloseableIteration evaluateGroupedCheck( + public abstract CloseableIteration evaluateGroupedCheck( CheckStatementPattern stmt, final List bindings) throws QueryEvaluationException; /** @@ -765,7 +767,7 @@ public abstract CloseableIteration evaluat * @return the result iteration * @throws QueryEvaluationException */ - public CloseableIteration evaluateService(FedXService service, + public CloseableIteration evaluateService(FedXService service, final List bindings) throws QueryEvaluationException { Var serviceRef = service.getService().getServiceRef(); @@ -787,6 +789,7 @@ public CloseableIteration evaluateService( service.getService().getBaseURI()); } + @Deprecated(forRemoval = true) @Override public Value evaluate(ValueExpr expr, BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException { @@ -864,15 +867,14 @@ protected QueryValueEvaluationStep prepare(ConjunctiveFilterExpr node, QueryEval }; } - @Override - public CloseableIteration evaluate(DescribeOperator operator, + public CloseableIteration evaluate(DescribeOperator operator, final BindingSet bindings) throws QueryEvaluationException { if (!(operator instanceof FederatedDescribeOperator)) { throw new FedXRuntimeException( "Expected a FedXDescribeOperator Node. Found " + operator.getClass() + " instead."); } - CloseableIteration iter = null; + CloseableIteration iter = null; try { iter = evaluate(operator.getArg(), bindings); // Note: we need to evaluate the DESCRIBE over the entire federation @@ -887,7 +889,20 @@ public CloseableIteration evaluate(Describ } - protected CloseableIteration evaluateAtStatementSources(Object preparedQuery, + @Override + protected QueryEvaluationStep prepare(DescribeOperator operator, QueryEvaluationContext context) + throws QueryEvaluationException { + if (!(operator instanceof FederatedDescribeOperator)) { + throw new FedXRuntimeException( + "Expected a FedXDescribeOperator Node. Found " + operator.getClass() + " instead."); + } + + QueryEvaluationStep child = precompile(operator.getArg(), context); + return bs -> new FederatedDescribeIteration(child.evaluate(bs), this, operator.getBindingNames(), bs, + ((FederatedDescribeOperator) operator).getQueryInfo()); + } + + protected CloseableIteration evaluateAtStatementSources(Object preparedQuery, List statementSources, QueryInfo queryInfo) throws QueryEvaluationException { if (preparedQuery instanceof String) { return evaluateAtStatementSources((String) preparedQuery, statementSources, queryInfo); @@ -899,11 +914,11 @@ protected CloseableIteration evaluateAtSta "Unsupported type for prepared query: " + preparedQuery.getClass().getCanonicalName()); } - protected CloseableIteration evaluateAtStatementSources(String preparedQuery, + protected CloseableIteration evaluateAtStatementSources(String preparedQuery, List statementSources, QueryInfo queryInfo) throws QueryEvaluationException { try { - CloseableIteration result; + CloseableIteration result; if (statementSources.size() == 1) { Endpoint ownedEndpoint = federationContext.getEndpointManager() @@ -936,12 +951,12 @@ protected CloseableIteration evaluateAtSta } } - protected CloseableIteration evaluateAtStatementSources( + protected CloseableIteration evaluateAtStatementSources( TupleExpr preparedQuery, List statementSources, QueryInfo queryInfo) throws QueryEvaluationException { try { - CloseableIteration result; + CloseableIteration result; if (statementSources.size() == 1) { Endpoint ownedEndpoint = federationContext.getEndpointManager() diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SailFederationEvalStrategy.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SailFederationEvalStrategy.java index d21efe1ed2a..dbe6cf8bfcc 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SailFederationEvalStrategy.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SailFederationEvalStrategy.java @@ -53,7 +53,7 @@ public SailFederationEvalStrategy(FederationContext federationContext) { } @Override - public CloseableIteration evaluateBoundJoinStatementPattern( + public CloseableIteration evaluateBoundJoinStatementPattern( StatementTupleExpr stmt, List bindings) throws QueryEvaluationException { @@ -71,7 +71,7 @@ public CloseableIteration evaluateBoundJoi TupleExpr preparedQuery = QueryAlgebraUtil.selectQueryBoundUnion((StatementPattern) stmt, bindings, filterExpr, isEvaluated); - CloseableIteration result = evaluateAtStatementSources(preparedQuery, + CloseableIteration result = evaluateAtStatementSources(preparedQuery, stmt.getStatementSources(), stmt.getQueryInfo()); // apply filter and/or convert to original bindings @@ -89,7 +89,7 @@ public CloseableIteration evaluateBoundJoi } @Override - public CloseableIteration evaluateGroupedCheck( + public CloseableIteration evaluateGroupedCheck( CheckStatementPattern stmt, List bindings) throws QueryEvaluationException { @@ -99,16 +99,16 @@ public CloseableIteration evaluateGroupedC TupleExpr preparedQuery = QueryAlgebraUtil.selectQueryStringBoundCheck(stmt.getStatementPattern(), bindings); - CloseableIteration result = evaluateAtStatementSources(preparedQuery, + CloseableIteration result = evaluateAtStatementSources(preparedQuery, stmt.getStatementSources(), stmt.getQueryInfo()); return new GroupedCheckConversionIteration(result, bindings); } @Override - public CloseableIteration executeJoin( + public CloseableIteration executeJoin( ControlledWorkerScheduler joinScheduler, - CloseableIteration leftIter, + CloseableIteration leftIter, TupleExpr rightArg, Set joinVars, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { @@ -120,7 +120,7 @@ public CloseableIteration executeJoin( } @Override - public CloseableIteration evaluateExclusiveGroup( + public CloseableIteration evaluateExclusiveGroup( ExclusiveGroup group, BindingSet bindings) throws RepositoryException, MalformedQueryException, QueryEvaluationException { diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SailTripleSource.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SailTripleSource.java index 31621ebfbf7..4baeaa37c09 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SailTripleSource.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SailTripleSource.java @@ -56,7 +56,7 @@ public class SailTripleSource extends TripleSourceBase { } @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( StatementPattern stmt, final BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, @@ -105,7 +105,7 @@ public CloseableIteration getStatements( } @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( Resource subj, IRI pred, Value obj, QueryInfo queryInfo, Resource... contexts) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -123,7 +123,7 @@ public CloseableIteration getStatements( resultHolder.set(new ExceptionConvertingIteration<>(repoResult) { @Override - protected QueryEvaluationException convert(Exception arg0) { + protected QueryEvaluationException convert(RuntimeException arg0) { return new QueryEvaluationException(arg0); } }); @@ -175,7 +175,7 @@ public boolean usePreparedQuery(StatementPattern stmt, QueryInfo queryInfo) { @SuppressWarnings("unchecked") @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( TupleExpr preparedQuery, BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, @@ -200,14 +200,14 @@ public CloseableIteration getStatements( log.debug("Details:", e); } - CloseableIteration res = null; + CloseableIteration res = null; try { if (precompiledQueryNode != null) { - res = (CloseableIteration) sailConn.evaluate( + res = (CloseableIteration) sailConn.evaluate( precompiledQueryNode, null, EmptyBindingSet.getInstance(), queryInfo.getIncludeInferred()); } else { // fallback: attempt the original tuple expression - res = (CloseableIteration) sailConn.evaluate(preparedQuery, + res = (CloseableIteration) sailConn.evaluate(preparedQuery, null, EmptyBindingSet.getInstance(), queryInfo.getIncludeInferred()); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SparqlFederationEvalStrategy.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SparqlFederationEvalStrategy.java index a34ab3e13ef..0be9600d7c1 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SparqlFederationEvalStrategy.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SparqlFederationEvalStrategy.java @@ -62,7 +62,7 @@ public SparqlFederationEvalStrategy(FederationContext federationContext) { } @Override - public CloseableIteration evaluateBoundJoinStatementPattern( + public CloseableIteration evaluateBoundJoinStatementPattern( StatementTupleExpr stmt, List bindings) throws QueryEvaluationException { @@ -80,7 +80,7 @@ public CloseableIteration evaluateBoundJoi String preparedQuery = QueryStringUtil.selectQueryStringBoundJoinVALUES((StatementPattern) stmt, bindings, filterExpr, isEvaluated, stmt.getQueryInfo().getDataset()); - CloseableIteration result = null; + CloseableIteration result = null; try { result = evaluateAtStatementSources(preparedQuery, stmt.getStatementSources(), stmt.getQueryInfo()); @@ -113,7 +113,7 @@ public CloseableIteration evaluateBoundJoi * * @deprecated */ - protected CloseableIteration evaluateBoundJoinStatementPattern_UNION( + protected CloseableIteration evaluateBoundJoinStatementPattern_UNION( StatementTupleExpr stmt, List bindings) throws QueryEvaluationException { @@ -131,7 +131,7 @@ protected CloseableIteration evaluateBound String preparedQuery = QueryStringUtil.selectQueryStringBoundUnion((StatementPattern) stmt, bindings, filterExpr, isEvaluated, stmt.getQueryInfo().getDataset()); - CloseableIteration result = evaluateAtStatementSources(preparedQuery, + CloseableIteration result = evaluateAtStatementSources(preparedQuery, stmt.getStatementSources(), stmt.getQueryInfo()); // apply filter and/or convert to original bindings @@ -149,7 +149,7 @@ protected CloseableIteration evaluateBound } @Override - public CloseableIteration evaluateGroupedCheck( + public CloseableIteration evaluateGroupedCheck( CheckStatementPattern stmt, List bindings) throws QueryEvaluationException { @@ -160,16 +160,16 @@ public CloseableIteration evaluateGroupedC String preparedQuery = QueryStringUtil.selectQueryStringBoundCheck(stmt.getStatementPattern(), bindings, stmt.getQueryInfo().getDataset()); - CloseableIteration result = evaluateAtStatementSources(preparedQuery, + CloseableIteration result = evaluateAtStatementSources(preparedQuery, stmt.getStatementSources(), stmt.getQueryInfo()); return new GroupedCheckConversionIteration(result, bindings); } @Override - public CloseableIteration executeJoin( + public CloseableIteration executeJoin( ControlledWorkerScheduler joinScheduler, - CloseableIteration leftIter, + CloseableIteration leftIter, TupleExpr rightArg, Set joinVars, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { @@ -181,7 +181,7 @@ public CloseableIteration executeJoin( } @Override - public CloseableIteration evaluateExclusiveGroup( + public CloseableIteration evaluateExclusiveGroup( ExclusiveGroup group, BindingSet bindings) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -196,7 +196,7 @@ public CloseableIteration evaluateExclusiv } catch (IllegalQueryException e) { /* no projection vars, e.g. local vars only, can occur in joins */ if (tripleSource.hasStatements(group, bindings)) { - CloseableIteration res = new SingleBindingSetIteration(bindings); + CloseableIteration res = new SingleBindingSetIteration(bindings); if (group.getBoundFilters() != null) { // make sure to insert any values from FILTER expressions that are directly // bound in this expression diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SparqlTripleSource.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SparqlTripleSource.java index 20e857ed03d..ec223efa220 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SparqlTripleSource.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/SparqlTripleSource.java @@ -67,7 +67,7 @@ public class SparqlTripleSource extends TripleSourceBase { } @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( StatementPattern stmt, BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -171,7 +171,7 @@ public boolean usePreparedQuery(StatementPattern stmt, QueryInfo queryInfo) { } @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( TupleExpr preparedQuery, BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -180,7 +180,7 @@ public CloseableIteration getStatements( } @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( Resource subj, IRI pred, Value obj, QueryInfo queryInfo, Resource... contexts) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -193,7 +193,7 @@ public CloseableIteration getStatements( queryInfo.getIncludeInferred(), contexts); resultHolder.set(new ExceptionConvertingIteration<>(repoResult) { @Override - protected QueryEvaluationException convert(Exception ex) { + protected QueryEvaluationException convert(RuntimeException ex) { if (ex instanceof QueryEvaluationException) { return (QueryEvaluationException) ex; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/TripleSource.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/TripleSource.java index 077c78baad2..62ab813de13 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/TripleSource.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/TripleSource.java @@ -53,7 +53,7 @@ public interface TripleSource { * @throws MalformedQueryException * @throws QueryEvaluationException */ - CloseableIteration getStatements(TupleExpr preparedQuery, + CloseableIteration getStatements(TupleExpr preparedQuery, final BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, QueryEvaluationException; @@ -70,30 +70,10 @@ CloseableIteration getStatements(TupleExpr * @throws MalformedQueryException * @throws QueryEvaluationException */ - CloseableIteration getStatements(String preparedQuery, + CloseableIteration getStatements(String preparedQuery, final BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, QueryEvaluationException; - /** - * Evaluate a given SPARQL query of the provided query type at the given source. - * - * @param preparedQuery - * @param queryType - * @param queryInfo - * @return the statements - * @throws RepositoryException - * @throws MalformedQueryException - * @throws QueryEvaluationException - * @Deprecated will be removed in 4.0. Replaced with - * {@link #getStatements(String, BindingSet, QueryType, QueryInfo)} - */ - @Deprecated(forRemoval = true) - default CloseableIteration getStatements(String preparedQuery, - QueryType queryType, QueryInfo queryInfo) - throws RepositoryException, MalformedQueryException, QueryEvaluationException { - return getStatements(preparedQuery, EmptyBindingSet.getInstance(), queryType, queryInfo); - } - /** * Evaluate a given SPARQL query of the provided query type at the given source. * @@ -106,7 +86,7 @@ default CloseableIteration getStatements(S * @throws MalformedQueryException * @throws QueryEvaluationException */ - CloseableIteration getStatements(String preparedQuery, + CloseableIteration getStatements(String preparedQuery, BindingSet queryBindings, QueryType queryType, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, QueryEvaluationException; @@ -124,7 +104,7 @@ CloseableIteration getStatements(String pr * @throws MalformedQueryException * @throws QueryEvaluationException */ - CloseableIteration getStatements(StatementPattern stmt, + CloseableIteration getStatements(StatementPattern stmt, final BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, QueryEvaluationException; @@ -142,7 +122,7 @@ CloseableIteration getStatements(Statement * @throws MalformedQueryException * @throws QueryEvaluationException */ - CloseableIteration getStatements( + CloseableIteration getStatements( Resource subj, IRI pred, Value obj, QueryInfo queryInfo, Resource... contexts) throws RepositoryException, MalformedQueryException, QueryEvaluationException; @@ -189,16 +169,6 @@ boolean hasStatements(Resource subj, IRI pred, Value obj, QueryInfo queryInfo, R boolean hasStatements(ExclusiveTupleExpr expr, BindingSet bindings) throws RepositoryException, MalformedQueryException, QueryEvaluationException; - /** - * - * @return true if a prepared query is to be used preferably, false otherwise - * @deprecated replaced with {@link #usePreparedQuery(StatementPattern, QueryInfo)}, to be removed in 4.0 - */ - @Deprecated(forRemoval = true) - default boolean usePreparedQuery() { - return true; - } - /** * * @param stmt diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/TripleSourceBase.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/TripleSourceBase.java index 4b3a2b845eb..380cbbe8abc 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/TripleSourceBase.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/TripleSourceBase.java @@ -67,7 +67,7 @@ public TripleSourceBase(FederationContext federationContext, Endpoint endpoint) } @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( String preparedQuery, BindingSet queryBindings, QueryType queryType, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -142,7 +142,7 @@ private void applyBindings(Operation operation, BindingSet queryBindings) { } @Override - public CloseableIteration getStatements( + public CloseableIteration getStatements( String preparedQuery, BindingSet bindings, FilterValueExpr filterExpr, QueryInfo queryInfo) throws RepositoryException, MalformedQueryException, QueryEvaluationException { @@ -155,7 +155,7 @@ public CloseableIteration getStatements( // evaluate the query monitorRemoteRequest(); - CloseableIteration res = null; + CloseableIteration res = null; try { res = query.evaluate(); @@ -179,7 +179,9 @@ public CloseableIteration getStatements( res = new InsertBindingsIteration(res, bindings); } - resultHolder.set(new ConsumingIteration(res, federationContext.getConfig().getConsumingIterationMax())); + res = new ConsumingIteration(res, federationContext.getConfig().getConsumingIterationMax()); + + resultHolder.set(res); } catch (Throwable t) { if (res != null) { res.close(); @@ -218,7 +220,7 @@ protected void monitorRemoteRequest() { monitoringService.monitorRemoteRequest(endpoint); } - private CloseableIteration booleanToBindingSetIteration(boolean hasResult) { + private CloseableIteration booleanToBindingSetIteration(boolean hasResult) { if (hasResult) { return new SingleBindingSetIteration(EmptyBindingSet.getInstance()); } @@ -251,8 +253,8 @@ protected void applyMaxExecutionTimeUpperBound(Operation operation) { FedXUtil.applyMaxQueryExecutionTime(operation, federationContext); } - private CloseableIteration closeConn(RepositoryConnection dependentConn, - CloseableIteration inner) { + private CloseableIteration closeConn(RepositoryConnection dependentConn, + CloseableIteration inner) { return new CloseDependentConnectionIteration<>(inner, dependentConn); } @@ -263,11 +265,11 @@ private CloseableIteration closeConn(Repository * @param operation the {@link ConnectionOperation} * @return the resulting iteration */ - protected CloseableIteration withConnection(ConnectionOperation operation) { + protected CloseableIteration withConnection(ConnectionOperation operation) { ResultHolder resultHolder = new ResultHolder<>(); RepositoryConnection conn = null; - CloseableIteration res = null; + CloseableIteration res = null; try { conn = endpoint.getConnection(); @@ -329,16 +331,16 @@ protected interface ConnectionOperation { * @param * @author Andreas Schwarte */ - protected static class ResultHolder implements Supplier> { + protected static class ResultHolder implements Supplier> { - protected CloseableIteration result; + protected CloseableIteration result; - public void set(CloseableIteration result) { + public void set(CloseableIteration result) { this.result = result; } @Override - public CloseableIteration get() { + public CloseableIteration get() { return result; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ControlledWorkerScheduler.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ControlledWorkerScheduler.java index 8e197288657..f677ca46ea4 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ControlledWorkerScheduler.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ControlledWorkerScheduler.java @@ -23,7 +23,6 @@ import org.eclipse.rdf4j.federated.evaluation.union.ControlledWorkerUnion; import org.eclipse.rdf4j.federated.exception.ExceptionUtil; import org.eclipse.rdf4j.federated.exception.FedXRuntimeException; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,16 +48,6 @@ public class ControlledWorkerScheduler implements Scheduler, TaskWrapperAw private final String name; private TaskWrapper taskWrapper; - /** - * Construct a new instance with 20 workers. - * - * @deprecated use {@link #ControlledWorkerScheduler(int, String)}. Scheduled to be removed in 4.0 - */ - @Deprecated(forRemoval = true) - public ControlledWorkerScheduler() { - this(20, "FedX Worker"); - } - /** * Construct a new instance with the specified number of workers and the given name. * @@ -156,7 +145,7 @@ public void done() { } @Override - public void handleResult(CloseableIteration res) { + public void handleResult(CloseableIteration res) { /* not needed here since the result is passed directly to the control instance */ throw new RuntimeException("Unsupported Operation for this scheduler."); } @@ -214,7 +203,7 @@ public WorkerRunnable(ParallelTask task) { @Override public void run() { - CloseableIteration res = null; + CloseableIteration res = null; try { diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/FedXQueueCursor.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/FedXQueueCursor.java index 76c62f841e0..3f460a6ad0b 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/FedXQueueCursor.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/FedXQueueCursor.java @@ -28,7 +28,7 @@ * @param * @author Andreas Schwarte */ -public class FedXQueueCursor extends QueueCursor> { +public class FedXQueueCursor extends QueueCursor> { private static final Logger log = LoggerFactory.getLogger(FedXQueueCursor.class); @@ -38,7 +38,7 @@ public static FedXQueueCursor create(int capacity, WeakReference calle } public static FedXQueueCursor create(int capacity) { - BlockingQueue> queue = new ArrayBlockingQueue<>(capacity, + BlockingQueue> queue = new ArrayBlockingQueue<>(capacity, false); return new FedXQueueCursor<>(queue); } @@ -48,9 +48,9 @@ public static FedXQueueCursor create(int capacity) { * we can close the non-consumed iterations from the queue. Note that the private queue of the super class is not * accessible. */ - private final BlockingQueue> queueRef; + private final BlockingQueue> queueRef; - private FedXQueueCursor(BlockingQueue> queue) { + private FedXQueueCursor(BlockingQueue> queue) { super(queue); this.queueRef = queue; } @@ -80,7 +80,7 @@ public void handleClose() throws QueryEvaluationException { try { Object take = queueRef.poll(); if (take instanceof CloseableIteration) { - ((CloseableIteration) take).close(); + ((CloseableIteration) take).close(); } } catch (Throwable t) { if (t instanceof InterruptedException) { diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelExecutor.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelExecutor.java index fbd61e275f7..a70690f9801 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelExecutor.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelExecutor.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.federated.evaluation.join.JoinExecutorBase; import org.eclipse.rdf4j.federated.evaluation.union.UnionExecutorBase; import org.eclipse.rdf4j.federated.structures.QueryInfo; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * Interface for any parallel cursor, i.e. result iterations. Implementations can act as control for scheduler @@ -34,7 +33,7 @@ public interface ParallelExecutor extends Runnable { * * @param res */ - void addResult(CloseableIteration res); + void addResult(CloseableIteration res); /** * Toss some exception to the controlling instance diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelExecutorBase.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelExecutorBase.java index 14d3ff01eda..514fc2e0c08 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelExecutorBase.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelExecutorBase.java @@ -33,7 +33,7 @@ * @see JoinExecutorBase * @see UnionExecutorBase */ -public abstract class ParallelExecutorBase extends LookAheadIteration +public abstract class ParallelExecutorBase extends LookAheadIteration implements ParallelExecutor { protected static final Logger log = LoggerFactory.getLogger(ParallelExecutorBase.class); @@ -48,7 +48,7 @@ public abstract class ParallelExecutorBase extends LookAheadIteration rightQueue = FedXQueueCursor.create(1024); - protected volatile CloseableIteration rightIter; + protected volatile CloseableIteration rightIter; protected volatile boolean finished = false; public ParallelExecutorBase(QueryInfo queryInfo) throws QueryEvaluationException { @@ -104,11 +104,11 @@ public final void run() { protected abstract void performExecution() throws Exception; @Override - public void addResult(CloseableIteration res) { + public void addResult(CloseableIteration res) { try { /* optimization: avoid adding empty results */ - if (res instanceof EmptyIteration) { + if (res instanceof EmptyIteration) { return; } if (isClosed() || rightQueue.isClosed()) { diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelServiceExecutor.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelServiceExecutor.java index 93d7369b0c1..50c868a0398 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelServiceExecutor.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelServiceExecutor.java @@ -23,6 +23,7 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.QueryInterruptedException; +import org.eclipse.rdf4j.query.algebra.Service; import org.eclipse.rdf4j.repository.sparql.federation.CollectionIteration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,7 +35,7 @@ * * @author Andreas Schwarte */ -public class ParallelServiceExecutor extends LookAheadIteration +public class ParallelServiceExecutor extends LookAheadIteration implements ParallelExecutor { /* @@ -51,7 +52,7 @@ public class ParallelServiceExecutor extends LookAheadIteration rightIter = null; + protected CloseableIteration rightIter = null; protected boolean finished = false; protected Exception error = null; @@ -81,7 +82,7 @@ public void run() { } @Override - public void addResult(CloseableIteration res) { + public void addResult(CloseableIteration res) { rightIter = res; latch.countDown(); @@ -159,12 +160,13 @@ protected BindingSet getNextElement() throws QueryEvaluationException { private class ParallelServiceTask extends ParallelTaskBase { @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { // Note: in order two avoid deadlocks we consume the SERVICE result. // This is basically required to avoid processing background tuple // request (i.e. HTTP slots) in the correct order. - try (var evaluate = strategy.evaluate(service.getService(), bindings)) { + Service service1 = service.getService(); + try (CloseableIteration evaluate = strategy.precompile(service1).evaluate(bindings)) { return new CollectionIteration<>(Iterations.asList(evaluate)); } } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelTask.java index 0b95dca5323..ae7509742e9 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelTask.java @@ -12,7 +12,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.federated.structures.QueryInfo; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * Interface for any parallel task that can be performed in Scheduler implementations. @@ -22,7 +21,7 @@ */ public interface ParallelTask { - CloseableIteration performTask() throws Exception; + CloseableIteration performTask() throws Exception; /** * return the controlling instance, e.g. in most cases the instance of a thread. Shared variables are used to inform diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelTaskBase.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelTaskBase.java index d49de629cb3..12208e72979 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelTaskBase.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/ParallelTaskBase.java @@ -23,7 +23,7 @@ public abstract class ParallelTaskBase implements ParallelTask { private static final Logger logger = LoggerFactory.getLogger(ParallelExecutorBase.class); protected Future scheduledFuture; - private CloseableIteration closableIter; + private CloseableIteration closableIter; private volatile boolean cancelled = false; private volatile boolean closed = false; @@ -34,7 +34,7 @@ public void cancel() { } @Override - public CloseableIteration performTask() throws Exception { + public CloseableIteration performTask() throws Exception { if (closed) { return new EmptyIteration<>(); } @@ -81,7 +81,7 @@ public CloseableIteration performTask() throws Exce return closableIter; } - protected abstract CloseableIteration performTaskInternal() throws Exception; + protected abstract CloseableIteration performTaskInternal() throws Exception; public void setScheduledFuture(Future future) { this.scheduledFuture = future; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/Scheduler.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/Scheduler.java index e00258173f6..e3515aa768c 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/Scheduler.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/concurrent/Scheduler.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.federated.evaluation.concurrent; import org.eclipse.rdf4j.common.iteration.CloseableIteration; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * Interface for any scheduler. @@ -34,7 +33,7 @@ public interface Scheduler { * * @param res */ - void handleResult(CloseableIteration res); + void handleResult(CloseableIteration res); /** * Inform the scheduler that a certain task is done. diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/BoundJoinConversionIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/BoundJoinConversionIteration.java index b65f4a79962..3158df973bd 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/BoundJoinConversionIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/BoundJoinConversionIteration.java @@ -27,11 +27,11 @@ */ @Deprecated(since = "4.1.0") public class BoundJoinConversionIteration - extends ConvertingIteration { + extends ConvertingIteration { protected final List bindings; - public BoundJoinConversionIteration(CloseableIteration iter, + public BoundJoinConversionIteration(CloseableIteration iter, List bindings) { super(iter); this.bindings = bindings; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/BoundJoinVALUESConversionIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/BoundJoinVALUESConversionIteration.java index 4daf2ef9520..fee3433a7f3 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/BoundJoinVALUESConversionIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/BoundJoinVALUESConversionIteration.java @@ -36,7 +36,7 @@ */ @Deprecated(since = "4.1.0") public class BoundJoinVALUESConversionIteration - extends ConvertingIteration { + extends ConvertingIteration { /** * The binding name for the index @@ -45,7 +45,7 @@ public class BoundJoinVALUESConversionIteration protected final List bindings; - public BoundJoinVALUESConversionIteration(CloseableIteration iter, + public BoundJoinVALUESConversionIteration(CloseableIteration iter, List bindings) { super(iter); this.bindings = bindings; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/CloseDependentConnectionIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/CloseDependentConnectionIteration.java index 2014c88d15f..c0bbff2f4c1 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/CloseDependentConnectionIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/CloseDependentConnectionIteration.java @@ -22,14 +22,14 @@ * * @author Andreas Schwarte */ -public class CloseDependentConnectionIteration extends AbstractCloseableIteration { +public class CloseDependentConnectionIteration extends AbstractCloseableIteration { private static final Logger logger = LoggerFactory.getLogger(CloseDependentConnectionIteration.class); - protected final CloseableIteration inner; + protected final CloseableIteration inner; protected final RepositoryConnection dependentConn; - public CloseDependentConnectionIteration(CloseableIteration inner, + public CloseDependentConnectionIteration(CloseableIteration inner, RepositoryConnection dependentConn) { this.inner = inner; this.dependentConn = dependentConn; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/ConsumingIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/ConsumingIteration.java index d3d92d477f4..40e857f7af5 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/ConsumingIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/ConsumingIteration.java @@ -30,11 +30,11 @@ * @author Andreas Schwarte * */ -public class ConsumingIteration implements CloseableIteration { +public class ConsumingIteration implements CloseableIteration { private final List consumed = Lists.newArrayList(); - private final CloseableIteration innerIter; + private final CloseableIteration innerIter; /** * The index of the next element that will be returned by a call to {@link #next()}. @@ -46,7 +46,7 @@ public class ConsumingIteration implements CloseableIteration iter, int max) + public ConsumingIteration(CloseableIteration iter, int max) throws QueryEvaluationException { innerIter = iter; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FederatedDescribeIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FederatedDescribeIteration.java index a316f934043..be633be9e72 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FederatedDescribeIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FederatedDescribeIteration.java @@ -16,7 +16,6 @@ import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.ConvertingIteration; import org.eclipse.rdf4j.common.iteration.EmptyIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; import org.eclipse.rdf4j.federated.algebra.StatementSource; import org.eclipse.rdf4j.federated.algebra.StatementSource.StatementSourceType; import org.eclipse.rdf4j.federated.algebra.StatementSourcePattern; @@ -39,15 +38,13 @@ * @author Andreas Schwarte * */ -@Deprecated(since = "4.1.0") public class FederatedDescribeIteration extends DescribeIteration { private final QueryInfo queryInfo; private final List allSources; - @Deprecated(since = "4.1.0", forRemoval = true) - public FederatedDescribeIteration(Iteration sourceIter, + public FederatedDescribeIteration(CloseableIteration sourceIter, FederationEvalStrategy strategy, Set describeExprNames, BindingSet parentBindings, QueryInfo queryInfo) { super(sourceIter, strategy, describeExprNames, parentBindings); @@ -61,7 +58,7 @@ public FederatedDescribeIteration(Iteration createNextIteration(Value subject, Value object) + protected CloseableIteration createNextIteration(Value subject, Value object) throws QueryEvaluationException { if (subject == null && object == null) { return new EmptyIteration<>(); @@ -71,15 +68,14 @@ protected CloseableIteration createNextIte Var predVar = new Var(VARNAME_PREDICATE); Var objVar = new Var(VARNAME_OBJECT, object); - StatementPattern pattern = new StatementPattern(subjVar, predVar, objVar); - // associate all federation members as sources for this pattern // Note: for DESCRIBE we currently do not perform any extra source selection, // i.e. we assume all members to be relevant for describing the resource - StatementSourcePattern stmtSourcePattern = new StatementSourcePattern(pattern, queryInfo); + StatementSourcePattern stmtSourcePattern = new StatementSourcePattern( + new StatementPattern(subjVar, predVar, objVar), queryInfo); allSources.forEach(stmtSourcePattern::addStatementSource); - CloseableIteration res = stmtSourcePattern.evaluate(parentBindings); + CloseableIteration res = stmtSourcePattern.evaluate(parentBindings); // we need to make sure that subject or object are added to the binding set // Note: FedX uses prepared SELECT queries to evaluate a statement pattern and diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FilteringInsertBindingsIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FilteringInsertBindingsIteration.java index 4ab41b4dc0b..0316226eeff 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FilteringInsertBindingsIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FilteringInsertBindingsIteration.java @@ -28,7 +28,7 @@ public class FilteringInsertBindingsIteration extends FilteringIteration { protected final BindingSet bindings; public FilteringInsertBindingsIteration(FilterValueExpr filterExpr, BindingSet bindings, - CloseableIteration iter, FederationEvalStrategy strategy) + CloseableIteration iter, FederationEvalStrategy strategy) throws QueryEvaluationException { super(filterExpr, iter, strategy); this.bindings = bindings; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FilteringIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FilteringIteration.java index dd7207033d3..ec8d73e7024 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FilteringIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/FilteringIteration.java @@ -26,14 +26,14 @@ * @author Andreas Schwarte */ @Deprecated(since = "4.1.0") -public class FilteringIteration extends FilterIteration { +public class FilteringIteration extends FilterIteration { private static final Logger log = LoggerFactory.getLogger(FilteringIteration.class); protected final FilterValueExpr filterExpr; protected final FederationEvalStrategy strategy; - public FilteringIteration(FilterValueExpr filterExpr, CloseableIteration iter, + public FilteringIteration(FilterValueExpr filterExpr, CloseableIteration iter, FederationEvalStrategy strategy) throws QueryEvaluationException { super(iter); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/GraphToBindingSetConversionIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/GraphToBindingSetConversionIteration.java index f7be4180b9a..c4ec86c7859 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/GraphToBindingSetConversionIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/GraphToBindingSetConversionIteration.java @@ -25,7 +25,7 @@ * @author Andreas Schwarte */ public class GraphToBindingSetConversionIteration - extends AbstractCloseableIteration { + extends AbstractCloseableIteration { protected final GraphQueryResult graph; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/GroupedCheckConversionIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/GroupedCheckConversionIteration.java index 64e91201af2..2a91afa9bc3 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/GroupedCheckConversionIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/GroupedCheckConversionIteration.java @@ -25,11 +25,11 @@ */ @Deprecated(since = "4.1.0") public class GroupedCheckConversionIteration - extends ConvertingIteration { + extends ConvertingIteration { protected final List bindings; - public GroupedCheckConversionIteration(CloseableIteration iter, + public GroupedCheckConversionIteration(CloseableIteration iter, List bindings) { super(iter); this.bindings = bindings; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration.java index f46b77d2961..d7cce0b4693 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration.java @@ -25,14 +25,14 @@ * * @author Andreas Schwarte */ -public class IndependentJoingroupBindingsIteration extends LookAheadIteration { +public class IndependentJoingroupBindingsIteration extends LookAheadIteration { protected final BindingSet bindings; - protected final CloseableIteration iter; + protected final CloseableIteration iter; protected ArrayList result = null; protected int currentIdx = 0; - public IndependentJoingroupBindingsIteration(CloseableIteration iter, + public IndependentJoingroupBindingsIteration(CloseableIteration iter, BindingSet bindings) { this.bindings = bindings; this.iter = iter; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration2.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration2.java index 4868452b6e6..f059522c5de 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration2.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration2.java @@ -28,17 +28,17 @@ * * @author Andreas Schwarte */ -public class IndependentJoingroupBindingsIteration2 extends LookAheadIteration { +public class IndependentJoingroupBindingsIteration2 extends LookAheadIteration { // a pattern matcher for the binding resolver, pattern: myVar_%outerID%#bindingId, e.g. name_0#0 protected static final Pattern pattern = Pattern.compile("(.*)_(.*)_(.*)"); protected final List bindings; - protected final CloseableIteration iter; + protected final CloseableIteration iter; protected ArrayList result = null; protected int currentIdx = 0; - public IndependentJoingroupBindingsIteration2(CloseableIteration iter, + public IndependentJoingroupBindingsIteration2(CloseableIteration iter, List bindings) { this.bindings = bindings; this.iter = iter; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration3.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration3.java index 1dc26e3d1d9..081b3a2bee6 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration3.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/IndependentJoingroupBindingsIteration3.java @@ -29,17 +29,17 @@ * * @author Andreas Schwarte */ -public class IndependentJoingroupBindingsIteration3 extends LookAheadIteration { +public class IndependentJoingroupBindingsIteration3 extends LookAheadIteration { // a pattern matcher for the binding resolver, pattern: myVar_%outerID%#bindingId, e.g. name_0#0 protected static final Pattern pattern = Pattern.compile("(.*)_(.*)_(.*)"); protected final List bindings; - protected final CloseableIteration iter; + protected final CloseableIteration iter; protected ArrayList result = null; protected int currentIdx = 0; - public IndependentJoingroupBindingsIteration3(CloseableIteration iter, + public IndependentJoingroupBindingsIteration3(CloseableIteration iter, List bindings) { this.bindings = bindings; this.iter = iter; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/InsertBindingsIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/InsertBindingsIteration.java index 017655203fb..5b566992c65 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/InsertBindingsIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/InsertBindingsIteration.java @@ -22,11 +22,11 @@ * @author Andreas Schwarte */ @Deprecated(since = "4.1.0") -public class InsertBindingsIteration extends ConvertingIteration { +public class InsertBindingsIteration extends ConvertingIteration { protected final BindingSet bindings; - public InsertBindingsIteration(CloseableIteration iter, BindingSet bindings) { + public InsertBindingsIteration(CloseableIteration iter, BindingSet bindings) { super(iter); this.bindings = bindings; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/LazyMutableClosableIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/LazyMutableClosableIteration.java index e3188884174..876159884a0 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/LazyMutableClosableIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/LazyMutableClosableIteration.java @@ -27,9 +27,9 @@ * @author Andreas Schwarte * */ -public class LazyMutableClosableIteration implements CloseableIteration { +public class LazyMutableClosableIteration implements CloseableIteration { - protected final CloseableIteration inner; + protected final CloseableIteration inner; protected List consumed = new ArrayList<>(); @@ -38,7 +38,7 @@ public class LazyMutableClosableIteration implements CloseableIteration inner) { + public LazyMutableClosableIteration(CloseableIteration inner) { super(); this.inner = inner; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/PrintingIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/PrintingIteration.java index 84327c4e66b..16927aa7e74 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/PrintingIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/PrintingIteration.java @@ -24,14 +24,14 @@ * @author Andreas Schwarte * */ -public class PrintingIteration extends AbstractCloseableIteration { +public class PrintingIteration extends AbstractCloseableIteration { - protected final CloseableIteration inner; + protected final CloseableIteration inner; protected LinkedList copyQueue = new LinkedList<>(); protected boolean done = false; public PrintingIteration( - CloseableIteration inner) { + CloseableIteration inner) { super(); this.inner = inner; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/QueryResultIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/QueryResultIteration.java index 8d58c498f4b..9648b75c89b 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/QueryResultIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/QueryResultIteration.java @@ -31,16 +31,16 @@ * @author Andreas Schwarte * */ -public class QueryResultIteration extends AbstractCloseableIteration { +public class QueryResultIteration extends AbstractCloseableIteration { // TODO apply this class and provide test case - protected final CloseableIteration inner; + protected final CloseableIteration inner; protected final QueryInfo queryInfo; protected final QueryManager qm; public QueryResultIteration( - CloseableIteration inner, QueryInfo queryInfo) { + CloseableIteration inner, QueryInfo queryInfo) { super(); this.inner = inner; this.queryInfo = queryInfo; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/RepositoryExceptionConvertingIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/RepositoryExceptionConvertingIteration.java deleted file mode 100644 index eaddbc9ef85..00000000000 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/RepositoryExceptionConvertingIteration.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.federated.evaluation.iterator; - -import org.eclipse.rdf4j.common.iteration.ExceptionConvertingIteration; -import org.eclipse.rdf4j.common.iteration.Iteration; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.repository.RepositoryResult; - -/** - * Convenience iteration to convert {@link RepositoryResult} exceptions to {@link QueryEvaluationException}. - * - * @author Andreas Schwarte - * - * @param - */ -@Deprecated(since = "4.1.0", forRemoval = true) -public class RepositoryExceptionConvertingIteration - extends ExceptionConvertingIteration { - - public RepositoryExceptionConvertingIteration( - Iteration iter) { - super(iter); - } - - @Override - protected QueryEvaluationException convert(Exception e) { - return new QueryEvaluationException(e); - } -} diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/SingleBindingSetIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/SingleBindingSetIteration.java index 11178f518dc..02ba5fd6cad 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/SingleBindingSetIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/SingleBindingSetIteration.java @@ -20,7 +20,7 @@ * @author Andreas Schwarte * */ -public class SingleBindingSetIteration extends AbstractCloseableIteration { +public class SingleBindingSetIteration extends AbstractCloseableIteration { protected final BindingSet res; protected boolean hasNext = true; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/StatementConversionIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/StatementConversionIteration.java index dc3ac11369c..ce2cb42f668 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/StatementConversionIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/StatementConversionIteration.java @@ -27,7 +27,7 @@ * * @author Andreas Schwarte */ -public class StatementConversionIteration extends AbstractCloseableIteration { +public class StatementConversionIteration extends AbstractCloseableIteration { protected final RepositoryResult repoResult; protected final BindingSet bindings; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/StopRemainingExecutionsOnCloseIteration.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/StopRemainingExecutionsOnCloseIteration.java index bb7a092f93d..264f408323d 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/StopRemainingExecutionsOnCloseIteration.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/iterator/StopRemainingExecutionsOnCloseIteration.java @@ -30,13 +30,13 @@ * @see ParallelTask#cancel() */ public class StopRemainingExecutionsOnCloseIteration - extends AbstractCloseableIteration { + extends AbstractCloseableIteration { - protected final CloseableIteration inner; + protected final CloseableIteration inner; protected final QueryInfo queryInfo; public StopRemainingExecutionsOnCloseIteration( - CloseableIteration inner, QueryInfo queryInfo) { + CloseableIteration inner, QueryInfo queryInfo) { super(); this.inner = inner; this.queryInfo = queryInfo; diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerBoundJoin.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerBoundJoin.java index 984cec7f9a1..48b475b04b2 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerBoundJoin.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerBoundJoin.java @@ -50,7 +50,7 @@ public class ControlledWorkerBoundJoin extends ControlledWorkerJoin { private static final Logger log = LoggerFactory.getLogger(ControlledWorkerBoundJoin.class); public ControlledWorkerBoundJoin(ControlledWorkerScheduler scheduler, FederationEvalStrategy strategy, - CloseableIteration leftIter, + CloseableIteration leftIter, TupleExpr rightArg, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { super(scheduler, strategy, leftIter, rightArg, bindings, queryInfo); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerJoin.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerJoin.java index e564350c11b..dab9027a0d1 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerJoin.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerJoin.java @@ -43,7 +43,7 @@ public class ControlledWorkerJoin extends JoinExecutorBase { protected final Phaser phaser = new Phaser(1); public ControlledWorkerJoin(ControlledWorkerScheduler scheduler, FederationEvalStrategy strategy, - CloseableIteration leftIter, + CloseableIteration leftIter, TupleExpr rightArg, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { super(strategy, leftIter, rightArg, bindings, queryInfo); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerLeftJoin.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerLeftJoin.java index 186c8c7dee7..a95048ab1a9 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerLeftJoin.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ControlledWorkerLeftJoin.java @@ -45,7 +45,7 @@ public class ControlledWorkerLeftJoin extends JoinExecutorBase { protected final LeftJoin join; public ControlledWorkerLeftJoin(ControlledWorkerScheduler scheduler, FederationEvalStrategy strategy, - CloseableIteration leftIter, + CloseableIteration leftIter, LeftJoin join, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { super(strategy, leftIter, join.getRightArg(), bindings, queryInfo); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/HashJoin.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/HashJoin.java index f6f3b298c27..24a47df7333 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/HashJoin.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/HashJoin.java @@ -41,7 +41,7 @@ public class HashJoin extends JoinExecutorBase { private final QueryEvaluationStep rightPrepared; public HashJoin(FederationEvalStrategy strategy, - CloseableIteration leftIter, + CloseableIteration leftIter, TupleExpr rightArg, QueryEvaluationStep rightPrepared, Set joinVars, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { @@ -128,7 +128,7 @@ protected void performJoin(Collection leftBlock, Collection join(Collection leftBlock, + static CloseableIteration join(Collection leftBlock, Collection rightBlock, Set joinVariables, Collection freeVariablesRight) { List res = new LinkedList<>(); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/JoinExecutorBase.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/JoinExecutorBase.java index 4be4fd50da5..b11cc72596c 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/JoinExecutorBase.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/JoinExecutorBase.java @@ -37,9 +37,9 @@ public abstract class JoinExecutorBase extends ParallelExecutorBase { /* Variables */ protected Set joinVars; // might be unknown (i.e. null for some implementations) - protected CloseableIteration leftIter; + protected CloseableIteration leftIter; - public JoinExecutorBase(FederationEvalStrategy strategy, CloseableIteration leftIter, + public JoinExecutorBase(FederationEvalStrategy strategy, CloseableIteration leftIter, TupleExpr rightArg, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { super(queryInfo); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelBoundJoinTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelBoundJoinTask.java index f5a9f45677a..3bde52a0027 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelBoundJoinTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelBoundJoinTask.java @@ -18,7 +18,6 @@ import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelExecutor; import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelTaskBase; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * A task implementation representing a bound join, see @@ -43,7 +42,7 @@ public ParallelBoundJoinTask(ParallelExecutor joinControl, Federatio } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { return strategy.evaluateBoundJoinStatementPattern(expr, bindings); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelCheckJoinTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelCheckJoinTask.java index 9ccb7d2efe6..b567d1c91f0 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelCheckJoinTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelCheckJoinTask.java @@ -18,7 +18,6 @@ import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelExecutor; import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelTaskBase; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * A task implementation representing a grouped bound check. See @@ -42,7 +41,7 @@ public ParallelCheckJoinTask(ParallelExecutor joinControl, Federatio } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { return strategy.evaluateGroupedCheck(expr, bindings); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelJoinTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelJoinTask.java index 56e39f47cdc..33b87e76a96 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelJoinTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelJoinTask.java @@ -15,7 +15,6 @@ import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelExecutor; import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelTaskBase; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.TupleExpr; /** @@ -39,7 +38,7 @@ public ParallelJoinTask(ParallelExecutor joinControl, FederationEval } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { return strategy.evaluate(expr, bindings); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelLeftJoinTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelLeftJoinTask.java index d18a65cf443..0d34e72187d 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelLeftJoinTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelLeftJoinTask.java @@ -49,7 +49,7 @@ public ParallelLeftJoinTask(ParallelExecutor joinControl, Federation } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { return new FedXLeftJoinIteration(strategy, join, leftBindings); @@ -60,7 +60,7 @@ public ParallelExecutor getControl() { return joinControl; } - static class FedXLeftJoinIteration extends LookAheadIteration { + static class FedXLeftJoinIteration extends LookAheadIteration { protected final FederationEvalStrategy strategy; @@ -74,7 +74,7 @@ static class FedXLeftJoinIteration extends LookAheadIteration scopeBindingNames; - private CloseableIteration rightIter; + private CloseableIteration rightIter; private final AtomicBoolean exhausted = new AtomicBoolean(false); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelServiceJoinTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelServiceJoinTask.java index f94dbc0aa81..dea485aa843 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelServiceJoinTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/ParallelServiceJoinTask.java @@ -19,7 +19,6 @@ import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelExecutor; import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelTaskBase; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.repository.sparql.federation.CollectionIteration; /** @@ -44,7 +43,7 @@ public ParallelServiceJoinTask(ParallelExecutor joinControl, Federat } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { // Note: in order two avoid deadlocks we consume the SERVICE result. // This is basically required to avoid processing background tuple diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/PhaserHandlingParallelExecutor.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/PhaserHandlingParallelExecutor.java index 275fa1860b1..3e157349d6b 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/PhaserHandlingParallelExecutor.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/PhaserHandlingParallelExecutor.java @@ -16,7 +16,6 @@ import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelExecutor; import org.eclipse.rdf4j.federated.structures.QueryInfo; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * A delegating {@link ParallelExecutor} which arrives and de-registers on the phaser on completion of a task. @@ -36,7 +35,7 @@ public PhaserHandlingParallelExecutor(ParallelExecutor delegate, Pha } @Override - public void addResult(CloseableIteration res) { + public void addResult(CloseableIteration res) { delegate.addResult(res); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/SynchronousBoundJoin.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/SynchronousBoundJoin.java index 28ccdb82ab4..90360d1d80e 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/SynchronousBoundJoin.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/SynchronousBoundJoin.java @@ -36,7 +36,7 @@ public class SynchronousBoundJoin extends SynchronousJoin { private static final Logger log = LoggerFactory.getLogger(SynchronousBoundJoin.class); public SynchronousBoundJoin(FederationEvalStrategy strategy, - CloseableIteration leftIter, + CloseableIteration leftIter, TupleExpr rightArg, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { super(strategy, leftIter, rightArg, bindings, queryInfo); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/SynchronousJoin.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/SynchronousJoin.java index 49ec4a35859..622a3c72207 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/SynchronousJoin.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/join/SynchronousJoin.java @@ -25,7 +25,7 @@ public class SynchronousJoin extends JoinExecutorBase { public SynchronousJoin(FederationEvalStrategy strategy, - CloseableIteration leftIter, + CloseableIteration leftIter, TupleExpr rightArg, BindingSet bindings, QueryInfo queryInfo) throws QueryEvaluationException { super(strategy, leftIter, rightArg, bindings, queryInfo); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelGetStatementsTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelGetStatementsTask.java index fdb7ed575db..4391178a262 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelGetStatementsTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelGetStatementsTask.java @@ -20,7 +20,6 @@ import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.StatementPattern; /** @@ -59,7 +58,7 @@ public ParallelExecutor getControl() { } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { TripleSource tripleSource = endpoint.getTripleSource(); return tripleSource.getStatements(subj, pred, obj, queryInfo, contexts); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelPreparedAlgebraUnionTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelPreparedAlgebraUnionTask.java index 7245095527e..f3749248090 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelPreparedAlgebraUnionTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelPreparedAlgebraUnionTask.java @@ -18,7 +18,6 @@ import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelTaskBase; import org.eclipse.rdf4j.federated.structures.QueryInfo; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.TupleExpr; /** @@ -47,7 +46,7 @@ public ParallelPreparedAlgebraUnionTask(ParallelExecutor unionContro } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { TripleSource tripleSource = endpoint.getTripleSource(); return tripleSource.getStatements(preparedQuery, bindings, filterExpr, queryInfo); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelPreparedUnionTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelPreparedUnionTask.java index 0ba2614eccc..f4472761fe2 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelPreparedUnionTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelPreparedUnionTask.java @@ -18,7 +18,6 @@ import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelTaskBase; import org.eclipse.rdf4j.federated.structures.QueryInfo; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; /** * A task implementation representing a prepared union, i.e. the prepared query is executed on the provided triple @@ -46,7 +45,7 @@ public ParallelPreparedUnionTask(ParallelExecutor unionControl, Stri } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { TripleSource tripleSource = endpoint.getTripleSource(); return tripleSource.getStatements(preparedQuery, bindings, filterExpr, queryInfo); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelUnionOperatorTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelUnionOperatorTask.java index 032e739ef40..c9bc20766b3 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelUnionOperatorTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelUnionOperatorTask.java @@ -14,7 +14,6 @@ import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelExecutor; import org.eclipse.rdf4j.federated.evaluation.concurrent.ParallelTaskBase; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.QueryEvaluationStep; /** @@ -42,7 +41,7 @@ public ParallelExecutor getControl() { } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { return expr.evaluate(bindings); } } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelUnionTask.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelUnionTask.java index 4fda8410779..926543f0e1f 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelUnionTask.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/evaluation/union/ParallelUnionTask.java @@ -19,7 +19,6 @@ import org.eclipse.rdf4j.federated.structures.QueryInfo; import org.eclipse.rdf4j.federated.util.QueryStringUtil; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.StatementPattern; /** @@ -47,7 +46,7 @@ public ParallelUnionTask(ParallelExecutor unionControl, StatementPat } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { TripleSource tripleSource = endpoint.getTripleSource(); return tripleSource.getStatements(stmt, bindings, filterExpr, queryInfo); } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/monitoring/MonitoringImpl.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/monitoring/MonitoringImpl.java index 92732ecd942..c53fae51671 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/monitoring/MonitoringImpl.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/monitoring/MonitoringImpl.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.federated.monitoring; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -18,7 +17,6 @@ import org.eclipse.rdf4j.federated.FedXConfig; import org.eclipse.rdf4j.federated.endpoint.Endpoint; -import org.eclipse.rdf4j.federated.exception.FedXRuntimeException; import org.eclipse.rdf4j.federated.structures.QueryInfo; import org.eclipse.rdf4j.query.algebra.TupleExpr; @@ -44,11 +42,7 @@ public class MonitoringImpl implements MonitoringService { this.config = config; if (config.isLogQueries()) { - try { - queryLog = new QueryLog(); - } catch (IOException e) { - throw new FedXRuntimeException("QueryLog cannot be initialized: " + e.getMessage()); - } + queryLog = new QueryLog(); } else { queryLog = null; } diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/monitoring/QueryLog.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/monitoring/QueryLog.java index 762cc19489a..c9fd99fb9f8 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/monitoring/QueryLog.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/monitoring/QueryLog.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.federated.monitoring; -import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.rdf4j.federated.FedXConfig; @@ -39,12 +38,12 @@ public class QueryLog { private final AtomicBoolean active = new AtomicBoolean(false); private Logger queryLog; - public QueryLog() throws IOException { + public QueryLog() { log.info("Initializing logging of queries"); initQueryLog(); } - private void initQueryLog() throws IOException { + private void initQueryLog() { queryLog = LoggerFactory.getLogger("QueryLog"); diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/optimizer/SourceSelection.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/optimizer/SourceSelection.java index 1b6a3cf1a3e..5d07a6c5433 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/optimizer/SourceSelection.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/optimizer/SourceSelection.java @@ -39,7 +39,6 @@ import org.eclipse.rdf4j.federated.structures.SubQuery; import org.eclipse.rdf4j.federated.util.QueryStringUtil; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.StatementPattern; import org.eclipse.rdf4j.query.impl.EmptyBindingSet; import org.slf4j.Logger; @@ -258,7 +257,7 @@ public void run() { } @Override - public void addResult(CloseableIteration res) { + public void addResult(CloseableIteration res) { latch.countDown(); } @@ -318,7 +317,7 @@ public ParallelCheckTask(Endpoint endpoint, StatementPattern stmt, QueryInfo que } @Override - protected CloseableIteration performTaskInternal() throws Exception { + protected CloseableIteration performTaskInternal() throws Exception { try { TripleSource t = endpoint.getTripleSource(); boolean hasResults = t.hasStatements(stmt, EmptyBindingSet.getInstance(), queryInfo, diff --git a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/util/QueryAlgebraUtil.java b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/util/QueryAlgebraUtil.java index c1729ee1b65..be0716eee0d 100644 --- a/tools/federation/src/main/java/org/eclipse/rdf4j/federated/util/QueryAlgebraUtil.java +++ b/tools/federation/src/main/java/org/eclipse/rdf4j/federated/util/QueryAlgebraUtil.java @@ -88,7 +88,6 @@ public static boolean hasFreeVars(StatementPattern stmt, BindingSet bindings) { * * @param var * @param bindings the bindings, must not be null, use {@link EmptyBindingSet} instead - * * @return the value or null */ public static Value getVarValue(Var var, BindingSet bindings) { @@ -153,7 +152,6 @@ public static Statement toStatement(StatementPattern stmt, BindingSet bindings) * @param filterExpr * @param evaluated parameter can be used outside this method to check whether FILTER has been evaluated, false in * beginning - * * @return the SELECT query * @throws IllegalQueryException */ @@ -196,7 +194,6 @@ public static TupleExpr selectQuery(StatementPattern stmt, BindingSet bindings, * @param filterExpr a filter expression or null * @param evaluated parameter can be used outside this method to check whether FILTER has been evaluated, false in * beginning - * * @return the SELECT query */ public static TupleExpr selectQuery(ExclusiveGroup group, BindingSet bindings, FilterValueExpr filterExpr, @@ -248,11 +245,11 @@ public static TupleExpr selectQuery(ExclusiveGroup group, BindingSet bindings, F /** * Construct a SELECT query expression for a bound union. - * + *

* Pattern: - * + *

* SELECT ?v_1 ?v_2 ?v_N WHERE { { ?v_1 p o } UNION { ?v_2 p o } UNION ... } - * + *

* Note that the filterExpr is not evaluated at the moment. * * @param stmt @@ -260,7 +257,6 @@ public static TupleExpr selectQuery(ExclusiveGroup group, BindingSet bindings, F * @param filterExpr * @param evaluated parameter can be used outside this method to check whether FILTER has been evaluated, false * in beginning - * * @return the SELECT query */ public static TupleExpr selectQueryBoundUnion(StatementPattern stmt, List unionBindings, @@ -294,9 +290,9 @@ public static TupleExpr selectQueryBoundUnion(StatementPattern stmt, List * Pattern: - * + *

* SELECT DISTINCT ?o_1 .. ?o_N WHERE { { s1 p1 ?o_1 FILTER ?o_1=o1 } UNION ... UNION { sN pN ?o_N FILTER ?o_N=oN }} * * @param stmt @@ -381,7 +377,6 @@ private static TupleExpr constructJoinArg(ExclusiveTupleExpr exclusiveExpr, Set< * @param stmt * @param varNames * @param bindings - * * @return the {@link StatementPattern} */ protected static StatementPattern constructStatement(StatementPattern stmt, Set varNames, @@ -402,7 +397,6 @@ protected static StatementPattern constructStatement(StatementPattern stmt, Set< * @param stmt * @param varNames * @param bindings - * * @return the {@link StatementPattern} */ protected static StatementPattern constructStatementId(StatementPattern stmt, String varID, Set varNames, @@ -458,20 +452,17 @@ protected static TupleExpr constructStatementCheckId(StatementPattern stmt, int * @param var * @param varNames * @param bindings - * * @return the variable - * */ protected static Var appendVar(Var var, Set varNames, BindingSet bindings) { - Var res = var.clone(); if (!var.hasValue()) { if (bindings.hasBinding(var.getName())) { - res.setValue(bindings.getValue(var.getName())); + return new Var(var.getName(), bindings.getValue(var.getName()), var.isAnonymous(), var.isConstant()); } else { varNames.add(var.getName()); } } - return res; + return var.clone(); } /** @@ -481,28 +472,25 @@ protected static Var appendVar(Var var, Set varNames, BindingSet binding * @param varID * @param varNames * @param bindings - * * @return the variable */ protected static Var appendVarId(Var var, String varID, Set varNames, BindingSet bindings) { - Var res = var.clone(); if (!var.hasValue()) { if (bindings.hasBinding(var.getName())) { - res.setValue(bindings.getValue(var.getName())); + return new Var(var.getName(), bindings.getValue(var.getName()), var.isAnonymous(), var.isConstant()); } else { - String newName = var.getName() + "_" + varID; - varNames.add(newName); - res.setName(newName); + Var res = new Var(var.getName() + "_" + varID); + varNames.add(res.getName()); + return res; } } - return res; + return var.clone(); } /** * A helper class to insert bindings in the {@link Var} nodes of the given {@link TupleExpr}. * * @author Andreas Schwarte - * */ private static class InsertBindingsVisitor extends AbstractQueryModelVisitor { @@ -519,12 +507,12 @@ private InsertBindingsVisitor(BindingSet bindings) { public void meet(Var node) throws QueryEvaluationException { if (node.hasValue()) { if (bindings.hasBinding(node.getName())) { - node.setValue(bindings.getValue(node.getName())); + node.replaceWith(new Var(node.getName(), bindings.getValue(node.getName()), node.isAnonymous(), + node.isConstant())); } } else { freeVars.add(node.getName()); } - super.meet(node); } } diff --git a/tools/federation/src/test/java/demos/Demo.java b/tools/federation/src/test/java/demos/Demo.java index 5f553e0d3f2..3260b6b9c34 100644 --- a/tools/federation/src/test/java/demos/Demo.java +++ b/tools/federation/src/test/java/demos/Demo.java @@ -21,7 +21,7 @@ public class Demo { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { File dataConfig = new File("local/dataSourceConfig.ttl"); FedXRepository repo = FedXFactory.createFederation(dataConfig); diff --git a/tools/federation/src/test/java/demos/Demo2.java b/tools/federation/src/test/java/demos/Demo2.java index b244f949a0f..09d00ae8529 100644 --- a/tools/federation/src/test/java/demos/Demo2.java +++ b/tools/federation/src/test/java/demos/Demo2.java @@ -21,7 +21,7 @@ public class Demo2 { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { if (System.getProperty("log4j.configuration") == null) { System.setProperty("log4j.configuration", "file:local/log4j.properties"); diff --git a/tools/federation/src/test/java/demos/Demo3.java b/tools/federation/src/test/java/demos/Demo3.java index b12e133ab80..db22c98d4f7 100644 --- a/tools/federation/src/test/java/demos/Demo3.java +++ b/tools/federation/src/test/java/demos/Demo3.java @@ -22,7 +22,7 @@ public class Demo3 { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { List endpoints = new ArrayList<>(); endpoints.add(EndpointFactory.loadSPARQLEndpoint("http://dbpedia", "http://dbpedia.org/sparql")); diff --git a/tools/federation/src/test/java/demos/Demo4.java b/tools/federation/src/test/java/demos/Demo4.java index 6c6038693a9..2e6de0f784c 100644 --- a/tools/federation/src/test/java/demos/Demo4.java +++ b/tools/federation/src/test/java/demos/Demo4.java @@ -19,7 +19,7 @@ public class Demo4 { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { FedXRepository repo = FedXFactory.createSparqlFederation(Arrays.asList( "http://dbpedia.org/sparql", diff --git a/tools/federation/src/test/java/demos/Demo5.java b/tools/federation/src/test/java/demos/Demo5.java index bfef8ccf2dc..6336b42ce43 100644 --- a/tools/federation/src/test/java/demos/Demo5.java +++ b/tools/federation/src/test/java/demos/Demo5.java @@ -19,7 +19,7 @@ public class Demo5 { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { FedXRepository repo = FedXFactory.createSparqlFederation(Arrays.asList( "http://dbpedia.org/sparql", diff --git a/tools/federation/src/test/java/demos/FedXWithRemoteRepositoryManager.java b/tools/federation/src/test/java/demos/FedXWithRemoteRepositoryManager.java index bdd9d9c5f60..af6bdb8e4ef 100644 --- a/tools/federation/src/test/java/demos/FedXWithRemoteRepositoryManager.java +++ b/tools/federation/src/test/java/demos/FedXWithRemoteRepositoryManager.java @@ -29,7 +29,7 @@ */ public class FedXWithRemoteRepositoryManager { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { // connection URL of a RDF4J server which manages the repositories String serverUrl = "http://localhost:8080/rdf4j-server"; diff --git a/tools/federation/src/test/java/demos/MonitorRequestsDemo.java b/tools/federation/src/test/java/demos/MonitorRequestsDemo.java index 7e8bcde7b77..bfe17c669dd 100644 --- a/tools/federation/src/test/java/demos/MonitorRequestsDemo.java +++ b/tools/federation/src/test/java/demos/MonitorRequestsDemo.java @@ -21,7 +21,7 @@ public class MonitorRequestsDemo { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { FedXConfig config = new FedXConfig().withEnableMonitoring(true).withLogQueries(true); FedXRepository repo = FedXFactory.newFederation() diff --git a/tools/federation/src/test/java/demos/QueryPlanLogDemo.java b/tools/federation/src/test/java/demos/QueryPlanLogDemo.java index 9be14d6c574..625a5afaed1 100644 --- a/tools/federation/src/test/java/demos/QueryPlanLogDemo.java +++ b/tools/federation/src/test/java/demos/QueryPlanLogDemo.java @@ -21,7 +21,7 @@ public class QueryPlanLogDemo { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { FedXConfig config = new FedXConfig().withEnableMonitoring(true).withLogQueryPlan(true); Repository repo = FedXFactory.newFederation() diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/BindTests.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/BindTests.java index 57dc18d1c6c..8be0156683c 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/BindTests.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/BindTests.java @@ -30,7 +30,7 @@ public void prepareData() throws Exception { } @Test - public void testSimple() throws Exception { + public void testSimple() { List res = runQuery( "SELECT * WHERE { BIND(20 AS ?age) . ?person foaf:age ?age }"); @@ -38,7 +38,7 @@ public void testSimple() throws Exception { } @Test - public void testConcat() throws Exception { + public void testConcat() { List res = runQuery( "SELECT * WHERE { foaf:age ?age . BIND(CONCAT('age: ', str(?age)) AS ?outAge) }"); @@ -47,7 +47,7 @@ public void testConcat() throws Exception { } @Test - public void testRebind() throws Exception { + public void testRebind() { List res = runQuery( "SELECT * WHERE { foaf:age ?age . BIND(str(?age) AS ?outAge) }"); @@ -56,7 +56,7 @@ public void testRebind() throws Exception { } @Test - public void testMultiBind() throws Exception { + public void testMultiBind() { List res = runQuery( "SELECT * WHERE { BIND(20 AS ?age) . foaf:age ?age . BIND(str(?age) AS ?outAge) }"); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXBaseTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXBaseTest.java index 531647dcac4..3a4d1ac3764 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXBaseTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXBaseTest.java @@ -96,7 +96,9 @@ protected void execute(String queryFile, String expectedResultFile, boolean chec // Some query results will automatically close themselves when they are exhausted. To properly test that // query results are closed correctly we need to evaluate the query without retrieving any elements. if (doubleCheckClose) { - ((TupleQuery) query).evaluate().close(); + try (TupleQueryResult evaluate = ((TupleQuery) query).evaluate()) { + // do nothing + } } try (TupleQueryResult queryResult = ((TupleQuery) query).evaluate()) { diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXRule.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXRule.java index fce0bb318ae..1cfc97fac61 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXRule.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXRule.java @@ -38,7 +38,7 @@ public FedXRule withConfiguration(Consumer configurator) { } @Override - public void beforeEach(ExtensionContext ctx) throws Exception { + public void beforeEach(ExtensionContext ctx) { FedXConfig fedxConfig = new FedXConfig(); for (Consumer configConsumer : configurations) { configConsumer.accept(fedxConfig); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXWithInferenceTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXWithInferenceTest.java index 5e3d5b8b9ee..e7dfc16d3b1 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXWithInferenceTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXWithInferenceTest.java @@ -51,19 +51,19 @@ public class FedXWithInferenceTest extends FedXBaseTest { private LocalRepositoryManager repoManager; @BeforeEach - public void before() throws Exception { + public void before() { File baseDir = new File(tempDir.toFile(), "data"); repoManager = new LocalRepositoryManager(baseDir); repoManager.init(); } @AfterEach - public void after() throws Exception { + public void after() { repoManager.shutDown(); } @Test - public void testFederationWithRDFSInference() throws Exception { + public void testFederationWithRDFSInference() { addMemoryStoreWithRDFS("repo1"); addMemoryStore("repo2"); @@ -143,14 +143,14 @@ public void testFederationWithRDFSInference() throws Exception { } - protected void addMemoryStore(String repoId) throws Exception { + protected void addMemoryStore(String repoId) { RepositoryImplConfig implConfig = new SailRepositoryConfig(new MemoryStoreConfig()); RepositoryConfig config = new RepositoryConfig(repoId, implConfig); repoManager.addRepositoryConfig(config); } - protected void addMemoryStoreWithRDFS(String repoId) throws Exception { + protected void addMemoryStoreWithRDFS(String repoId) { RepositoryImplConfig implConfig = new SailRepositoryConfig( new SchemaCachingRDFSInferencerConfig(new MemoryStoreConfig())); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXWithLocalRepositoryManagerTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXWithLocalRepositoryManagerTest.java index e7725098d51..fbaad635c84 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXWithLocalRepositoryManagerTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/FedXWithLocalRepositoryManagerTest.java @@ -58,19 +58,19 @@ public class FedXWithLocalRepositoryManagerTest extends FedXBaseTest { private TestLocalRepositoryManager repoManager; @BeforeEach - public void before() throws Exception { + public void before() { File baseDir = new File(tempDir.toFile(), "data"); repoManager = new TestLocalRepositoryManager(baseDir); repoManager.init(); } @AfterEach - public void after() throws Exception { + public void after() { repoManager.shutDown(); } @Test - public void testWithLocalRepositoryManager() throws Exception { + public void testWithLocalRepositoryManager() { addMemoryStore("repo1"); addMemoryStore("repo2"); @@ -102,7 +102,7 @@ public void testWithLocalRepositoryManager() throws Exception { } @Test - public void testWithLocalRepositoryManager_FactoryInitialization() throws Exception { + public void testWithLocalRepositoryManager_FactoryInitialization() { addMemoryStore("repo1"); addMemoryStore("repo2"); @@ -129,7 +129,7 @@ public void testWithLocalRepositoryManager_FactoryInitialization() throws Except } @Test - public void testWithLocalRepositoryManager_CustomFederatedServiceResolver() throws Exception { + public void testWithLocalRepositoryManager_CustomFederatedServiceResolver() { addMemoryStore("repo1"); addMemoryStore("repo2"); @@ -191,7 +191,7 @@ protected FederatedService createService(String serviceUrl) throws QueryEvaluati } @Test - public void testMultipleFederationInstances() throws Exception { + public void testMultipleFederationInstances() { addMemoryStore("repo1"); addMemoryStore("repo2"); @@ -236,7 +236,7 @@ public void testMultipleFederationInstances() throws Exception { } } - protected void addMemoryStore(String repoId) throws Exception { + protected void addMemoryStore(String repoId) { RepositoryImplConfig implConfig = new SailRepositoryConfig(new MemoryStoreConfig()); RepositoryConfig config = new RepositoryConfig(repoId, implConfig); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/LargeJoinTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/LargeJoinTest.java index 8bd5b42ca80..2b2229086bc 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/LargeJoinTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/LargeJoinTest.java @@ -46,14 +46,14 @@ public class LargeJoinTest extends FedXBaseTest { private TestLocalRepositoryManager repoManager; @BeforeEach - public void before() throws Exception { + public void before() { File baseDir = new File(tempDir.toFile(), "data"); repoManager = new TestLocalRepositoryManager(baseDir); repoManager.init(); } @AfterEach - public void after() throws Exception { + public void after() { repoManager.shutDown(); } @@ -64,7 +64,7 @@ protected FederationContext federationContext() { @Test @Disabled - public void testWithLocalRepositoryManager() throws Exception { + public void testWithLocalRepositoryManager() { addNativeStore("repo1"); addNativeStore("repo2"); @@ -122,7 +122,7 @@ public void testWithLocalRepositoryManager() throws Exception { } - protected void addNativeStore(String repoId) throws Exception { + protected void addNativeStore(String repoId) { RepositoryImplConfig implConfig = new SailRepositoryConfig(new NativeStoreConfig()); RepositoryConfig config = new RepositoryConfig(repoId, implConfig); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/MediumConcurrencyTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/MediumConcurrencyTestIT.java similarity index 88% rename from tools/federation/src/test/java/org/eclipse/rdf4j/federated/MediumConcurrencyTest.java rename to tools/federation/src/test/java/org/eclipse/rdf4j/federated/MediumConcurrencyTestIT.java index e0f4aa4141a..736d2fb13e5 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/MediumConcurrencyTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/MediumConcurrencyTestIT.java @@ -15,6 +15,7 @@ import java.util.Arrays; import java.util.List; import java.util.Random; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -24,9 +25,13 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; -public class MediumConcurrencyTest extends SPARQLBaseTest { +/** + * This test is particularly flaky, and it is very hard to debug the root cause. + */ +public class MediumConcurrencyTestIT extends SPARQLBaseTest { static final String[] queries = new String[] { "query01", "query02", "query03", "query04", "query05", "query06", "query07", "query08", "query09", @@ -35,6 +40,8 @@ public class MediumConcurrencyTest extends SPARQLBaseTest { private static ExecutorService executor; + private final CountDownLatch countDownLatch = new CountDownLatch(1); + @BeforeAll public static void beforeClass() { executor = Executors.newFixedThreadPool(10); @@ -48,6 +55,7 @@ public static void afterClass() throws InterruptedException { } } + // @RepeatedTest(1000) @Test @Disabled("Test is very flaky, but it's too difficult to figure out what's wrong.") public void queryMix() throws Throwable { @@ -65,6 +73,8 @@ public void queryMix() throws Throwable { futures.add(f); } + countDownLatch.countDown(); + try { final String message = Assertions.assertTimeoutPreemptively(Duration.ofSeconds(30), () -> { for (Future f : futures) { @@ -83,6 +93,7 @@ public void queryMix() throws Throwable { protected Future submit(final String query, final int queryId) { return executor.submit(() -> { + countDownLatch.await(); log.info("Executing query " + queryId + ": " + query); execute("/tests/medium/" + query + ".rq", "/tests/medium/" + query + ".srx", false, true); // uncomment to simulate canceling case diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/SPARQLBaseTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/SPARQLBaseTest.java index 9d92bd8a5b8..f33d37d3048 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/SPARQLBaseTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/SPARQLBaseTest.java @@ -44,7 +44,7 @@ protected void initFedXConfig() { } - protected Set getStatements(Resource subj, IRI pred, Value obj) throws Exception { + protected Set getStatements(Resource subj, IRI pred, Value obj) { Set res = new HashSet<>(); try (RepositoryConnection conn = fedxRule.getRepository() diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/SPARQLServerBaseTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/SPARQLServerBaseTest.java index a9a96e36a38..df40772402c 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/SPARQLServerBaseTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/SPARQLServerBaseTest.java @@ -96,7 +96,7 @@ public static void afterTest() throws Exception { } @BeforeEach - public void beforeEachTest() throws Exception { + public void beforeEachTest() { // reset operations counter and fail after for (int i = 1; i <= MAX_ENDPOINTS; i++) { RepositorySettings repoSettings = repoSettings(i); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/ServiceTests.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/ServiceTests.java index cb05d9614e0..fb36566925c 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/ServiceTests.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/ServiceTests.java @@ -424,15 +424,15 @@ public TestSparqlFederatedService(String serviceUrl, HttpClientSessionManager cl } @Override - public CloseableIteration select(Service service, + public CloseableIteration select(Service service, Set projectionVars, BindingSet bindings, String baseUri) throws QueryEvaluationException { serviceRequestCount.incrementAndGet(); return super.select(service, projectionVars, bindings, baseUri); } @Override - public CloseableIteration evaluate(Service service, - CloseableIteration bindings, String baseUri) + public CloseableIteration evaluate(Service service, + CloseableIteration bindings, String baseUri) throws QueryEvaluationException { boundJoinRequestCount.incrementAndGet(); return super.evaluate(service, bindings, baseUri); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/cache/SourceSelectionMemoryCacheTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/cache/SourceSelectionMemoryCacheTest.java index 9c08fd90d18..77cb703bda8 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/cache/SourceSelectionMemoryCacheTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/cache/SourceSelectionMemoryCacheTest.java @@ -34,7 +34,7 @@ protected void initFedXConfig() { } @Test - public void test_neverCacheUnbound() throws Exception { + public void test_neverCacheUnbound() { // just execute for one kind of test environment assumeSparqlEndpoint(); @@ -53,7 +53,7 @@ public void test_neverCacheUnbound() throws Exception { } @Test - public void test_inferGeneralized() throws Exception { + public void test_inferGeneralized() { // just execute for one kind of test environment assumeSparqlEndpoint(); @@ -75,7 +75,7 @@ public void test_inferGeneralized() throws Exception { } @Test - public void test_inferGeneralized2() throws Exception { + public void test_inferGeneralized2() { // just execute for one kind of test environment assumeSparqlEndpoint(); @@ -99,7 +99,7 @@ public void test_inferGeneralized2() throws Exception { } @Test - public void test_inferGeneralized3() throws Exception { + public void test_inferGeneralized3() { // just execute for one kind of test environment assumeSparqlEndpoint(); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/endpoint/EndpointFactoryTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/endpoint/EndpointFactoryTest.java index 01898173692..0fcb4fb36e9 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/endpoint/EndpointFactoryTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/endpoint/EndpointFactoryTest.java @@ -42,7 +42,7 @@ public void testValidSparqlEndpoint() throws Exception { @Test @Disabled // needs to be fixed, connection timeout needs to be set - public void testNotReachableEndpoint() throws Exception { + public void testNotReachableEndpoint() { try { EndpointFactory.loadSPARQLEndpoint("http://invalid.org/not_sparql"); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/evaluation/join/HashJoinTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/evaluation/join/HashJoinTest.java index 5dc18a2c295..8e296073c11 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/evaluation/join/HashJoinTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/evaluation/join/HashJoinTest.java @@ -22,7 +22,6 @@ import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.query.Binding; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.impl.MapBindingSet; import org.eclipse.rdf4j.query.impl.SimpleBinding; import org.junit.jupiter.api.Assertions; @@ -34,7 +33,7 @@ public class HashJoinTest { @Test - public void testSimple() throws Exception { + public void testSimple() { List leftBlock = new ArrayList<>(); leftBlock.add(bindingSet(binding("x", irid("p1")))); @@ -46,7 +45,7 @@ public void testSimple() throws Exception { rightBlock.add(bindingSet(binding("x", irid("p1")))); rightBlock.add(bindingSet(binding("x", irid("p4")))); - CloseableIteration joinResultIter = HashJoin.join(leftBlock, rightBlock, + CloseableIteration joinResultIter = HashJoin.join(leftBlock, rightBlock, Sets.newHashSet("x"), Collections.emptyList()); List joinResult = Iterations.asList(joinResultIter); @@ -58,7 +57,7 @@ public void testSimple() throws Exception { } @Test - public void testMultipleBindings() throws Exception { + public void testMultipleBindings() { List leftBlock = new ArrayList<>(); leftBlock.add(bindingSet(binding("x", irid("p1")), binding("y", l("P1")))); @@ -67,7 +66,7 @@ public void testMultipleBindings() throws Exception { List rightBlock = new ArrayList<>(); rightBlock.add(bindingSet(binding("x", irid("p2")), binding("z", l("something")))); - CloseableIteration joinResultIter = HashJoin.join(leftBlock, rightBlock, + CloseableIteration joinResultIter = HashJoin.join(leftBlock, rightBlock, Sets.newHashSet("x"), Collections.emptyList()); List joinResult = Iterations.asList(joinResultIter); @@ -79,7 +78,7 @@ public void testMultipleBindings() throws Exception { } @Test - public void testLeftJoin_NoResultForBinding() throws Exception { + public void testLeftJoin_NoResultForBinding() { List leftBlock = new ArrayList<>(); leftBlock.add(bindingSet(binding("x", irid("p1")), binding("y", l("P1")))); @@ -88,7 +87,7 @@ public void testLeftJoin_NoResultForBinding() throws Exception { List rightBlock = new ArrayList<>(); rightBlock.add(bindingSet(binding("x", irid("p1")), binding("z", l("something")))); - CloseableIteration joinResultIter = HashJoin.join(leftBlock, rightBlock, + CloseableIteration joinResultIter = HashJoin.join(leftBlock, rightBlock, Sets.newHashSet("x"), Collections.emptyList()); List joinResult = Iterations.asList(joinResultIter); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/optimizer/FilterOptimizerTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/optimizer/FilterOptimizerTest.java index b238d947528..8379fbc4049 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/optimizer/FilterOptimizerTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/optimizer/FilterOptimizerTest.java @@ -14,7 +14,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; -import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -287,7 +286,7 @@ public static Stream data() { } @BeforeEach - public void setup(@TempDir File baseDir) throws IOException { + public void setup(@TempDir File baseDir) { RepositoryManager manager = new LocalRepositoryManager(baseDir); federatedRepository = createFedXRepo(manager); addRepoConfig(manager, "standard"); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/RemoteRepositoryTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/RemoteRepositoryTest.java index 5e98a780aab..1782e30d54a 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/RemoteRepositoryTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/RemoteRepositoryTest.java @@ -86,7 +86,7 @@ public static void main(String[] args) throws Exception { System.out.println("Done."); } - private static List retrieveInstances(RepositoryConnection conn, IRI type) throws Exception { + private static List retrieveInstances(RepositoryConnection conn, IRI type) { try (RepositoryResult qres = conn.getStatements(null, RDF.TYPE, type, false)) { return qres .stream() @@ -97,7 +97,7 @@ private static List retrieveInstances(RepositoryConnection conn, IRI type) } } - private static long runQuery(RepositoryConnection conn, IRI instance) throws Exception { + private static long runQuery(RepositoryConnection conn, IRI instance) { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * WHERE { <" + instance.stringValue() + "> ?p ?o }"); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/RepositoryPerformance.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/RepositoryPerformance.java index 4f025a71a11..67d7ac1af82 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/RepositoryPerformance.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/RepositoryPerformance.java @@ -122,7 +122,7 @@ public void run() throws Exception { System.out.println("Done. Overall duration: " + (System.currentTimeMillis() - testStart) + "ms"); } - private List retrieveInstances(RepositoryConnection conn) throws Exception { + private List retrieveInstances(RepositoryConnection conn) { try (RepositoryResult qres = conn.getStatements(null, RDF.TYPE, type, false)) { return qres.stream() .limit(MAX_INSTANCES) @@ -132,7 +132,7 @@ private List retrieveInstances(RepositoryConnection conn) throws Exception } } - private int runQuery(RepositoryConnection conn, IRI instance) throws Exception { + private int runQuery(RepositoryConnection conn, IRI instance) { long start = System.currentTimeMillis(); TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, @@ -150,9 +150,9 @@ private int runQuery(RepositoryConnection conn, IRI instance) throws Exception { } } - abstract RepositoryConnection getConnection() throws Exception; + abstract RepositoryConnection getConnection(); - abstract void shutdown() throws Exception; + abstract void shutdown(); } static class SparqlRepositoryPerformanceTest extends PerformanceBase { @@ -167,14 +167,14 @@ public SparqlRepositoryPerformanceTest(IRI type, String sparqlEndpoint) { Repository repo = null; @Override - RepositoryConnection getConnection() throws Exception { + RepositoryConnection getConnection() { repo = new SPARQLRepository(sparqlEndpoint); repo.init(); return repo.getConnection(); } @Override - void shutdown() throws Exception { + void shutdown() { repo.shutDown(); } @@ -194,14 +194,14 @@ public RemoteRepositoryPerformanceTest(IRI type, String repositoryServer, String Repository repo = null; @Override - RepositoryConnection getConnection() throws Exception { + RepositoryConnection getConnection() { repo = new HTTPRepository(repositoryServer, repositoryName); repo.init(); return repo.getConnection(); } @Override - void shutdown() throws Exception { + void shutdown() { repo.shutDown(); } diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/SPARQLRepositoryPerformance.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/SPARQLRepositoryPerformance.java index cf054b0448e..8b09b8ad5b8 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/SPARQLRepositoryPerformance.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/performance/SPARQLRepositoryPerformance.java @@ -21,7 +21,7 @@ public class SPARQLRepositoryPerformance { /** * @param args */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) { SPARQLRepository repo = new SPARQLRepository("http://10.212.10.29:8081/openrdf-sesame/repositories/drugbank"); repo.init(); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/CustomAppConfiguration.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/CustomAppConfiguration.java index cdcfad1eb8f..126decc818a 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/CustomAppConfiguration.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/CustomAppConfiguration.java @@ -50,22 +50,22 @@ public LogReader getDefaultLogReader() { } @Override - public void init() throws IOException { + public void init() { } @Override - public void load() throws IOException { + public void load() { } @Override - public void save() throws IOException { + public void save() { } @Override - public void destroy() throws IOException { + public void destroy() { } diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/NativeStoreServer.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/NativeStoreServer.java index ebfe0be94f0..48f3a176e74 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/NativeStoreServer.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/NativeStoreServer.java @@ -38,7 +38,7 @@ public NativeStoreServer(File dataDir) { } @Override - public void initialize(int nRepositories) throws Exception { + public void initialize(int nRepositories) { for (int i = 1; i <= nRepositories; i++) { NativeStore store = NativeStoreProvideTest.createNativeStore(new File(dataDir, "endpoint" + i)); @@ -51,7 +51,7 @@ public void initialize(int nRepositories) throws Exception { } @Override - public void shutdown() throws Exception { + public void shutdown() { } diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/SPARQLEmbeddedServer.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/SPARQLEmbeddedServer.java index 88631a7b918..60d4b95bb4e 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/SPARQLEmbeddedServer.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/server/SPARQLEmbeddedServer.java @@ -147,7 +147,7 @@ public void shutdown() throws Exception { } @Override - public Endpoint loadEndpoint(int i) throws Exception { + public Endpoint loadEndpoint(int i) { return useRemoteRepositoryEndpoint ? EndpointFactory.loadRemoteRepository(getServerUrl(), "endpoint" + i) : EndpointFactory.loadSPARQLEndpoint("http://endpoint" + i, getRepositoryUrl("endpoint" + i)); } diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/write/RepositoryWriteStrategyTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/write/RepositoryWriteStrategyTest.java index 644bcfd9717..e6a2dc7f2e5 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/write/RepositoryWriteStrategyTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/write/RepositoryWriteStrategyTest.java @@ -40,13 +40,13 @@ public void setUp() { } @Test - public void testBegin() throws Exception { + public void testBegin() { strategy.begin(); verify(connection).begin(); } @Test - public void testSetTransactionSettings() throws Exception { + public void testSetTransactionSettings() { TransactionSetting setting = mock(TransactionSetting.class); strategy.setTransactionSettings(setting); diff --git a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/write/WriteTest.java b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/write/WriteTest.java index 3bd09a93f83..605bb511e5e 100644 --- a/tools/federation/src/test/java/org/eclipse/rdf4j/federated/write/WriteTest.java +++ b/tools/federation/src/test/java/org/eclipse/rdf4j/federated/write/WriteTest.java @@ -199,7 +199,7 @@ protected Statement simpleStatement() { } @BeforeEach - public void clearWriteOperations() throws Exception { + public void clearWriteOperations() { writeOperations.set(0); } diff --git a/tools/runtime-osgi/pom.xml b/tools/runtime-osgi/pom.xml index 523f0974147..8c5e906fae2 100644 --- a/tools/runtime-osgi/pom.xml +++ b/tools/runtime-osgi/pom.xml @@ -89,6 +89,13 @@ + + com.github.siom79.japicmp + japicmp-maven-plugin + + true + + diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/protocol/ProtocolController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/protocol/ProtocolController.java index 3fde4205a13..f31f98ebc8e 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/protocol/ProtocolController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/protocol/ProtocolController.java @@ -30,7 +30,7 @@ public class ProtocolController extends AbstractController { public ProtocolController() throws ApplicationContextException { - setSupportedMethods(new String[] { METHOD_GET, METHOD_HEAD }); + setSupportedMethods(METHOD_GET, METHOD_HEAD); } @Override diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/RepositoryConfigRepository.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/RepositoryConfigRepository.java index 4aca44b1f87..87b0bc1e18d 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/RepositoryConfigRepository.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/RepositoryConfigRepository.java @@ -113,7 +113,7 @@ public RepositoryResult getContextIDs() throws RepositoryException { manager.getRepositoryIDs().forEach(id -> { contextIDs.add(getContext(id)); }); - CloseableIteration iter; + CloseableIteration iter; iter = new CloseableIteratorIteration<>(contextIDs.iterator()); return new RepositoryResult<>(iter); } @@ -121,7 +121,7 @@ public RepositoryResult getContextIDs() throws RepositoryException { @Override public RepositoryResult getStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws RepositoryException { - CloseableIteration iter = new CloseableIteratorIteration<>( + CloseableIteration iter = new CloseableIteratorIteration<>( committed.getStatements(subj, pred, obj, contexts).iterator()); return new RepositoryResult<>(iter); } @@ -205,7 +205,7 @@ public void rollback() throws RepositoryException { @Override public RepositoryResult getNamespaces() throws RepositoryException { - CloseableIteration iter; + CloseableIteration iter; iter = new CloseableIteratorIteration<>(committed.getNamespaces().iterator()); return new RepositoryResult<>(iter); } diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/RepositoryListController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/RepositoryListController.java index c906a42376d..261a0ed938b 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/RepositoryListController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/RepositoryListController.java @@ -43,7 +43,7 @@ public class RepositoryListController extends AbstractController { private RepositoryManager repositoryManager; public RepositoryListController() throws ApplicationContextException { - setSupportedMethods(new String[] { METHOD_GET, METHOD_HEAD }); + setSupportedMethods(METHOD_GET, METHOD_HEAD); } public void setRepositoryManager(RepositoryManager repMan) { diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/config/ConfigController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/config/ConfigController.java index 039fa61d338..3d1bff847d4 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/config/ConfigController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/config/ConfigController.java @@ -52,7 +52,7 @@ public class ConfigController extends AbstractController { private final ModelFactory modelFactory = new LinkedHashModelFactory(); public ConfigController() throws ApplicationContextException { - setSupportedMethods(new String[] { METHOD_GET, METHOD_POST, METHOD_HEAD }); + setSupportedMethods(METHOD_GET, METHOD_POST, METHOD_HEAD); } public void setRepositoryManager(RepositoryManager repositoryManager) { diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/contexts/ContextsController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/contexts/ContextsController.java index a58cc82519e..f2d2625e6c3 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/contexts/ContextsController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/contexts/ContextsController.java @@ -59,7 +59,7 @@ protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpSer List contexts = new ArrayList<>(); RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request); try { - try (CloseableIteration contextIter = repositoryCon + try (CloseableIteration contextIter = repositoryCon .getContextIDs()) { while (contextIter.hasNext()) { BindingSet bindingSet = new ListBindingSet(columnNames, contextIter.next()); diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/graph/GraphController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/graph/GraphController.java index cce6d39a3c0..40c7893e57e 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/graph/GraphController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/graph/GraphController.java @@ -59,7 +59,7 @@ public class GraphController extends AbstractController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public GraphController() throws ApplicationContextException { - setSupportedMethods(new String[] { METHOD_GET, METHOD_HEAD, METHOD_POST, "PUT", "DELETE" }); + setSupportedMethods(METHOD_GET, METHOD_HEAD, METHOD_POST, "PUT", "DELETE"); } @Override diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/namespaces/NamespacesController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/namespaces/NamespacesController.java index a0d6b9aa37a..7b772e956a8 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/namespaces/NamespacesController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/namespaces/NamespacesController.java @@ -53,7 +53,7 @@ public class NamespacesController extends AbstractController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public NamespacesController() throws ApplicationContextException { - setSupportedMethods(new String[] { METHOD_GET, METHOD_HEAD, "DELETE" }); + setSupportedMethods(METHOD_GET, METHOD_HEAD, "DELETE"); } @Override @@ -87,7 +87,7 @@ private ModelAndView getExportNamespacesResult(HttpServletRequest request, HttpS try (RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request)) { final ValueFactory vf = repositoryCon.getValueFactory(); try { - try (CloseableIteration iter = repositoryCon + try (CloseableIteration iter = repositoryCon .getNamespaces()) { while (iter.hasNext()) { Namespace ns = iter.next(); diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/size/SizeController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/size/SizeController.java index 7b81f300135..e357c141a9c 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/size/SizeController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/size/SizeController.java @@ -38,7 +38,7 @@ public class SizeController extends AbstractController { public SizeController() throws ApplicationContextException { - setSupportedMethods(new String[] { METHOD_GET, METHOD_HEAD }); + setSupportedMethods(METHOD_GET, METHOD_HEAD); } @Override diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/statements/StatementsController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/statements/StatementsController.java index 73129ad2abb..85ac839c2cd 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/statements/StatementsController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/statements/StatementsController.java @@ -88,7 +88,7 @@ public class StatementsController extends AbstractController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); public StatementsController() throws ApplicationContextException { - setSupportedMethods(new String[] { METHOD_GET, METHOD_POST, METHOD_HEAD, "PUT", "DELETE" }); + setSupportedMethods(METHOD_GET, METHOD_POST, METHOD_HEAD, "PUT", "DELETE"); } @Override diff --git a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/transaction/TransactionController.java b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/transaction/TransactionController.java index fbe58ca6071..ff647a6a6b5 100644 --- a/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/transaction/TransactionController.java +++ b/tools/server-spring/src/main/java/org/eclipse/rdf4j/http/server/repository/transaction/TransactionController.java @@ -104,7 +104,7 @@ public class TransactionController extends AbstractController implements Disposa private final Logger logger = LoggerFactory.getLogger(this.getClass()); public TransactionController() throws ApplicationContextException { - setSupportedMethods(new String[] { METHOD_POST, "PUT", "DELETE" }); + setSupportedMethods(METHOD_POST, "PUT", "DELETE"); } @Override diff --git a/tools/server-spring/src/test/java/org/eclipse/rdf4j/common/webapp/util/HttpServerUtilTest.java b/tools/server-spring/src/test/java/org/eclipse/rdf4j/common/webapp/util/HttpServerUtilTest.java index 88455258e85..a96872625fe 100644 --- a/tools/server-spring/src/test/java/org/eclipse/rdf4j/common/webapp/util/HttpServerUtilTest.java +++ b/tools/server-spring/src/test/java/org/eclipse/rdf4j/common/webapp/util/HttpServerUtilTest.java @@ -13,8 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.BufferedReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; @@ -52,10 +50,9 @@ public class HttpServerUtilTest { private ArrayList tupleQueryMimeTypes; /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { FileFormatServiceRegistry registry = TupleQueryResultWriterRegistry.getInstance(); tupleQueryMimeTypes = new ArrayList<>(16); @@ -168,7 +165,7 @@ public String getCharacterEncoding() { } @Override - public void setCharacterEncoding(String env) throws UnsupportedEncodingException { + public void setCharacterEncoding(String env) { // TODO Auto-generated method stub } @@ -186,7 +183,7 @@ public String getContentType() { } @Override - public ServletInputStream getInputStream() throws IOException { + public ServletInputStream getInputStream() { // TODO Auto-generated method stub return null; } @@ -240,7 +237,7 @@ public int getServerPort() { } @Override - public BufferedReader getReader() throws IOException { + public BufferedReader getReader() { // TODO Auto-generated method stub return null; } @@ -556,7 +553,7 @@ public DispatcherType getDispatcherType() { * @see javax.servlet.http.HttpServletRequest#authenticate(javax.servlet.http.HttpServletResponse) */ @Override - public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { + public boolean authenticate(HttpServletResponse response) throws ServletException { // TODO Auto-generated method stub return false; } @@ -589,7 +586,7 @@ public void logout() throws ServletException { * @see javax.servlet.http.HttpServletRequest#getParts() */ @Override - public Collection getParts() throws IOException, ServletException { + public Collection getParts() throws ServletException { // TODO Auto-generated method stub return null; } @@ -600,7 +597,7 @@ public Collection getParts() throws IOException, ServletException { * @see javax.servlet.http.HttpServletRequest#getPart(java.lang.String) */ @Override - public Part getPart(String name) throws IOException, ServletException { + public Part getPart(String name) throws ServletException { // TODO Auto-generated method stub return null; } diff --git a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/RepositoryControllerTest.java b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/RepositoryControllerTest.java index d28707ab949..38d89d72ec3 100644 --- a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/RepositoryControllerTest.java +++ b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/RepositoryControllerTest.java @@ -43,7 +43,7 @@ public class RepositoryControllerTest { private RepositoryManager manager; @BeforeEach - public void setUp() throws Exception { + public void setUp() { request = new MockHttpServletRequest(); request.setAttribute("repositoryID", repositoryId); response = new MockHttpServletResponse(); diff --git a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/config/ConfigControllerTest.java b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/config/ConfigControllerTest.java index e6578115dee..61d1d47c9d2 100644 --- a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/config/ConfigControllerTest.java +++ b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/config/ConfigControllerTest.java @@ -43,7 +43,7 @@ public class ConfigControllerTest { private RepositoryManager manager; @BeforeEach - public void setUp() throws Exception { + public void setUp() { request = new MockHttpServletRequest(); request.setAttribute("repositoryID", repositoryId); response = new MockHttpServletResponse(); diff --git a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/config/ConfigViewTest.java b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/config/ConfigViewTest.java index b3950515dcf..545551982f1 100644 --- a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/config/ConfigViewTest.java +++ b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/config/ConfigViewTest.java @@ -31,7 +31,7 @@ public class ConfigViewTest { @BeforeEach - public void setUp() throws Exception { + public void setUp() { } @Test diff --git a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/namespaces/NamespaceControllerTest.java b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/namespaces/NamespaceControllerTest.java index efa6973f8e7..bcdfd3dd41f 100644 --- a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/namespaces/NamespaceControllerTest.java +++ b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/namespaces/NamespaceControllerTest.java @@ -36,7 +36,7 @@ class NamespaceControllerTest { private MockHttpServletResponse response; @BeforeEach - public void setUp() throws Exception { + public void setUp() { request = new MockHttpServletRequest(); request.setAttribute("repositoryID", REPO_ID); request.setAttribute("repository", new SailRepository(new MemoryStore())); diff --git a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TestActiveTransactionRegistry.java b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TestActiveTransactionRegistry.java index 182cfd6b58e..7df63bdc705 100644 --- a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TestActiveTransactionRegistry.java +++ b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TestActiveTransactionRegistry.java @@ -32,10 +32,9 @@ public class TestActiveTransactionRegistry { private UUID txnId2; /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { System.setProperty(ActiveTransactionRegistry.CACHE_TIMEOUT_PROPERTY, "1"); registry = ActiveTransactionRegistry.INSTANCE; repository = Mockito.mock(Repository.class); diff --git a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TestTransactionControllerErrorHandling.java b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TestTransactionControllerErrorHandling.java index da647c290d1..2d40145c702 100644 --- a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TestTransactionControllerErrorHandling.java +++ b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TestTransactionControllerErrorHandling.java @@ -11,6 +11,8 @@ package org.eclipse.rdf4j.http.server.repository.transaction; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -84,16 +86,19 @@ public void shouldThrowMalformedQueryExceptionForQuerySyntaxErrors() throws Exce response = new MockHttpServletResponse(); - try { - transactionController.handleRequestInternal(request, response); - Assertions.fail("Exception must be thrown."); - } catch (ClientHTTPException e) { - Assertions.assertNotNull(e); - Assertions.assertEquals("MALFORMED QUERY: org.eclipse.rdf4j.query.parser.sparql.ast.VisitorException: " + - "QName 'ex:data' uses an undefined prefix", e.getMessage()); - } finally { - txn.close(); - ActiveTransactionRegistry.INSTANCE.deregister(txn); - } + assertThrows(ClientHTTPException.class, () -> { + try { + transactionController.handleRequestInternal(request, response); + } catch (ClientHTTPException e) { + Assertions + .assertEquals("MALFORMED QUERY: org.eclipse.rdf4j.query.parser.sparql.ast.VisitorException: " + + "QName 'ex:data' uses an undefined prefix", e.getMessage()); + throw e; + } finally { + txn.close(); + ActiveTransactionRegistry.INSTANCE.deregister(txn); + } + }); + } } diff --git a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TransactionStartControllerTest.java b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TransactionStartControllerTest.java index 6dc27330070..afd2004940c 100644 --- a/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TransactionStartControllerTest.java +++ b/tools/server-spring/src/test/java/org/eclipse/rdf4j/http/server/repository/transaction/TransactionStartControllerTest.java @@ -44,7 +44,7 @@ class TransactionStartControllerTest { private MockHttpServletResponse response; @BeforeEach - public void setUp() throws Exception { + public void setUp() { request = new MockHttpServletRequest(); request.setRequestURI("/repositories/" + REPO_ID + "/transactions"); request.setAttribute("repositoryID", REPO_ID); diff --git a/tools/server/pom.xml b/tools/server/pom.xml index ae610487e56..9d21d2969d2 100644 --- a/tools/server/pom.xml +++ b/tools/server/pom.xml @@ -123,6 +123,13 @@ + + com.github.siom79.japicmp + japicmp-maven-plugin + + true + + diff --git a/tools/workbench/pom.xml b/tools/workbench/pom.xml index 58c4e083595..4276baac5b7 100644 --- a/tools/workbench/pom.xml +++ b/tools/workbench/pom.xml @@ -81,6 +81,13 @@ + + com.github.siom79.japicmp + japicmp-maven-plugin + + true + + diff --git a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/CreateServlet.java b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/CreateServlet.java index 2d72a7b59d9..c011e6407bc 100644 --- a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/CreateServlet.java +++ b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/CreateServlet.java @@ -30,6 +30,7 @@ import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.util.Models; +import org.eclipse.rdf4j.model.vocabulary.CONFIG; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.query.QueryResultHandlerException; import org.eclipse.rdf4j.repository.RepositoryException; @@ -112,10 +113,12 @@ RepositoryConfig updateRepositoryConfig(final String configString) throws IOExce final Model graph = new LinkedHashModel(); final RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE, SimpleValueFactory.getInstance()); rdfParser.setRDFHandler(new StatementCollector(graph)); - rdfParser.parse(new StringReader(configString), RepositoryConfigSchema.NAMESPACE); + rdfParser.parse(new StringReader(configString), CONFIG.NAMESPACE); - Resource res = Models.subject(graph.getStatements(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY)) - .orElseThrow(() -> new RepositoryException("could not find instance of Repository class in config")); + Resource res = Models.subject(graph.getStatements(null, RDF.TYPE, CONFIG.Rep.Repository)) + .orElseGet(() -> Models.subject(graph.getStatements(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY)) + .orElseThrow(() -> new RepositoryException( + "could not find instance of Repository class in config"))); final RepositoryConfig repConfig = RepositoryConfig.create(graph, res); repConfig.validate(); manager.addRepositoryConfig(repConfig); diff --git a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/QueryServlet.java b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/QueryServlet.java index ed7afbcd499..bd2d9c62bd2 100644 --- a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/QueryServlet.java +++ b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/QueryServlet.java @@ -30,8 +30,8 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Namespace; +import org.eclipse.rdf4j.model.base.CoreDatatype; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; -import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.query.MalformedQueryException; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.QueryResultHandlerException; @@ -123,7 +123,7 @@ public void init(final ServletConfig config) throws ServletException { super.init(config); try { this.storage = QueryStorage.getSingletonInstance(this.appConfig); - } catch (RepositoryException | IOException e) { + } catch (RepositoryException e) { throw new ServletException(e); } } @@ -225,7 +225,7 @@ protected void doPost(final WorkbenchRequest req, final HttpServletResponse resp final String query = getQueryText(req); final Boolean infer = Boolean.valueOf(req.getParameter(EDIT_PARAMS[2])); final Literal limit = SimpleValueFactory.getInstance() - .createLiteral(req.getParameter(EDIT_PARAMS[3]), XSD.INTEGER); + .createLiteral(req.getParameter(EDIT_PARAMS[3]), CoreDatatype.XSD.INTEGER); builder.result(queryLn, query, infer, limit); builder.end(); } else { diff --git a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/SavedQueriesServlet.java b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/SavedQueriesServlet.java index d3a6ab40c1d..6ca91311cd1 100644 --- a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/SavedQueriesServlet.java +++ b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/commands/SavedQueriesServlet.java @@ -47,7 +47,7 @@ public void init(final ServletConfig config) throws ServletException { super.init(config); try { this.storage = QueryStorage.getSingletonInstance(this.appConfig); - } catch (RepositoryException | IOException e) { + } catch (RepositoryException e) { throw new ServletException(e); } } diff --git a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/proxy/ServerValidator.java b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/proxy/ServerValidator.java index d717c516630..b69dcaa936a 100644 --- a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/proxy/ServerValidator.java +++ b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/proxy/ServerValidator.java @@ -14,7 +14,6 @@ import java.io.File; import java.io.IOException; import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; @@ -115,7 +114,7 @@ private boolean canConnect(final String server) { return success; } - private File asLocalFile(final URL rdf) throws UnsupportedEncodingException { + private File asLocalFile(final URL rdf) { return new File(URLDecoder.decode(rdf.getFile(), StandardCharsets.UTF_8)); } } diff --git a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/proxy/WorkbenchServlet.java b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/proxy/WorkbenchServlet.java index 0e36797c2a6..4f899de502c 100644 --- a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/proxy/WorkbenchServlet.java +++ b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/proxy/WorkbenchServlet.java @@ -13,7 +13,6 @@ import java.io.File; import java.io.IOException; import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; @@ -197,7 +196,7 @@ private RepositoryManager createRepositoryManager(final String param) throws IOE return manager; } - private File asLocalFile(final URL rdf) throws UnsupportedEncodingException { + private File asLocalFile(final URL rdf) { return new File(URLDecoder.decode(rdf.getFile(), StandardCharsets.UTF_8)); } diff --git a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/CookieHandler.java b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/CookieHandler.java index c18a5957f8e..8d1280824f1 100644 --- a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/CookieHandler.java +++ b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/CookieHandler.java @@ -12,7 +12,6 @@ import static java.lang.Integer.parseInt; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -44,8 +43,7 @@ public CookieHandler(final ServletConfig config, final TransformationServlet ser this.servlet = servlet; } - public void updateCookies(final WorkbenchRequest req, final HttpServletResponse resp) - throws UnsupportedEncodingException { + public void updateCookies(final WorkbenchRequest req, final HttpServletResponse resp) { for (String name : this.servlet.getCookieNames()) { if (req.isParameterPresent(name)) { addCookie(req, resp, name); @@ -53,8 +51,7 @@ public void updateCookies(final WorkbenchRequest req, final HttpServletResponse } } - private void addCookie(final WorkbenchRequest req, final HttpServletResponse resp, final String name) - throws UnsupportedEncodingException { + private void addCookie(final WorkbenchRequest req, final HttpServletResponse resp, final String name) { final String raw = req.getParameter(name); final String value = URLEncoder.encode(raw, StandardCharsets.UTF_8); LOGGER.info("name: {}\nvalue: {}", name, value); diff --git a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/QueryStorage.java b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/QueryStorage.java index 4433b6ee304..1aa9408dd32 100644 --- a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/QueryStorage.java +++ b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/QueryStorage.java @@ -11,7 +11,6 @@ package org.eclipse.rdf4j.workbench.util; import java.io.File; -import java.io.IOException; import java.util.UUID; import org.eclipse.rdf4j.common.app.AppConfiguration; @@ -48,7 +47,7 @@ public class QueryStorage { private static QueryStorage instance; public static QueryStorage getSingletonInstance(final AppConfiguration config) - throws RepositoryException, IOException { + throws RepositoryException { synchronized (LOCK) { if (instance == null || instance.isShutdown()) { instance = new QueryStorage(config); @@ -119,9 +118,8 @@ private boolean isShutdown() { * * @param appConfig the application configuration, for obtaining the data directory * @throws RepositoryException if there is an issue creating the object to access the repository - * @throws IOException */ - private QueryStorage(final AppConfiguration appConfig) throws RepositoryException, IOException { + private QueryStorage(final AppConfiguration appConfig) throws RepositoryException { queries = new SailRepository(new NativeStore(new File(appConfig.getDataDir(), "queries"))); queries.init(); } diff --git a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/WorkbenchRequest.java b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/WorkbenchRequest.java index 060370aac05..254d05b0ca8 100644 --- a/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/WorkbenchRequest.java +++ b/tools/workbench/src/main/java/org/eclipse/rdf4j/workbench/util/WorkbenchRequest.java @@ -16,7 +16,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -298,7 +297,7 @@ private Map getMultipartParameterMap() return parameters; } - private Map getUrlParameterMap(String url) throws UnsupportedEncodingException { + private Map getUrlParameterMap(String url) { String qry = url.substring(url.indexOf(';') + 1); Map parameters = new HashMap<>(); for (String param : qry.split("&")) { diff --git a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/CreateServletTest.java b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/CreateServletTest.java new file mode 100644 index 00000000000..7753a02966b --- /dev/null +++ b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/CreateServletTest.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Distribution License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: BSD-3-Clause + *******************************************************************************/ +package org.eclipse.rdf4j.workbench.commands; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +import org.eclipse.rdf4j.common.exception.RDF4JException; +import org.eclipse.rdf4j.repository.config.RepositoryConfig; +import org.eclipse.rdf4j.repository.manager.LocalRepositoryManager; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * @author Dale Visser + */ +public class CreateServletTest { + + @TempDir + static File datadir; + + static CreateServlet servlet; + + @BeforeAll + public static void setUpServlet() { + servlet = new CreateServlet(); + servlet.setRepositoryManager(new LocalRepositoryManager(datadir)); + } + + private static final String[] EXPECTED_TEMPLATES = new String[] { "memory-customrule", "memory-rdfs-dt", + "memory-rdfs", "memory", + "native-customrule", "native-rdfs-dt", "native-rdfs", "native", "remote", "sparql", "memory-shacl", + "native-shacl" }; + + /** + * Regression test for SES-1907. + */ + @Test + public final void testExpectedTemplatesCanBeResolved() { + for (String template : EXPECTED_TEMPLATES) { + String resource = template + ".ttl"; + assertThat(RepositoryConfig.class.getResourceAsStream(resource)).isNotNull().as(resource); + } + } + + @Test + public final void testExpectedTemplatesCanBeLoaded() throws IOException { + for (String template : EXPECTED_TEMPLATES) { + assertThat(CreateServlet.getConfigTemplate(template).getTemplate()).isNotNull(); + } + } + + @Test + public void testUpdateRepositoryConfig_legacyConfig() { + var servlet = new CreateServlet(); + servlet.setRepositoryManager(new LocalRepositoryManager(datadir)); + + var in = getClass().getResourceAsStream("/configFiles/memory-legacy.ttl"); + + try { + String legacyConfigString = new String(in.readAllBytes(), StandardCharsets.UTF_8); + RepositoryConfig config = servlet.updateRepositoryConfig(legacyConfigString); + + assertThat(config.getID()).isEqualTo("legacy"); + assertThat(config.getTitle()).isEqualTo("Legacy Test Repository"); + } catch (RDF4JException | IOException e) { + fail(e.getMessage()); + } + } + + @Test + public void testUpdateRepositoryConfig_newConfig() { + var servlet = new CreateServlet(); + servlet.setRepositoryManager(new LocalRepositoryManager(datadir)); + + var in = getClass().getResourceAsStream("/configFiles/memory.ttl"); + + try { + String legacyConfigString = new String(in.readAllBytes(), StandardCharsets.UTF_8); + RepositoryConfig config = servlet.updateRepositoryConfig(legacyConfigString); + + assertThat(config.getID()).isEqualTo("test"); + assertThat(config.getTitle()).isEqualTo("test store"); + } catch (RDF4JException | IOException e) { + fail(e.getMessage()); + } + } + + @Test + public void testUpdateRepositoryConfig_useLegacy_legacyConfig() { + var in = getClass().getResourceAsStream("/configFiles/memory-legacy.ttl"); + + try { + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", "true"); + String legacyConfigString = new String(in.readAllBytes(), StandardCharsets.UTF_8); + RepositoryConfig config = servlet.updateRepositoryConfig(legacyConfigString); + System.setProperty("org.eclipse.rdf4j.model.vocabulary.useLegacyConfig", ""); + + assertThat(config.getID()).isEqualTo("legacy"); + assertThat(config.getTitle()).isEqualTo("Legacy Test Repository"); + } catch (RDF4JException | IOException e) { + fail(e.getMessage()); + } + } +} diff --git a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestExploreServlet.java b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/ExploreServletTest.java similarity index 99% rename from tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestExploreServlet.java rename to tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/ExploreServletTest.java index f1bcbc6d257..fe356977bcd 100644 --- a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestExploreServlet.java +++ b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/ExploreServletTest.java @@ -35,7 +35,7 @@ /** * @author Dale Visser */ -public class TestExploreServlet { +public class ExploreServletTest { private RepositoryConnection connection; diff --git a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestInfoServlet.java b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/InfoServletTest.java similarity index 95% rename from tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestInfoServlet.java rename to tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/InfoServletTest.java index a39f4b1e0b7..f25a4b12681 100644 --- a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestInfoServlet.java +++ b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/InfoServletTest.java @@ -27,7 +27,7 @@ /** * @author dale */ -public class TestInfoServlet { +public class InfoServletTest { private final InfoServlet servlet = new InfoServlet(); @@ -36,10 +36,9 @@ public class TestInfoServlet { private final RepositoryInfo info = new RepositoryInfo(); /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { servlet.setRepositoryInfo(info); manager = mock(RepositoryManager.class); servlet.setRepositoryManager(manager); diff --git a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestQueryServlet.java b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/QueryServletTest.java similarity index 95% rename from tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestQueryServlet.java rename to tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/QueryServletTest.java index fba0116a31e..af716f02834 100644 --- a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestQueryServlet.java +++ b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/QueryServletTest.java @@ -33,7 +33,7 @@ /** * @author Dale Visser */ -public class TestQueryServlet { +public class QueryServletTest { private static final String SHORT_QUERY = "select * {?s ?p ?o .}"; @@ -47,17 +47,17 @@ public void setUp() throws IOException { } @Test - public final void testLongQuery() throws ServletException, IOException { + public final void testLongQuery() throws ServletException { assertThat(servlet.shouldWriteQueryCookie(longQuery)).isFalse(); } @Test - public final void testShortQuery() throws ServletException, IOException { + public final void testShortQuery() throws ServletException { assertThat(servlet.shouldWriteQueryCookie(SHORT_QUERY)).isTrue(); } @Test - public final void testNoQuery() throws ServletException, IOException { + public final void testNoQuery() throws ServletException { assertThat(servlet.shouldWriteQueryCookie(null)).isTrue(); } diff --git a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestRemoveServlet.java b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/RemoveServletTest.java similarity index 98% rename from tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestRemoveServlet.java rename to tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/RemoveServletTest.java index d2d02938990..423ebd6608a 100644 --- a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestRemoveServlet.java +++ b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/RemoveServletTest.java @@ -35,7 +35,7 @@ * * @author Dale Visser */ -public class TestRemoveServlet { +public class RemoveServletTest { private final RemoveServlet servlet = new RemoveServlet(); diff --git a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestCreateServlet.java b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestCreateServlet.java deleted file mode 100644 index e97c5a99dea..00000000000 --- a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/commands/TestCreateServlet.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.workbench.commands; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; - -import org.eclipse.rdf4j.repository.config.RepositoryConfig; -import org.junit.jupiter.api.Test; - -/** - * @author Dale Visser - */ -public class TestCreateServlet { - - private static final String[] EXPECTED_TEMPLATES = new String[] { "memory-customrule", "memory-rdfs-dt", - "memory-rdfs", "memory", - "native-customrule", "native-rdfs-dt", "native-rdfs", "native", "remote", "sparql", "memory-shacl", - "native-shacl" }; - - /** - * Regression test for SES-1907. - */ - @Test - public final void testExpectedTemplatesCanBeResolved() { - for (String template : EXPECTED_TEMPLATES) { - System.out.println(template); - String resource = template + ".ttl"; - assertThat(RepositoryConfig.class.getResourceAsStream(resource)).isNotNull().as(resource); - } - } - - @Test - public final void testExpectedTemplatesCanBeLoaded() throws IOException { - for (String template : EXPECTED_TEMPLATES) { - System.out.println(template); - CreateServlet.getConfigTemplate(template); - } - } - -} diff --git a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/util/TestTupleResultBuilder.java b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/util/TestTupleResultBuilder.java index 391dc86bc7f..8e14dfa38ef 100644 --- a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/util/TestTupleResultBuilder.java +++ b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/util/TestTupleResultBuilder.java @@ -48,7 +48,7 @@ public final void testSES1726regression() throws Exception { } @Test - public final void testSES1846Normal() throws Exception { + public final void testSES1846Normal() { TupleResultBuilder builder = new TupleResultBuilder(new SPARQLBooleanXMLWriter(new ByteArrayOutputStream()), SimpleValueFactory.getInstance()); builder.startBoolean(); @@ -57,7 +57,7 @@ public final void testSES1846Normal() throws Exception { } @Test - public final void testSES1846regression() throws Exception { + public final void testSES1846regression() { TupleResultBuilder builder = new TupleResultBuilder(new SPARQLBooleanXMLWriter(new ByteArrayOutputStream()), SimpleValueFactory.getInstance()); try { diff --git a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/util/TestValueDecoder.java b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/util/TestValueDecoder.java index 8077f177ee0..2a188572e2f 100644 --- a/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/util/TestValueDecoder.java +++ b/tools/workbench/src/test/java/org/eclipse/rdf4j/workbench/util/TestValueDecoder.java @@ -38,10 +38,9 @@ public class TestValueDecoder { private ValueFactory factory; /** - * @throws java.lang.Exception */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { factory = SimpleValueFactory.getInstance(); // Build a mock repository instance that provides 'decoder' with all @@ -70,7 +69,7 @@ public final void testPlainStringLiteral() throws BadRequestException { } @Test - public final void testUnexpectedLiteralAttribute() throws BadRequestException { + public final void testUnexpectedLiteralAttribute() { try { decoder.decodeValue("\"datatype oops\"^rdfs:label"); fail("Expected BadRequestException."); diff --git a/tools/workbench/src/test/resources/configFiles/memory-legacy.ttl b/tools/workbench/src/test/resources/configFiles/memory-legacy.ttl new file mode 100644 index 00000000000..a4d10cfb50a --- /dev/null +++ b/tools/workbench/src/test/resources/configFiles/memory-legacy.ttl @@ -0,0 +1,23 @@ +# +# 'Test' main-memory repository config - legacy configuration +# +@prefix rdfs: . +@prefix rep: . +@prefix sr: . +@prefix sail: . +@prefix ms: . +@prefix sb: . + +[] a rep:Repository ; + rep:repositoryID "legacy" ; + rdfs:label "Legacy Test Repository" ; + rep:repositoryImpl [ + rep:repositoryType "openrdf:SailRepository" ; + sr:sailImpl [ + sail:sailType "openrdf:MemoryStore" ; + sail:iterationCacheSyncThreshold "1000"; + ms:persist false ; + ms:syncDelay 0 ; + sb:evaluationStrategyFactory "org.eclipse.rdf4j.query.algebra.evaluation.impl.StrictEvaluationStrategyFactory" + ] + ]. diff --git a/tools/workbench/src/test/resources/configFiles/memory.ttl b/tools/workbench/src/test/resources/configFiles/memory.ttl new file mode 100644 index 00000000000..fd19cbf5fdf --- /dev/null +++ b/tools/workbench/src/test/resources/configFiles/memory.ttl @@ -0,0 +1,19 @@ +# +# RDF4J configuration for a main-memory repository +# +@prefix rdfs: . +@prefix config: . + +[] a config:Repository ; + config:rep.id "test" ; + rdfs:label "test store" ; + config:rep.impl [ + config:rep.type "openrdf:SailRepository" ; + config:sail.impl [ + config:sail.type "openrdf:MemoryStore" ; + config:sail.iterationCacheSyncThreshold "10000"; + config:mem.persist true ; + config:mem.syncDelay 0 ; + config:sail.defaultQueryEvaluationMode "STANDARD" + ] + ].