You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@clerezza.apache.org by en...@apache.org on 2014/03/29 19:05:24 UTC
[1/5] CLEREZZA-813 Moved the two virtuoso modules to the clerezza
root folder. Added to the main pom.xml
Repository: clerezza
Updated Branches:
refs/heads/master b8776a544 -> bb87e83fe
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
new file mode 100644
index 0000000..0ac3a27
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
@@ -0,0 +1,310 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage.access;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.sql.SQLException;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.apache.clerezza.rdf.core.Graph;
+import org.apache.clerezza.rdf.core.MGraph;
+import org.apache.clerezza.rdf.core.NonLiteral;
+import org.apache.clerezza.rdf.core.PlainLiteral;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.access.NoSuchEntityException;
+import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
+import org.apache.clerezza.rdf.core.impl.SimpleMGraph;
+import org.apache.clerezza.rdf.core.impl.TripleImpl;
+import org.apache.clerezza.rdf.virtuoso.storage.TestUtils;
+import org.apache.clerezza.rdf.virtuoso.storage.access.VirtuosoWeightedProvider;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import virtuoso.jdbc4.VirtuosoException;
+
+/**
+ *
+ * Tests the VirtuosoWeightedProvider
+ *
+ * @author enridaga
+ *
+ */
+public class VirtuosoWeightedProviderTest {
+ static final Logger log = LoggerFactory
+ .getLogger(VirtuosoWeightedProviderTest.class);
+
+ private static final String TEST_GRAPH_URI = "VirtuosoWeightedProviderTest";
+
+ private static VirtuosoWeightedProvider wp = null;
+
+ @BeforeClass
+ public static void before() throws ClassNotFoundException, SQLException {
+ org.junit.Assume.assumeTrue(!TestUtils.SKIP);
+
+ log.info("Preparing VirtuosoWeightedProvider for test");
+ wp = TestUtils.getProvider();
+ }
+
+ @Test
+ public void weight() {
+ log.info("Test setting the weight");
+ int w = 200;
+ wp.setWeight(w);
+ assertTrue(wp.getWeight() == w);
+ }
+
+ @Test
+ public void listGraphs() {
+ log.info("Test listGraphs()");
+ Set<UriRef> gs = wp.listGraphs();
+ Iterator<UriRef> it = gs.iterator();
+ log.debug("Graphs:");
+ while (it.hasNext()) {
+ UriRef r = it.next();
+ // Must not be null
+ assertNotNull(r);
+ // Must not be empty string
+ assertFalse(r.getUnicodeString().equals(""));
+ log.debug(" > {}", r.getUnicodeString());
+ }
+ }
+
+ @Test
+ public void listGraphsIsUnmodifiable() {
+ log.info("Test listGraphsIsUnmodifiable()");
+ Set<UriRef> gs = wp.listGraphs();
+ boolean exception = false;
+ try {
+ gs.add(new UriRef("example"));
+ } catch (UnsupportedOperationException e) {
+ log.debug(
+ "Great, we had an {} exception while modifying an immutable set!",
+ e.getClass());
+ exception = true;
+ }
+ assertTrue(exception);
+ }
+
+ @Test
+ public void listMGraphs() {
+ log.info("Test listMGraphs()");
+ Set<UriRef> mg = wp.listMGraphs();
+ log.debug("Graphs:");
+ for (UriRef r : mg) {
+ // Must not be null
+ assertNotNull(r);
+ // Must not be empty string
+ assertFalse(r.getUnicodeString().equals(""));
+ log.debug("MGraph iri: {}", r.getUnicodeString());
+ }
+ }
+
+ final UriRef enridaga = new UriRef("enridaga");
+ final UriRef alexdma = new UriRef("alexdma");
+ final UriRef anuzzolese = new UriRef("anuzzolese");
+ final UriRef predicate = new UriRef("http://property/name");
+ final PlainLiteral object = new PlainLiteralImpl("Enrico Daga");
+ final UriRef knows = new UriRef(TestUtils.FOAF_NS + "knows");
+
+ @Test
+ public void createMGraph() {
+ log.info("createMGraph()");
+ try {
+ MGraph mgraph = wp.createMGraph(new UriRef(TEST_GRAPH_URI));
+ assertNotNull(mgraph);
+ if (log.isDebugEnabled()) {
+ log.debug("Created mgraph, adding a triple");
+ log.debug("MGraph size is {}", mgraph.size());
+ }
+ mgraph.add(new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return knows;
+ }
+
+ @Override
+ public Resource getObject() {
+ return anuzzolese;
+ }
+ });
+ log.debug("MGraph size is {}", mgraph.size());
+ assertTrue(mgraph.size() == 1);
+ } catch (RuntimeException re) {
+ log.error("ERROR! ", re);
+ assertFalse(true);
+ }
+ }
+
+ @Test
+ public void createGraph() throws VirtuosoException, ClassNotFoundException,
+ SQLException {
+ MGraph smg = new SimpleMGraph();
+ Triple t = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return knows;
+ }
+
+ @Override
+ public Resource getObject() {
+ return anuzzolese;
+ }
+ };
+ smg.add(t);
+ UriRef name = new UriRef(TEST_GRAPH_URI);
+ Graph g = wp.createGraph(name, smg);
+ // Graph must contain the triple
+ assertTrue(g.contains(t));
+ // Graph size must be 1
+ assertTrue(g.size() == 1);
+ // Graph retrieved by id must contain the triple
+ assertTrue(wp.getGraph(name).contains(t));
+ // Graph retrieved by id must be equal to g
+ assertTrue(wp.getGraph(name).equals(g));
+ }
+
+ @Test
+ public void testEquals() {
+ log.info("testEquals()");
+ UriRef name = new UriRef(TEST_GRAPH_URI);
+ MGraph g = wp.createMGraph(name);
+ // Equals
+ log.debug("Should be equal: {}", g.equals(wp.getMGraph(name)));
+ assertTrue(g.equals(wp.getMGraph(name)));
+ log.debug("{} <-> {}", g.getClass(), g.getGraph().getClass());
+ log.debug("Should not be equal: {}", g.equals(g.getGraph()));
+ // Not equals
+ assertFalse(g.equals(g.getGraph()));
+ }
+
+ @Before
+ @After
+ public void clear() throws VirtuosoException, ClassNotFoundException,
+ SQLException {
+ log.info("clear()");
+ log.debug("Removing test graphs <{}>", TEST_GRAPH_URI);
+ try {
+ wp.deleteTripleCollection(new UriRef(TEST_GRAPH_URI));
+ } catch (NoSuchEntityException nsee) {
+ // Nothing to do
+ }
+ try {
+ wp.deleteTripleCollection(new UriRef("urn:my-empty-graph"));
+ } catch (NoSuchEntityException nsee) {
+ // Nothing to do
+ }
+ try {
+ wp.deleteTripleCollection(new UriRef("urn:my-non-empty-graph"));
+ } catch (NoSuchEntityException nsee) {
+ // Nothing to do
+ }
+ }
+
+ @Test
+ public void testCreateEmptyMGraph(){
+ log.info("testCreateEmptyMGraph()");
+// try {
+ UriRef ur = new UriRef("urn:my-empty-graph");
+ Assert.assertFalse(wp.listGraphs().contains(ur));
+ Assert.assertFalse(wp.listMGraphs().contains(ur));
+ wp.createMGraph(ur);
+ Assert.assertTrue(wp.canRead(ur));
+ Assert.assertTrue(wp.canModify(ur));
+ Assert.assertTrue(wp.listGraphs().contains(ur));
+ Assert.assertTrue(wp.listMGraphs().contains(ur));
+ wp.deleteTripleCollection(ur);
+ Assert.assertFalse(wp.listGraphs().contains(ur));
+ Assert.assertFalse(wp.listMGraphs().contains(ur));
+// } catch (NoSuchEntityException nsee) {
+// // Nothing to do
+// }
+ }
+
+ @Test
+ public void testEmptyAndNonEmptyGraphs(){
+ log.info("testEmptyAndNonEmptyGraphs()");
+
+ UriRef ur = new UriRef("urn:my-empty-graph");
+ UriRef nur = new UriRef("urn:my-non-empty-graph");
+
+ Assert.assertFalse(wp.listGraphs().contains(ur));
+ Assert.assertFalse(wp.listMGraphs().contains(ur));
+ wp.createMGraph(ur);
+ Assert.assertTrue(wp.canRead(ur));
+ Assert.assertTrue(wp.canModify(ur));
+ wp.createMGraph(nur);
+ Assert.assertTrue(wp.canRead(nur));
+ Assert.assertTrue(wp.canModify(nur));
+ Assert.assertTrue(wp.listGraphs().contains(nur));
+ Assert.assertTrue(wp.listMGraphs().contains(nur));
+
+ // Add a triple to the non-empty graph
+ Triple t = new TripleImpl(new UriRef("urn:test:subject"), new UriRef("urn:test:predicate"),
+ new PlainLiteralImpl("A literal"));
+ wp.getMGraph(nur).add(t);
+ // Show inserted triple
+ Iterator<Triple> ti = wp.getMGraph(nur).iterator();
+ while(ti.hasNext()){
+ log.info(" > {}", ti.next());
+ }
+ Assert.assertTrue(wp.getMGraph(nur).contains(t));
+ Assert.assertTrue(wp.getMGraph(ur).isEmpty());
+ // We delete the empty graph
+ wp.deleteTripleCollection(ur);
+ Assert.assertFalse(wp.listGraphs().contains(ur));
+ Assert.assertFalse(wp.listMGraphs().contains(ur));
+ // But the other is still there
+ Assert.assertTrue(wp.listGraphs().contains(nur));
+ Assert.assertTrue(wp.listMGraphs().contains(nur));
+ // And it still contains its triple
+ Assert.assertTrue(wp.getMGraph(nur).contains(t));
+ // We delete the triple
+ wp.getMGraph(nur).remove(t);
+ Assert.assertFalse(wp.getMGraph(nur).contains(t));
+ Assert.assertTrue(wp.getMGraph(nur).isEmpty());
+ // We delete the non empty graph
+ wp.deleteTripleCollection(nur);
+ Assert.assertFalse(wp.listGraphs().contains(nur));
+ Assert.assertFalse(wp.listMGraphs().contains(nur));
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/resources/log4j.properties b/rdf.virtuoso.storage/src/test/resources/log4j.properties
new file mode 100644
index 0000000..ad89d4d
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/resources/log4j.properties
@@ -0,0 +1,6 @@
+log4j.rootLogger=INFO, S
+log4j.appender.S = org.apache.log4j.ConsoleAppender
+log4j.appender.S.layout = org.apache.log4j.PatternLayout
+log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
+
+log4j.logger.rdf.virtuoso.storage=DEBUG
[2/5] CLEREZZA-813 Moved the two virtuoso modules to the clerezza
root folder. Added to the main pom.xml
Posted by en...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
new file mode 100644
index 0000000..1e4628b
--- /dev/null
+++ b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
@@ -0,0 +1,937 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage.access;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.Writer;
+import java.math.BigInteger;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.clerezza.rdf.core.Graph;
+import org.apache.clerezza.rdf.core.MGraph;
+import org.apache.clerezza.rdf.core.TripleCollection;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.access.EntityAlreadyExistsException;
+import org.apache.clerezza.rdf.core.access.EntityUndeletableException;
+import org.apache.clerezza.rdf.core.access.NoSuchEntityException;
+import org.apache.clerezza.rdf.core.access.TcManager;
+import org.apache.clerezza.rdf.core.access.WeightedTcProvider;
+import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoGraph;
+import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoMGraph;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Properties;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Service;
+import org.osgi.framework.Constants;
+import org.osgi.service.cm.ConfigurationException;
+import org.osgi.service.component.ComponentContext;
+import org.osgi.service.component.ComponentException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import virtuoso.jdbc4.VirtuosoConnection;
+import virtuoso.jdbc4.VirtuosoException;
+import virtuoso.jdbc4.VirtuosoPreparedStatement;
+import virtuoso.jdbc4.VirtuosoResultSet;
+import virtuoso.jdbc4.VirtuosoStatement;
+
+/**
+ * A {@link org.apache.clerezza.rdf.core.access.WeightedTcProvider} for
+ * Virtuoso.
+ *
+ * @author enridaga
+ *
+ */
+@Component(metatype = true, immediate = true)
+@Service(WeightedTcProvider.class)
+@Properties({
+ @Property(name = "password", description = "User password"),
+ @Property(name = "host", description = "The host running the Virtuoso server"),
+ @Property(name = "port", description = "The port number"),
+ @Property(name = "user", description = "User name"),
+ @Property(name = "weight", intValue = 110, description = "Weight assigned to this provider"),
+ @Property(name = TcManager.GENERAL_PURPOSE_TC, boolValue = true) })
+public class VirtuosoWeightedProvider implements WeightedTcProvider {
+
+ // JDBC driver class (XXX move to DataAccess?)
+ public static final String DRIVER = "virtuoso.jdbc4.Driver";
+
+ // Default value for the property "weight"
+ public static final int DEFAULT_WEIGHT = 110;
+
+ // Names of properties in OSGi configuration
+ public static final String HOST = "host";
+ public static final String PORT = "port";
+ public static final String USER = "user";
+ public static final String PASSWORD = "password";
+ public static final String WEIGHT = "weight";
+
+ // Name of the graph used to contain the registry of the created graphs
+ public static final String ACTIVE_GRAPHS_GRAPH = "urn:x-virtuoso:active-graphs";
+
+ // Loaded graphs
+ private Map<UriRef, VirtuosoMGraph> graphs = new HashMap<UriRef, VirtuosoMGraph>();
+
+ // DataAccess registry
+ private Set<DataAccess> dataAccessSet = new HashSet<DataAccess>();
+
+ // Logger
+ private Logger logger = LoggerFactory
+ .getLogger(VirtuosoWeightedProvider.class);
+
+ // Fields
+ private String host;
+ private Integer port;
+ private String user;
+ private String pwd;
+ private String connStr;
+ private int weight = DEFAULT_WEIGHT;
+
+ /**
+ * Creates a new {@link VirtuosoWeightedProvider}.
+ *
+ * Before the weighted provider can be used, the method
+ * <code>activate</code> has to be called.
+ */
+ public VirtuosoWeightedProvider() {
+ logger.debug("Created VirtuosoWeightedProvider.");
+ }
+
+ public VirtuosoWeightedProvider(String jdbcConnectionString,
+ String jdbcUser, String jdbcPassword) {
+ connStr = jdbcConnectionString;
+ user = jdbcUser;
+ pwd = jdbcPassword;
+ }
+
+ /**
+ * Activates this component.<br />
+ *
+ * @param cCtx
+ * Execution context of this component. A value of null is
+ * acceptable when you set the property connection
+ * @throws ConfigurationException
+ * @throws IllegalArgumentException
+ * No component context given and connection was not set.
+ */
+ @Activate
+ public void activate(ComponentContext cCtx) {
+ logger.trace("activate(ComponentContext {})", cCtx);
+ logger.info("Activating VirtuosoWeightedProvider...");
+
+ if (cCtx == null) {
+ logger.error("No component context given and connection was not set");
+ throw new IllegalArgumentException(
+ "No component context given and connection was not set");
+ } else if (cCtx != null) {
+ logger.debug("Context is given: {}", cCtx);
+ String pid = (String) cCtx.getProperties().get(
+ Constants.SERVICE_PID);
+ try {
+
+ // Bind logging of DriverManager
+ if (logger.isDebugEnabled()) {
+ logger.debug("Activating logging for DriverManager");
+ // DriverManager.setLogWriter(new PrintWriter(System.err));
+ DriverManager.setLogWriter(new PrintWriter(new Writer() {
+ private Logger l = LoggerFactory
+ .getLogger(DriverManager.class);
+ private StringBuilder b = new StringBuilder();
+
+ @Override
+ public void write(char[] cbuf, int off, int len)
+ throws IOException {
+ b.append(cbuf, off, len);
+ }
+
+ @Override
+ public void flush() throws IOException {
+ l.debug("{}", b.toString());
+ b = new StringBuilder();
+ }
+
+ @Override
+ public void close() throws IOException {
+ l.debug("{}", b.toString());
+ l.debug("Log DriverManager PrintWriter closed");
+ }
+ }));
+ }
+
+ // FIXME The following should not be needed...
+ try {
+ this.weight = (Integer) cCtx.getProperties().get(WEIGHT);
+ } catch (NumberFormatException nfe) {
+ logger.warn(nfe.toString());
+ logger.warn("Setting weight to defaults");
+ this.weight = DEFAULT_WEIGHT;
+ }
+
+ /**
+ * Initialize connection properties
+ */
+ // We take the configuration of the SCR component
+ Object phost = cCtx.getProperties().get(HOST);
+ Object pport = cCtx.getProperties().get(PORT);
+ Object puser = cCtx.getProperties().get(USER);
+ Object ppwd = cCtx.getProperties().get(PASSWORD);
+
+ // If the component is not configured, we inspect system properties
+ // Maybe this is a first launch, otherwise we set a value as default
+ if(phost == null && System.getProperty("virtuoso.host") != null){
+ phost = System.getProperty("virtuoso.host");
+ } else if(phost == null){
+ phost = "localhost";
+ }
+ if(pport == null && System.getProperty("virtuoso.port") != null){
+ pport = System.getProperty("virtuoso.port");
+ } else if(pport == null){
+ pport = Integer.valueOf(1111);
+ }
+ if(puser == null && System.getProperty("virtuoso.user") != null){
+ puser = System.getProperty("virtuoso.user");
+ } else if(puser == null){
+ puser = "dba";
+ }
+ if(ppwd == null && System.getProperty("virtuoso.password") != null){
+ ppwd = System.getProperty("virtuoso.password");
+ } else if(ppwd == null){
+ ppwd = "dba";
+ }
+ // We set the configuration
+ host = (String) phost;
+ port = (Integer) pport;
+ user = (String) puser;
+ pwd = (String) ppwd;
+
+ // Build connection string
+ connStr = getConnectionString(host, port);
+
+ // Check connection
+ VirtuosoConnection connection = getConnection(connStr, user,
+ pwd);
+ logger.info("Connection to {} initialized. User is {}", connStr, user);
+ // everything went ok
+ connection.close();
+ } catch (VirtuosoException e) {
+ logger.error(
+ "A problem occurred while initializing connection to Virtuoso",
+ e);
+ logger.error("Be sure you have configured the connection parameters correctly in the OSGi/SCR configuration");
+ cCtx.disableComponent(pid);
+ throw new ComponentException(e.getLocalizedMessage());
+ } catch (SQLException e) {
+ logger.error(
+ "A problem occurred while initializing connection to Virtuoso",
+ e);
+ logger.error("Be sure you have configured the connection parameters correctly in the OSGi/SCR configuration");
+ cCtx.disableComponent(pid);
+ throw new ComponentException(e.getLocalizedMessage());
+ } catch (ClassNotFoundException e) {
+ logger.error(
+ "A problem occurred while initializing connection to Virtuoso",
+ e);
+ logger.error("Be sure you have configured the connection parameters correctly in the OSGi/SCR configuration");
+ cCtx.disableComponent(pid);
+ throw new ComponentException(e.getLocalizedMessage());
+ }
+ }
+ // Load remembered graphs
+ Set<UriRef> remembered = readRememberedGraphs();
+ for (UriRef name : remembered) {
+ if (canModify(name)) {
+ graphs.put(name, new VirtuosoMGraph(name.getUnicodeString(),
+ createDataAccess()));
+ } else {
+ graphs.put(name, new VirtuosoGraph(name.getUnicodeString(),
+ createDataAccess()));
+ }
+ }
+ logger.info("Activated VirtuosoWeightedProvider.");
+ }
+
+ public static final String getConnectionString(String hostName,
+ Integer portNumber) {
+ return new StringBuilder().append("jdbc:virtuoso://").append(hostName)
+ .append(":").append(portNumber).append("/CHARSET=UTF-8")
+ .toString();
+ }
+
+ private Set<UriRef> readRememberedGraphs() {
+ logger.trace(" readRememberedGraphs()");
+ String SQL = "SPARQL SELECT DISTINCT ?G FROM <" + ACTIVE_GRAPHS_GRAPH
+ + "> WHERE { ?G a <urn:x-virtuoso/active-graph> }";
+ VirtuosoConnection connection = null;
+ Exception e = null;
+ VirtuosoStatement st = null;
+ VirtuosoResultSet rs = null;
+ Set<UriRef> remembered = new HashSet<UriRef>();
+ try {
+ connection = getConnection();
+ st = (VirtuosoStatement) connection.createStatement();
+ logger.debug("Executing SQL: {}", SQL);
+ rs = (VirtuosoResultSet) st.executeQuery(SQL);
+ while (rs.next()) {
+ UriRef name = new UriRef(rs.getString(1));
+ logger.debug(" > Graph {}", name);
+ remembered.add(name);
+ }
+ } catch (VirtuosoException e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ } catch (SQLException e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ } catch (ClassNotFoundException e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ } finally {
+
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Exception ex) {
+ }
+ ;
+ try {
+ if (st != null)
+ st.close();
+ } catch (Exception ex) {
+ }
+ ;
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (VirtuosoException e1) {
+ logger.error("Cannot close connection", e1);
+ }
+ }
+ }
+ if (e != null) {
+ throw new RuntimeException(e);
+ }
+ return remembered;
+ }
+
+ private void rememberGraphs(UriRef... graphs) {
+ logger.trace(" saveActiveGraphs()");
+ if (graphs.length > 0) {
+ // Returns the list of graphs in the virtuoso quad store
+ String SQL = "SPARQL INSERT INTO <" + ACTIVE_GRAPHS_GRAPH
+ + "> { `iri(??)` a <urn:x-virtuoso/active-graph> }";
+ VirtuosoConnection connection = null;
+ Exception e = null;
+ VirtuosoPreparedStatement st = null;
+ VirtuosoResultSet rs = null;
+ try {
+ try {
+ connection = getConnection();
+ connection.setAutoCommit(false);
+ st = (VirtuosoPreparedStatement) connection
+ .prepareStatement(SQL);
+ logger.debug("Executing SQL: {}", SQL);
+ for (UriRef u : graphs) {
+ logger.trace(" > remembering {}", u);
+ st.setString(1, u.getUnicodeString());
+ st.executeUpdate();
+ }
+ connection.commit();
+ } catch (Exception e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ connection.rollback();
+ }
+ } catch (SQLException e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Exception ex) {
+ }
+ ;
+ try {
+ if (st != null)
+ st.close();
+ } catch (Exception ex) {
+ }
+ ;
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (VirtuosoException e1) {
+ logger.error("Cannot close connection", e1);
+ }
+ }
+ }
+ if (e != null) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ private void forgetGraphs(UriRef... graphs) {
+ logger.trace(" forgetGraphs()");
+ if (graphs.length > 0) {
+ // Returns the list of graphs in the virtuoso quad store
+ String SQL = "SPARQL WITH <"
+ + ACTIVE_GRAPHS_GRAPH
+ + "> DELETE { ?s ?p ?v } WHERE { ?s ?p ?v . FILTER( ?s = iri(??) ) }";
+ VirtuosoConnection connection = null;
+ Exception e = null;
+ VirtuosoPreparedStatement st = null;
+ VirtuosoResultSet rs = null;
+ try {
+ try {
+ connection = getConnection();
+ connection.setAutoCommit(false);
+ st = (VirtuosoPreparedStatement) connection
+ .prepareStatement(SQL);
+ logger.debug("Executing SQL: {}", SQL);
+ for (UriRef u : graphs) {
+ logger.trace(" > remembering {}", u);
+ st.setString(1, u.getUnicodeString());
+ st.executeUpdate();
+ }
+ connection.commit();
+ } catch (Exception e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ connection.rollback();
+ }
+ } catch (SQLException e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Exception ex) {
+ }
+ ;
+ try {
+ if (st != null)
+ st.close();
+ } catch (Exception ex) {
+ }
+ ;
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (VirtuosoException e1) {
+ logger.error("Cannot close connection", e1);
+ }
+ }
+ }
+ if (e != null) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ /**
+ * Deactivates this component.
+ *
+ * @param cCtx
+ * component context provided by OSGi
+ */
+ @Deactivate
+ public void deactivate(ComponentContext cCtx) {
+ logger.debug("deactivate(ComponentContext {})", cCtx);
+ // Save active (possibly empty) graphs to a dedicated graph
+ rememberGraphs();
+ // XXX Important. Close all opened resources
+ for (DataAccess mg : dataAccessSet) {
+ mg.close();
+ }
+ logger.info("Shutdown complete.");
+ }
+
+ public VirtuosoConnection getConnection() throws SQLException,
+ ClassNotFoundException {
+ return getConnection(connStr, user, pwd);
+ }
+
+ private VirtuosoConnection getConnection(final String connStr,final String user,
+ final String pwd) throws SQLException, ClassNotFoundException {
+ logger.debug("getConnection(String {}, String {}, String *******)",
+ connStr, user);
+ /**
+ * FIXME For some reasons, it looks the DriverManager is instantiating a
+ * new virtuoso.jdbc4.Driver instance upon any activation. (Enable DEBUG
+ * to see this)
+ */
+ logger.debug("Loading JDBC Driver");
+ try {
+ VirtuosoConnection c = AccessController
+ .doPrivileged(new PrivilegedAction<VirtuosoConnection>() {
+ public VirtuosoConnection run() {
+ try {
+ Class.forName(VirtuosoWeightedProvider.DRIVER,
+ true, this.getClass().getClassLoader());
+ return (VirtuosoConnection) DriverManager
+ .getConnection(connStr, user, pwd);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ c.setAutoCommit(true);
+ return c;
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Retrieves the Graph (unmodifiable) with the given UriRef If no graph
+ * exists with such name, throws a NoSuchEntityException
+ */
+ @Override
+ public Graph getGraph(UriRef name) throws NoSuchEntityException {
+ logger.debug("getGraph(UriRef {}) ", name);
+ // If it is read-only, returns the Graph
+ // If it is not read-only, returns the getGraph() version of the MGraph
+ VirtuosoMGraph g = loadGraphOnce(name);
+ if (g instanceof Graph) {
+ return (Graph) g;
+ } else {
+ return g.getGraph();
+ }
+ }
+
+ /**
+ * Retrieves the MGraph (modifiable) with the given UriRef. If no graph
+ * exists with such name, throws a NoSuchEntityException.
+ *
+ * @return mgraph
+ */
+ @Override
+ public MGraph getMGraph(UriRef name) throws NoSuchEntityException {
+ logger.debug("getMGraph(UriRef {}) ", name);
+ VirtuosoMGraph g = loadGraphOnce(name);
+ if (g instanceof Graph) {
+ // We have this graph but only in read-only mode!
+ throw new NoSuchEntityException(name);
+ }
+ return g;
+ }
+
+ /**
+ * Load the graph once. It check whether a graph object have been already
+ * created for that UriRef, if yes returns it.
+ *
+ * If not check if at least 1 triple is present in the quad for such graph
+ * identifier. If yes, creates a new graph object and loads it in the map,
+ * referring to it on next calls.
+ *
+ * This method returns a VirtuosoGraph if the graph is read-only
+ *
+ * @param name
+ * @return
+ */
+ private VirtuosoMGraph loadGraphOnce(UriRef name) {
+ logger.debug("loadGraphOnce({})", name);
+
+ // Check whether the graph have been already loaded once
+ if (graphs.containsKey(name)) {
+ logger.debug("{} is already loaded", name);
+ return graphs.get(name);
+ } else {
+ VirtuosoMGraph graph = null;
+ logger.debug("Attempt to load {}", name);
+ // Let's create the graph object
+ String SQL = "SPARQL SELECT ?G WHERE { GRAPH ?G {[] [] []} . FILTER(?G = "
+ + name + ")} LIMIT 1";
+
+ Statement st = null;
+ VirtuosoResultSet rs = null;
+ VirtuosoConnection connection = null;
+ Exception e = null;
+ try {
+ connection = getConnection(connStr, user, pwd);
+ st = connection.createStatement();
+ logger.debug("Executing SQL: {}", SQL);
+ st.execute(SQL);
+ rs = (VirtuosoResultSet) st.getResultSet();
+ if (rs.next() == false) {
+ // The graph is empty, it is not readable or does not exists
+ logger.debug("Graph does not exists: {}", name);
+ throw new NoSuchEntityException(name);
+ } else {
+ // The graph exists and it is readable ...
+ logger.trace("Graph {} is readable", name);
+ // is it writable?
+ logger.trace("Is {} writable?", name);
+ if (canModify(name)) {
+ logger.trace("Creating writable graph {}",
+ name);
+ graphs.put(name,
+ new VirtuosoMGraph(name.getUnicodeString(),
+ createDataAccess()));
+ } else {
+ logger.trace("Creating read-only graph {}",
+ name);
+ graphs.put(name,
+ new VirtuosoMGraph(name.getUnicodeString(),
+ createDataAccess()).asVirtuosoGraph());
+ }
+ graph = graphs.get(name);
+ }
+
+ } catch (VirtuosoException ve) {
+ logger.error("Error while executing query/connection.", ve);
+ e = ve;
+ } catch (SQLException se) {
+ logger.error("Error while executing query/connection.", se);
+ e = se;
+ } catch (ClassNotFoundException ce) {
+ logger.error("Error while executing query/connection.", ce);
+ e = ce;
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Exception ex) {
+ }
+ ;
+ try {
+ if (st != null)
+ st.close();
+ } catch (Exception ex) {
+ }
+ ;
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (VirtuosoException e1) {
+ logger.error("Cannot close connection", e1);
+ }
+ }
+ }
+ if (e != null) {
+ throw new RuntimeException(e);
+ }
+ return graph;
+ }
+
+ }
+
+ public DataAccess createDataAccess() {
+ DataAccess da = new DataAccess(connStr, user, pwd);
+ dataAccessSet.add(da);
+ // Remember all opened ones
+ return da;
+ }
+
+ /**
+ * Generic implementation of the get(M)Graph method. If the named graph is
+ * modifiable, behaves the same as getMGraph(UriRef name), elsewhere,
+ * behaves as getGraph(UriRef name)
+ */
+ @Override
+ public TripleCollection getTriples(UriRef name)
+ throws NoSuchEntityException {
+ logger.debug("getTriples(UriRef {}) ", name);
+ return loadGraphOnce(name);
+ }
+
+ /**
+ * Returns the list of graphs in the virtuoso quad store. The returned set
+ * is unmodifiable.
+ *
+ * @return graphs
+ */
+ @Override
+ public Set<UriRef> listGraphs() {
+ logger.debug("listGraphs()");
+ Set<UriRef> graphs = new HashSet<UriRef>();
+ // XXX Add the active (possibly empty) mgraphs
+ graphs.addAll(this.graphs.keySet());
+ // Returns the list of graphs in the virtuoso quad store
+ String SQL = "SPARQL SELECT DISTINCT ?G WHERE {GRAPH ?G {[] [] []} }";
+ VirtuosoConnection connection = null;
+ Exception e = null;
+ VirtuosoStatement st = null;
+ VirtuosoResultSet rs = null;
+ try {
+ connection = getConnection();
+ st = (VirtuosoStatement) connection.createStatement();
+ logger.debug("Executing SQL: {}", SQL);
+ rs = (VirtuosoResultSet) st.executeQuery(SQL);
+ while (rs.next()) {
+ UriRef graph = new UriRef(rs.getString(1));
+ logger.debug(" > Graph {}", graph);
+ graphs.add(graph);
+ }
+ } catch (VirtuosoException e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ } catch (SQLException e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ } catch (ClassNotFoundException e1) {
+ logger.error("Error while executing query/connection.", e1);
+ e = e1;
+ } finally {
+
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Exception ex) {
+ }
+ ;
+ try {
+ if (st != null)
+ st.close();
+ } catch (Exception ex) {
+ }
+ ;
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (VirtuosoException e1) {
+ logger.error("Cannot close connection", e1);
+ }
+ }
+ }
+ if (e != null) {
+ throw new RuntimeException(e);
+ }
+ return Collections.unmodifiableSet(graphs);
+ }
+
+ @Override
+ public Set<UriRef> listMGraphs() {
+ logger.debug("listMGraphs()");
+ Set<UriRef> graphs = listGraphs();
+ Set<UriRef> mgraphs = new HashSet<UriRef>();
+ logger.debug("Modifiable graphs:");
+ for (UriRef u : graphs) {
+ if (canModify(u)) {
+ logger.debug(" > {}", u);
+ mgraphs.add(u);
+ }
+ }
+ return Collections.unmodifiableSet(mgraphs);
+ }
+
+ private long getPermissions(String graph) {
+ VirtuosoConnection connection = null;
+ ResultSet rs = null;
+ Statement st = null;
+ logger.debug("getPermissions(String {})", graph);
+ Exception e = null;
+ Long result = null;
+ try {
+ connection = getConnection();
+ String sql = "SELECT DB.DBA.RDF_GRAPH_USER_PERMS_GET ('" + graph
+ + "','" + connection.getMetaData().getUserName() + "') ";
+ logger.debug("Executing SQL: {}", sql);
+ st = connection.createStatement();
+ st.execute(sql);
+ rs = st.getResultSet();
+ rs.next();
+ result = rs.getLong(1);
+ logger.debug("Permission: {}", result);
+ } catch (VirtuosoException ve) {
+ logger.error("A virtuoso SQL exception occurred.");
+ e = ve;
+ } catch (SQLException se) {
+ logger.error("An SQL exception occurred.");
+ e = se;
+ } catch (ClassNotFoundException e1) {
+ logger.error("An ClassNotFoundException occurred.");
+ e = e1;
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Exception ex) {
+ }
+ ;
+ try {
+ if (st != null)
+ st.close();
+ } catch (Exception ex) {
+ }
+ ;
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (VirtuosoException e1) {
+ logger.error("Cannot close connection", e1);
+ }
+ }
+ }
+ if (e != null) {
+ throw new RuntimeException(e);
+ }
+ return result;
+ }
+
+ public boolean canRead(UriRef graph) {
+ logger.debug("canRead(UriRef {})", graph);
+ return (isRead(getPermissions(graph.getUnicodeString())));
+ }
+
+ public boolean canModify(UriRef graph) {
+ logger.debug("canModify(UriRef {})", graph);
+ return (isWrite(getPermissions(graph.getUnicodeString())));
+ }
+
+ private boolean testPermission(long value, int bit) {
+ logger.debug("testPermission(long {},int {})", value, bit);
+ return BigInteger.valueOf(value).testBit(bit);
+ }
+
+ private boolean isRead(long permission) {
+ logger.debug("isRead(long {})", permission);
+ return testPermission(permission, 1);
+ }
+
+ private boolean isWrite(long permission) {
+ logger.debug("isWrite(long {})", permission);
+ return testPermission(permission, 2);
+ }
+
+ @Override
+ public Set<UriRef> listTripleCollections() {
+ logger.debug("listTripleCollections()");
+ // I think this should behave the same as listGraphs() in our case.
+ return listGraphs();
+ }
+
+ private VirtuosoMGraph createVirtuosoMGraph(UriRef name)
+ throws UnsupportedOperationException, EntityAlreadyExistsException {
+ logger.debug("createVirtuosoMGraph(UriRef {})", name);
+ // If the graph already exists, we throw an exception
+ try {
+ loadGraphOnce(name);
+ throw new EntityAlreadyExistsException(name);
+ } catch (NoSuchEntityException nsee) {
+ if (canModify(name)) {
+ graphs.put(name, new VirtuosoMGraph(name.getUnicodeString(),
+ createDataAccess()));
+ rememberGraphs(name);
+ return graphs.get(name);
+ } else {
+ logger.error("Cannot create MGraph {}", name);
+ throw new UnsupportedOperationException();
+ }
+ }
+ }
+
+ /**
+ * Creates an initially empty MGraph. If the name already exists in the
+ * store, throws an {@see EntityAlreadyExistsException}
+ */
+ @Override
+ public MGraph createMGraph(UriRef name)
+ throws UnsupportedOperationException, EntityAlreadyExistsException {
+ logger.debug("createMGraph(UriRef {})", name);
+ return createVirtuosoMGraph(name);
+ }
+
+ /**
+ * Creates a new graph with the given triples, then returns the readable
+ * (not modifiable) version of the graph
+ *
+ */
+ @Override
+ public Graph createGraph(UriRef name, TripleCollection triples)
+ throws UnsupportedOperationException, EntityAlreadyExistsException {
+ logger.debug("createGraph(UriRef {}, TripleCollection {})", name,
+ triples);
+ VirtuosoMGraph mgraph = createVirtuosoMGraph(name);
+ mgraph.addAll(triples);
+ return mgraph.getGraph();
+ }
+
+ /**
+ * Clears the given graph and removes it from the loaded graphs.
+ *
+ */
+ @Override
+ public void deleteTripleCollection(UriRef name)
+ throws UnsupportedOperationException, NoSuchEntityException,
+ EntityUndeletableException {
+ logger.debug("deleteTripleCollection(UriRef {})", name);
+ TripleCollection g = (VirtuosoMGraph) getTriples(name);
+ if (g instanceof Graph) {
+ throw new EntityUndeletableException(name);
+ } else {
+ ((MGraph) g).clear();
+ graphs.remove(name);
+ forgetGraphs(name);
+ }
+ }
+
+ /**
+ * Returns the names of a graph. Personally don't know why a graph should
+ * have more then 1 identifier. Anyway, this does not happen with Virtuoso
+ *
+ * @return names
+ */
+ @Override
+ public Set<UriRef> getNames(Graph graph) {
+ logger.debug("getNames(Graph {})", graph);
+ return Collections.singleton(new UriRef(((VirtuosoMGraph) graph)
+ .getName()));
+ }
+
+ /**
+ * Returns the weight of this provider.
+ *
+ */
+ @Override
+ public int getWeight() {
+ logger.debug("getWeight()");
+ /**
+ * The weight
+ */
+ return this.weight;
+ }
+
+ /**
+ * Sets the weight
+ *
+ * @param weight
+ */
+ public void setWeight(int weight) {
+ logger.debug("setWeight(int {})", weight);
+ this.weight = weight;
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.access.WeightedTcProvider
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.access.WeightedTcProvider b/rdf.virtuoso.storage/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.access.WeightedTcProvider
new file mode 100644
index 0000000..bfb2afc
--- /dev/null
+++ b/rdf.virtuoso.storage/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.access.WeightedTcProvider
@@ -0,0 +1 @@
+rdf.virtuoso.storage.access.VirtuosoWeightedProvider
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/main/resources/log4j.properties b/rdf.virtuoso.storage/src/main/resources/log4j.properties
new file mode 100644
index 0000000..201aca8
--- /dev/null
+++ b/rdf.virtuoso.storage/src/main/resources/log4j.properties
@@ -0,0 +1,5 @@
+#log4j.rootLogger=DEBUG, S
+#log4j.appender.S = org.apache.log4j.ConsoleAppender
+#log4j.appender.S.layout = org.apache.log4j.PatternLayout
+#log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
+
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ConnectionTest.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ConnectionTest.java b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ConnectionTest.java
new file mode 100644
index 0000000..6a1e4b5
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ConnectionTest.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Map.Entry;
+import java.util.Properties;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import virtuoso.jdbc4.VirtuosoConnection;
+import virtuoso.jdbc4.VirtuosoException;
+
+/**
+ * Tests the connection to the Virtuoso DBMS
+ *
+ * @author enridaga
+ */
+public class ConnectionTest {
+
+ static final Logger log = LoggerFactory.getLogger(ConnectionTest.class);
+
+ private static VirtuosoConnection connection = null;
+
+ @BeforeClass
+ public static void before() throws ClassNotFoundException, SQLException {
+ org.junit.Assume.assumeTrue(!TestUtils.SKIP);
+ connection = TestUtils.getConnection();
+ }
+
+ @Test
+ public void testIsClosed() {
+ assertFalse(connection.isClosed());
+ }
+
+ @Test
+ public void testIsConnectionLost() {
+ assertFalse(connection.isConnectionLost(0));
+ }
+
+ @Test
+ public void testIsReadOnly() throws VirtuosoException {
+ assertFalse(connection.isReadOnly());
+ }
+
+ @Test
+ public void testConnection() {
+ log.info("testConnection()");
+ try {
+
+ Statement st = connection.createStatement();
+ log.debug("Populate graph <mytest>");
+ String[] queries = {
+ "sparql clear graph <mytest>",
+ "sparql insert into graph <mytest> { <xxx> <P01> \"test1\"@en }",
+ "sparql insert into graph <mytest> { <xxx> <P01> \"test2\"@it }",
+ "sparql PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> insert into graph <mytest> { <xxx> <P01> \"test3\"^^xsd:string }",
+ "sparql insert into graph <mytest> { <xxx> <P01> \"test4\" }",
+ "sparql insert into graph <mytest> { <xxx> <P01> \"test5\" . <xxx> <P02> _:b1"
+ + " . _:b1 <P03> <yyy> " + " . _:b3 <P05> <zzz> "
+ + " . _:b3 <P05> <ppp> " +
+ // This is to consider that we can force it
+ " . <nodeID://b10005> <P05> <ooo> " + " }",
+ "sparql insert into graph <mytest> { <nodeID://b10005> <property> <nodeID://b10007>}",
+ "sparql insert into graph <mytest> { <enridaga> <property> \"Literal value\"^^<http://datatype#type>}",
+ "sparql insert into graph <mytest> { <nodeID://b10005> <property> <nodeID://b10007>}" };
+ for (String q : queries) {
+ log.debug("Querying: {}", q);
+ st.execute(q);
+ }
+
+ String query = "sparql SELECT * from <mytest> WHERE {?s ?p ?o}";
+ log.debug("Querying: {}", query);
+ ResultSet rs = st.executeQuery(query);
+ TestUtils.stamp(rs);
+ } catch (SQLException e) {
+ log.error("SQL ERROR: ", e);
+ assertTrue(false);
+ } catch (Exception e) {
+ log.error("SQL ERROR: ", e);
+ assertTrue(false);
+ }
+ }
+
+ @Test
+ public void test() throws ClassNotFoundException, SQLException {
+ DatabaseMetaData dm = connection.getMetaData();
+ log.debug("Username is {}", dm.getUserName());
+ Properties p = connection.getClientInfo();
+ if (p == null) {
+ log.warn("Client info is null...");
+ } else
+ for (Entry<Object, Object> e : p.entrySet()) {
+ log.info("Client info property: {} => {}", e.getKey(),
+ e.getValue());
+ }
+ String SQL = "SELECT DISTINCT id_to_iri(G) FROM DB.DBA.RDF_QUAD quad ";
+ VirtuosoConnection cn = TestUtils.getConnection();
+ long startAt = System.currentTimeMillis();
+ // get the list of quad using SQL
+ log.debug("Executing SQL: {}", SQL);
+ cn.createStatement().executeQuery(SQL);
+ long endAt = System.currentTimeMillis();
+ log.debug("Using SQL: {}ms", endAt - startAt);
+ SQL = "SPARQL SELECT DISTINCT ?G WHERE {GRAPH ?G {?S ?P ?O} }";
+ startAt = System.currentTimeMillis();
+ // get the list of quad using SQL+SPARQL
+ log.debug("Executing SQL: {}", SQL);
+ cn.createStatement().executeQuery(SQL);
+ endAt = System.currentTimeMillis();
+ log.debug("Using SQL+SPARQL: {}ms", endAt - startAt);
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/RdfIOTest.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/RdfIOTest.java b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/RdfIOTest.java
new file mode 100644
index 0000000..7221c9b
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/RdfIOTest.java
@@ -0,0 +1,352 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import java.io.IOException;
+import java.net.URL;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Iterator;
+
+import org.apache.clerezza.platform.config.SystemConfig;
+import org.apache.clerezza.rdf.core.BNode;
+import org.apache.clerezza.rdf.core.MGraph;
+import org.apache.clerezza.rdf.core.NonLiteral;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.TypedLiteral;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.impl.TripleImpl;
+import org.apache.clerezza.rdf.core.impl.TypedLiteralImpl;
+import org.apache.clerezza.rdf.core.serializedform.ParsingProvider;
+import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
+import org.apache.clerezza.rdf.jena.parser.JenaParserProvider;
+import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoBNode;
+import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoMGraph;
+import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import virtuoso.jdbc4.VirtuosoException;
+
+public class RdfIOTest {
+ static VirtuosoMGraph mgraph = null;
+ static final String TEST_GRAPH_NAME = "RdfIOTest";
+ static final String XSD = "http://www.w3.org/2001/XMLSchema#";
+ static Logger log = LoggerFactory.getLogger(RdfIOTest.class);
+ static DataAccess da;
+
+ @BeforeClass
+ public static void assume(){
+ org.junit.Assume.assumeTrue(!TestUtils.SKIP);
+ }
+
+ /**
+ * Clean before any test
+ *
+ * @throws ClassNotFoundException
+ * @throws SQLException
+ */
+ @Before
+ public void before() throws ClassNotFoundException, SQLException {
+
+ da = TestUtils.getProvider().createDataAccess();
+ mgraph = new VirtuosoMGraph(TEST_GRAPH_NAME, da);
+ mgraph.clear();
+ log.debug("Clearing graph <{}>", TEST_GRAPH_NAME);
+ }
+
+ /**
+ * Clean after a test
+ *
+ * @throws VirtuosoException
+ * @throws ClassNotFoundException
+ * @throws SQLException
+ */
+ @After
+ public void clear() throws VirtuosoException, ClassNotFoundException,
+ SQLException {
+ log.debug("Clearing graph <{}> of size {}", TEST_GRAPH_NAME,
+ mgraph.size());
+ // clear all resources
+ da.close();
+
+ da = null;
+ mgraph = null;
+
+ log.debug("Removing graph <{}>", TEST_GRAPH_NAME);
+ Statement st = TestUtils.getConnection().createStatement();
+ st.execute("SPARQL CLEAR GRAPH <" + TEST_GRAPH_NAME + ">");
+ st.close();
+ }
+
+ @Test
+ public void xsdString() throws ClassNotFoundException, SQLException {
+ log.info("Text an xsd:string");
+ TypedLiteral object = new TypedLiteralImpl("lorem ipsum", new UriRef(
+ XSD + "string"));
+ UriRef subject = new UriRef("urn:io-test:reto");
+ UriRef predicate = new UriRef("urn:io-test:hasText");
+
+ Triple read = writeAndRead(subject, predicate, object);
+ Assert.assertTrue(read
+ .equals(new TripleImpl(subject, predicate, object)));
+ Assert.assertTrue(read.getObject() instanceof TypedLiteral);
+ TypedLiteral l = (TypedLiteral) read.getObject();
+ Assert.assertEquals(l.getLexicalForm(), "lorem ipsum");
+ Assert.assertEquals(l.getDataType(), new UriRef(XSD + "string"));
+
+ }
+
+ @Test
+ public void longString() throws ClassNotFoundException, SQLException, InterruptedException {
+ log.info("Test a long xsd:string");
+ StringBuilder longStr = new StringBuilder();
+ int c = 250000;
+ while (c > 0) {
+ longStr.append(" lorem ipsum ");
+ c--;
+ }
+ int size = longStr.length();
+ TypedLiteral object = new TypedLiteralImpl(longStr.toString(),
+ new UriRef(XSD + "string"));
+ UriRef subject = new UriRef("urn:io-test:reto");
+ UriRef predicate = new UriRef("urn:io-test:hasText");
+ Triple read = writeAndRead(subject, predicate, object);
+ Assert.assertTrue(read
+ .equals(new TripleImpl(subject, predicate, object)));
+ Assert.assertTrue(read.getObject() instanceof TypedLiteral);
+ TypedLiteral l = (TypedLiteral) read.getObject();
+ Assert.assertEquals(l.getDataType(), new UriRef(XSD + "string"));
+ Assert.assertTrue(l.getLexicalForm().length() == size);
+ }
+
+ private Triple writeAndRead(NonLiteral subject, UriRef predicate,
+ Resource object) throws ClassNotFoundException, SQLException {
+ Triple t = new TripleImpl(subject, predicate, object);
+ mgraph.add(t);
+ Triple read = mgraph.getGraph().iterator().next();
+ return read;
+ }
+
+ @Test
+ public void subjectAsUriTest() throws ClassNotFoundException, SQLException {
+ log.info("Test subject as UriRef");
+
+ NonLiteral subject;
+ UriRef predicate = new UriRef("urn:io-test:predicate");
+ UriRef object = new UriRef("urn:io-test:object");
+
+ // subject may be UriRef
+ subject = new UriRef("urn:io-test:enridaga");
+ Triple read = writeAndRead(subject, predicate, object);
+ Assert.assertTrue(read.getSubject().equals(subject));
+ Assert.assertEquals(read.getSubject(), new UriRef(
+ "urn:io-test:enridaga"));
+ Assert.assertNotSame(read.getSubject(), new UriRef(
+ "urn:io-test:alexdma"));
+ Assert.assertEquals(read, new TripleImpl(subject, predicate, object));
+
+ }
+
+ @Test
+ public void subjectAsBnodeTest() throws ClassNotFoundException,
+ SQLException {
+ log.info("Test subject as BNode");
+
+ NonLiteral subject;
+ UriRef predicate = new UriRef("urn:io-test:predicate");
+ UriRef object = new UriRef("urn:io-test:object");
+
+ // subject may be BNode
+ subject = new BNode();
+ Triple read = writeAndRead(subject, predicate, object);
+ // bnodes cannot be equals!
+ Assert.assertFalse(read.getSubject().equals(subject));
+ Assert.assertTrue(read.getSubject() instanceof BNode);
+ Assert.assertNotSame(read.getSubject(), new UriRef(
+ "urn:io-test:enridaga"));
+ Assert.assertNotSame(read.getSubject(), new UriRef(
+ "urn:io-test:alexdma"));
+ // bnodes cannot be equals!
+ Assert.assertNotSame(read, new TripleImpl(subject, predicate, object));
+ }
+
+ @Test
+ public void objectAsUriTest() throws ClassNotFoundException, SQLException {
+ log.info("Test object as UriRef");
+
+ NonLiteral subject = new UriRef("urn:io-test:enridaga");
+ UriRef predicate = new UriRef("urn:io-test:predicate");
+ UriRef object = new UriRef("urn:io-test:object");
+
+ Triple read = writeAndRead(subject, predicate, object);
+ //
+ Assert.assertTrue(read.getObject().equals(object));
+ Assert.assertTrue(read.getObject() instanceof UriRef);
+ Assert.assertEquals(read.getObject(), new UriRef("urn:io-test:object"));
+ Assert.assertNotSame(read.getSubject(), new UriRef(
+ "urn:io-test:alexdma"));
+ Assert.assertEquals(read, new TripleImpl(subject, predicate, object));
+ }
+
+ @Test
+ public void objectAsBnodeTest() throws ClassNotFoundException, SQLException {
+ log.info("Test object as Bnode");
+
+ NonLiteral subject = new UriRef("urn:io-test:subject");
+ UriRef predicate = new UriRef("urn:io-test:predicate");
+ Resource object;
+
+ // subject may be BNode
+ object = new BNode();
+ Triple read = writeAndRead(subject, predicate, object);
+ // bnodes cannot be equals!
+ Assert.assertFalse(read.getObject().equals(object));
+ Assert.assertTrue(read.getSubject().equals(subject));
+
+ Assert.assertTrue(read.getObject() instanceof BNode);
+ Assert.assertTrue(read.getObject() instanceof VirtuosoBNode);
+
+ Assert.assertNotSame(read.getObject(), new UriRef(
+ "urn:io-test:enridaga"));
+ Assert.assertNotSame(read.getObject(),
+ new UriRef("urn:io-test:alexdma"));
+ // these bnodes cannot be equals!
+ Assert.assertNotSame(read, new TripleImpl(subject, predicate, object));
+ }
+
+ @Test
+ public void bnodesTest() throws ClassNotFoundException, SQLException {
+ log.info("Test iterations and filter with bnode");
+
+ NonLiteral s1 = new BNode();
+ NonLiteral s2 = new BNode();
+ NonLiteral s3 = new BNode();
+ NonLiteral s4 = new BNode();
+
+ UriRef p1 = new UriRef("p1");
+ UriRef p2 = new UriRef("p2");
+ UriRef p3 = new UriRef("p3");
+
+ mgraph.add(new TripleImpl(s1, p1, s2));
+ // Get the bnode of s1
+ Triple first = mgraph.filter(null, p1, null).next();
+
+ Assert.assertTrue(first.getSubject() instanceof VirtuosoBNode);
+ Assert.assertTrue(first.getObject() instanceof VirtuosoBNode);
+
+ BNode s1intern = (BNode) first.getSubject();
+ BNode s2intern = (BNode) first.getObject();
+
+ mgraph.add(new TripleImpl(s2intern, p1, s3));
+ Triple second = mgraph.filter(s2intern, p1, null).next();
+ Assert.assertTrue(second.getObject() instanceof VirtuosoBNode);
+
+ mgraph.add(new TripleImpl(s1intern, p2, s4));
+ Triple third = mgraph.filter(s1intern, p2, null).next();
+ Assert.assertTrue(third.getObject() instanceof VirtuosoBNode);
+ BNode s4intern = (BNode) third.getObject();
+
+ mgraph.add(new TripleImpl(s1intern, p2, s4intern));
+ mgraph.add(new TripleImpl(s4intern, p3, s1intern));
+
+ Iterator<Triple> all = mgraph.iterator();
+ while(all.hasNext()){
+ Triple l = all.next();
+ log.info("{} {} {}",new Object[]{ l.getSubject(), l.getPredicate(), l.getObject()});
+ }
+ Iterator<Triple> i = mgraph.filter(null, p2, null);
+ int n = 0;
+ while (i.hasNext()) {
+ n++;
+ Triple s1t = i.next();
+ Iterator<Triple> s1i = mgraph.filter(s1t.getSubject(), null, null);
+ boolean found = false;
+ while (s1i.hasNext()) {
+ Triple s1it = s1i.next();
+ found = true;
+ log.info("{} {}",s1it.getSubject(), s1t.getSubject());
+ Assert.assertTrue(s1it.getSubject().equals(s1t.getSubject()));
+ Assert.assertTrue(s1it.getPredicate().equals(p1)
+ || s1it.getPredicate().equals(p2));
+
+ }
+ Assert.assertTrue(found);
+ Assert.assertTrue(s1t.getObject() instanceof VirtuosoBNode);
+ Assert.assertTrue(s1t.getSubject() instanceof VirtuosoBNode);
+ Iterator<Triple> s4i = mgraph.filter((NonLiteral) s1t.getObject(),
+ null, null);
+ log.info("s4 {} ",s1t.getObject());
+ while (s4i.hasNext()) {
+ Triple s4it = s4i.next();
+ log.info("{} {}",s4it.getSubject(), s1t.getObject());
+ Assert.assertTrue(s4it.getSubject().equals(s1t.getObject()));
+ Assert.assertTrue(s4it.getPredicate().equals(p3));
+ }
+ }
+ Assert.assertEquals(n, 1);
+
+ }
+
+ @Test
+ public void sysconfigTest(){
+
+ SystemConfig sc = new SystemConfig();
+ MGraph systemGraph = mgraph;
+ URL config = sc.getClass().getResource(SystemConfig.CONFIG_FILE);
+ if (config == null) {
+ throw new RuntimeException("no config file found");
+ }
+ ParsingProvider parser = new JenaParserProvider();
+ try {
+ parser.parse(systemGraph, config.openStream(),
+ SupportedFormat.RDF_XML, null);
+ } catch (IOException ex) {
+ log.warn("Cannot parse coniguration at URL: {}", config);
+ throw new RuntimeException(ex);
+ }
+ }
+
+ @Test
+ public void testUnicodeChars() throws ClassNotFoundException, SQLException {
+ log.info("Text an xsd:string");
+
+ String s = "lorem ipsum è é £ ò ç à ù β ät ü ä";
+ TypedLiteral object = new TypedLiteralImpl(s, new UriRef(
+ XSD + "string"));
+ UriRef subject = new UriRef("urn:io-test:reto");
+ UriRef predicate = new UriRef("urn:io-test:hasText");
+
+ Triple read = writeAndRead(subject, predicate, object);
+ log.info("o: {} :: {}", object, read.getObject());
+ Assert.assertTrue(read
+ .equals(new TripleImpl(subject, predicate, object)));
+ Assert.assertTrue(read.getObject() instanceof TypedLiteral);
+ TypedLiteral l = (TypedLiteral) read.getObject();
+ Assert.assertEquals(l.getLexicalForm(), s);
+ Assert.assertEquals(l.getDataType(), new UriRef(XSD + "string"));
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/TestUtils.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/TestUtils.java b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/TestUtils.java
new file mode 100644
index 0000000..e96d62b
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/TestUtils.java
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.virtuoso.storage.access.VirtuosoWeightedProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import virtuoso.jdbc4.VirtuosoConnection;
+import virtuoso.jdbc4.VirtuosoExtendedString;
+import virtuoso.jdbc4.VirtuosoRdfBox;
+import virtuoso.jdbc4.VirtuosoResultSet;
+
+/**
+ * Utilities for tests
+ *
+ * @author enridaga
+ *
+ */
+public class TestUtils {
+
+ public static final String FOAF_NS = "http://xmlns.com/foaf/0.1/";
+
+ private static VirtuosoWeightedProvider provider = null;
+ private static String jdbcConnectionString = null;
+ private static String jdbcUser = null;
+ private static String jdbcPassword = null;
+ private static String jdbcDriver = null;
+
+ static Logger log = LoggerFactory.getLogger(TestUtils.class);
+ public static boolean SKIP = false;
+ static {
+ String skipProperty = System.getProperty("virtuoso.test");
+ if (skipProperty == null) {
+ log.info("virtuoso.skip property is not set. We skip tests by default.");
+ SKIP = true;
+ } else
+ SKIP = !skipProperty.equals("true");
+ }
+
+ public static VirtuosoConnection getConnection() throws SQLException, ClassNotFoundException{
+ return getProvider().getConnection();
+ }
+ public static VirtuosoWeightedProvider getProvider()
+ throws ClassNotFoundException, SQLException {
+ if (provider == null) {
+ initProvider();
+ }
+ return provider;
+ }
+
+ private static void initProvider() throws ClassNotFoundException,
+ SQLException {
+ if (SKIP) {
+ log.warn("Skipping tests.");
+ return;
+ }
+ String host = System.getProperty("virtuoso.host");
+ String port = System.getProperty("virtuoso.port");
+ jdbcUser = System.getProperty("virtuoso.user");
+ jdbcPassword = System.getProperty("virtuoso.password");
+ jdbcDriver = System.getProperty("virtuoso.driver");
+ if (host == null) {
+ host = "localhost";
+ log.info("Missing param 'host', setting to default: {}", host);
+ }
+ if (port == null) {
+ port = "1111";
+ log.info("Missing param 'port', setting to default: {}", port);
+ }
+ if (jdbcUser == null) {
+ jdbcUser = "dba";
+ log.info("Missing param 'user', setting to default: {}", jdbcUser);
+ }
+ if (jdbcPassword == null) {
+ jdbcPassword = "dba";
+ log.info("Missing param 'password', setting to default: {}",
+ jdbcPassword);
+ }
+ if (jdbcDriver == null) {
+ jdbcDriver = "virtuoso.jdbc4.Driver";
+ log.info("Missing param 'password', setting to default: {}",
+ jdbcDriver);
+ }
+
+ StringBuilder cb = new StringBuilder();
+ cb.append("jdbc:virtuoso://");
+ cb.append(host);
+ cb.append(":");
+ cb.append(port).append("/CHARSET=UTF-8");
+ jdbcConnectionString = cb.toString();
+// Class.forName(VirtuosoWeightedProvider.DRIVER);
+ log.info("Create provider");
+// connection = (VirtuosoConnection) DriverManager.getConnection(
+// jdbcConnectionString, jdbcUser, jdbcPassword);
+ provider = new VirtuosoWeightedProvider(jdbcConnectionString, jdbcUser, jdbcPassword);
+ log.debug("Connection URL: {}", jdbcConnectionString);
+ log.debug("Connection user: {}", jdbcUser);
+ }
+
+ public static void stamp(ResultSet rs) {
+ try {
+ ResultSetMetaData rsmd;
+
+ StringBuilder output = new StringBuilder();
+ output.append(System.getProperty("line.separator"));
+ output.append("------------------------------");
+ output.append(System.getProperty("line.separator"));
+ rsmd = rs.getMetaData();
+
+ while (rs.next()) {
+ for (int i = 1; i <= rsmd.getColumnCount(); i++) {
+ String s = rs.getString(i);
+ Object o = ((VirtuosoResultSet) rs).getObject(i);
+ if (o instanceof VirtuosoExtendedString) {
+ // In case is IRI
+ VirtuosoExtendedString vs = (VirtuosoExtendedString) o;
+ if (vs.iriType == VirtuosoExtendedString.IRI
+ && (vs.strType & 0x01) == 0x01) {
+ output.append(" <" + vs.str + "> ");
+ log.debug(" {} is IRI", vs.str);
+ } else if (vs.iriType == VirtuosoExtendedString.BNODE) {
+ log.debug(" {} is BNODE", vs.str);
+ output.append(" <" + vs.str + "> ");
+ } else {
+ // In case is untyped literal
+ log.debug(" {} is an untyped literal", vs.str);
+ output.append(vs.str);
+ }
+ } else if (o instanceof VirtuosoRdfBox) {
+ // In case is typed literal
+ VirtuosoRdfBox rb = (VirtuosoRdfBox) o;
+ output.append(rb.rb_box + " lang=" + rb.getLang()
+ + " type=" + rb.getType());
+ log.debug(" {} is an typed literal", rb.rb_box);
+
+ } else if (rs.wasNull()) {
+ log.debug(" NULL ");
+ output.append("NULL");
+ } else {
+ // Is simple untyped string
+ output.append(s);
+ }
+
+ }
+ output.append("\n");
+ }
+
+ output.append(System.getProperty("line.separator"));
+ output.append("------------------------------");
+ output.append(System.getProperty("line.separator"));
+ log.info(output.toString());
+ } catch (Exception e) {
+ log.error("ERROR", e);
+ }
+ }
+
+ public static void stamp(Triple next) {
+ log.info("> TRIPLE : "+next.getSubject().toString() + " "
+ + next.getPredicate().toString() + " "
+ + next.getObject().toString());
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ThreadSafetyTest.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ThreadSafetyTest.java b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ThreadSafetyTest.java
new file mode 100644
index 0000000..fb418ab
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ThreadSafetyTest.java
@@ -0,0 +1,341 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.impl.TripleImpl;
+import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoMGraph;
+import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ *
+ * Credit: This code is largely cloned by the thread safe test in
+ * {@see org.apache.clerezza.rdf.sesame.storage.ThreadSafetyTest}
+ *
+ * @author enridaga
+ *
+ */
+public class ThreadSafetyTest {
+
+ private ExecutorService executor;
+ private VirtuosoMGraph mgraph;
+ private DataAccess da = null;
+ static Logger log = LoggerFactory.getLogger(ThreadSafetyTest.class);
+
+ @BeforeClass
+ public static void assume(){
+ org.junit.Assume.assumeTrue(!TestUtils.SKIP);
+ }
+
+ @Before
+ public void setUp() throws Exception {
+
+ da = TestUtils.getProvider().createDataAccess();
+ da.clearGraph("ThreadSafetyTest");
+ mgraph = new VirtuosoMGraph("ThreadSafetyTest",
+ da);
+ mgraph.clear();
+ executor = Executors.newCachedThreadPool();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ try {
+ executor.shutdown();
+ if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
+ fail("Timeout while waiting for termination");
+ }
+ } finally {
+ mgraph.clear();
+ mgraph = null;
+ da.close();
+ da = null;
+ }
+ }
+
+ @Test
+ public void testProduceFirstAndThenConsume() throws Exception {
+ log.info("testProduceFirstAndThenConsume()");
+ // Produce first...
+ Future<Result> fp = executor.submit(new Producer("A", 100));
+ fp.get().assertResult();
+
+ // ...and then consume
+ Future<Result> fc = executor.submit(new Consumer("A", 100));
+ fc.get().assertResult();
+ Iterator<Triple> it = mgraph.iterator();
+ while (it.hasNext()) {
+ TestUtils.stamp(it.next());
+ }
+ // test graph size
+ assertEquals(0, mgraph.size());
+ }
+
+ @Test
+ public void testProduceAndConsumeSingle() throws Exception {
+ log.info("testProduceAndConsumeSingle()");
+ List<Task> tasks = Arrays.asList(
+ new Consumer("A", 100), new Producer("A", 100));
+ List<Future<Result>> futures = executor.invokeAll(tasks);
+ for (Future<Result> future : futures) {
+ future.get().assertResult();
+ }
+ assertEquals(0, mgraph.size());
+ }
+
+ @Test
+ public void testProduceAndConsumeMultiple() throws Exception {
+ log.info("testProduceAndConsumeMultiple()");
+ List<Task> tasks = Arrays.asList(
+ new Consumer("A", 100), new Producer("A", 100),
+ new Consumer("B", 100), new Producer("B", 100),
+ new Consumer("C", 100), new Producer("C", 100),
+ new Consumer("D", 100), new Producer("D", 100));
+ List<Future<Result>> futures = executor.invokeAll(tasks);
+ for (Future<Result> future : futures) {
+ future.get().assertResult();
+ }
+ assertEquals(0, mgraph.size());
+ }
+
+ @Test
+ public void testProduceAndConsumeMixed() throws Exception {
+ log.info("testProduceAndConsumeMixed()");
+ List<? extends Task> tasks = Arrays.asList(
+ new Consumer("A", 110), new Consumer("A", 170),
+ new Consumer("B", 100), new Consumer("B", 500),
+ new Consumer("C", 230), new Consumer("C", 230),
+ new Consumer("D", 540), new Consumer("D", 10),
+ new Producer("D", 50), new Producer("D", 500),
+ new Producer("C", 400), new Producer("C", 60),
+ new Producer("B", 300), new Producer("B", 300),
+ new Producer("A", 200), new Producer("A", 80));
+ List<Future<Result>> futures = executor.invokeAll(tasks);
+ for (Future<Result> future : futures) {
+ future.get().assertResult();
+ }
+ assertEquals(0, mgraph.size());
+ }
+ /**
+ * The <code>Task</code> specifies a <code>Callable</code> whoes execution
+ * results in an <code>Integer</code>.
+ */
+ private abstract class Task implements Callable<Result> {
+
+ protected final String collectionName;
+ protected final UriRef subject;
+ protected final UriRef predicate;
+ protected final int numElements;
+
+ /**
+ * Creates a new <code>Task</code>.
+ *
+ * @param collectionName
+ * Name of the task's collection.
+ * @param numElements
+ * The number of elements to process.
+ */
+ protected Task(String collectionName, int numElements) {
+ if (collectionName == null) {
+ throw new IllegalArgumentException("Invalid name: null");
+ } else if (collectionName.length() <= 0) {
+ throw new IllegalArgumentException("Invalid name: '"
+ + collectionName + "'");
+ } else if (numElements < 0) {
+ throw new IllegalArgumentException("Invalid numElements: "
+ + numElements);
+ }
+ this.numElements = numElements;
+ this.collectionName = collectionName;
+ subject = new UriRef("http://example.org/" + "collection/"
+ + collectionName);
+ predicate = new UriRef("http://example.org/ontology/contains");
+ }
+
+ /**
+ * Causes the currently executing thread object to temporarily pause and
+ * allow other threads to execute.
+ */
+ protected void yield() {
+ try {
+ Thread.sleep(5);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ /**
+ * This class represents a task that produces triples that are stored in the
+ * graph.
+ */
+ private class Producer extends Task {
+
+ /**
+ * Creates a new <code>Producer</code> task.
+ *
+ * @param collectionName
+ * Name of the task's collection.
+ * @param numElements
+ * The number of elements to produce.
+ */
+ public Producer(String collectionName, int numElements) {
+ super(collectionName, numElements);
+ }
+
+ @Override
+ public Result call() throws InterruptedException {
+ int counter = 0;
+ for (int elementName = 1; counter < numElements; elementName++) {
+ yield();
+ final Triple t = createTriple(elementName);
+ if (mgraph.add(t)) {
+ counter++;
+ yield();
+ } else {
+ System.out.println("WARNING: element " + t + "NOT created");
+ }
+ }
+ return new Result(collectionName, "Produced elements", numElements,
+ counter);
+ }
+
+ /**
+ * Creates a new collection element triple.
+ *
+ * @param value
+ * Value of the collection element.
+ * @return A new triple representing the collection element.
+ */
+ protected Triple createTriple(int value) {
+ final UriRef object = new UriRef("http://example.org/"
+ + collectionName + "/" + Integer.valueOf(value)
+ + Math.random());
+ return new TripleImpl(subject, predicate, object);
+ }
+ }
+
+ /**
+ * This class represents a task that produces triples that are stored in the
+ * graph.
+ */
+ private class Consumer extends Task {
+
+ /**
+ * Creates a new <code>Consumer</code> task.
+ *
+ * @param collectionName
+ * Name of the task's collection.
+ * @param numElements
+ * The number of elements to consume.
+ */
+ public Consumer(String collectionName, int numElements) {
+ super(collectionName, numElements);
+ }
+
+ /**
+ * Performs this task.
+ *
+ * @return the number of elements successfully added to the graph.
+ */
+ @Override
+ public Result call() throws InterruptedException {
+ int counter = 0;
+ while (counter < numElements) {
+ yield();
+
+ Triple triple = null;
+ mgraph.getLock().writeLock().lock();
+ try {
+ // System.out.println("synchonized");
+ Iterator<Triple> i = mgraph
+ .filter(subject, predicate, null);
+ if (i.hasNext()) {
+ triple = i.next();
+ }
+
+ if (triple != null && mgraph.remove(triple)) {
+ counter++;
+ }
+ } finally {
+ mgraph.getLock().writeLock().unlock();
+ }
+ }
+ return new Result(collectionName, "Consumed elements", numElements,
+ counter);
+ }
+ }
+
+ /**
+ * Task result that asserts the number of processed elements.
+ */
+ private class Result {
+
+ private final int expected;
+ private final int actual;
+ private final String msg;
+ private final String cn;
+
+ /**
+ * Creates a new task result that asserts the element count.
+ *
+ * @param cn
+ * Name of the affected collection.
+ * @param msg
+ * Assertion message to print.
+ * @param expected
+ * Expected number of processed elements.
+ * @param actual
+ * Actual number of processed elements.
+ */
+ public Result(String cn, String msg, int expected, int actual) {
+ this.expected = expected;
+ this.actual = actual;
+ this.msg = msg;
+ this.cn = cn;
+ }
+
+ /**
+ * Asserts this result.
+ */
+ public void assertResult() {
+ assertEquals("[" + cn + "] " + msg, expected, actual);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraphTest.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraphTest.java b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraphTest.java
new file mode 100644
index 0000000..2280a3f
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraphTest.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import org.apache.clerezza.rdf.core.Graph;
+import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoGraph;
+
+/**
+ * Tests the {@link VirtuosoGraph} implementation of {@link Graph}
+ *
+ * @author enridaga
+ *
+ */
+public class VirtuosoGraphTest {
+
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraphTest.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraphTest.java b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraphTest.java
new file mode 100644
index 0000000..0d7b1ec
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraphTest.java
@@ -0,0 +1,526 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Iterator;
+
+import org.apache.clerezza.rdf.core.BNode;
+import org.apache.clerezza.rdf.core.Graph;
+import org.apache.clerezza.rdf.core.Language;
+import org.apache.clerezza.rdf.core.NonLiteral;
+import org.apache.clerezza.rdf.core.PlainLiteral;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.TypedLiteral;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
+import org.apache.clerezza.rdf.core.impl.TypedLiteralImpl;
+import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoMGraph;
+import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import virtuoso.jdbc4.VirtuosoException;
+
+public class VirtuosoMGraphTest {
+ static VirtuosoMGraph mgraph = null;
+ static DataAccess da = null;
+ static final String TEST_GRAPH_NAME = "VirtuosoMGraphTest";
+
+ static Logger log = LoggerFactory.getLogger(VirtuosoMGraphTest.class);
+
+ @BeforeClass
+ public static void assume(){
+ org.junit.Assume.assumeTrue(!TestUtils.SKIP);
+ }
+
+ /**
+ * Clean before any test
+ *
+ * @throws ClassNotFoundException
+ * @throws SQLException
+ */
+ @Before
+ public void before() throws ClassNotFoundException, SQLException {
+
+ da = TestUtils.getProvider().createDataAccess();
+ mgraph = new VirtuosoMGraph(TEST_GRAPH_NAME, da);
+ mgraph.clear();
+ log.debug("Clearing graph <{}>", TEST_GRAPH_NAME);
+ }
+
+ final UriRef enridaga = new UriRef("enridaga");
+ final UriRef alexdma = new UriRef("alexdma");
+ final UriRef anuzzolese = new UriRef("anuzzolese");
+ final UriRef predicate = new UriRef("http://property/name");
+ final PlainLiteral object = new PlainLiteralImpl("Enrico Daga", new Language("it"));
+ final TypedLiteral objectTyped = new TypedLiteralImpl("Enrico Daga", new UriRef("http://www.w3.org/2001/XMLSchema#string"));
+ final TypedLiteral objectXml = new TypedLiteralImpl("<div>Enrico Daga</div>" ,
+ new UriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"));
+ final UriRef knows = new UriRef(TestUtils.FOAF_NS + "knows");
+
+ @Test
+ public void testAddSingle() {
+ log.info("testAddSingle()");
+ Triple triple = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return predicate;
+ }
+
+ @Override
+ public Resource getObject() {
+ return object;
+ }
+ };
+ boolean success = mgraph.add(triple);
+ assertTrue(success);
+ assertTrue(mgraph.size() == 1);
+ assertTrue(mgraph.filter(enridaga, predicate, object).hasNext());
+ assertTrue(mgraph.filter(enridaga, predicate, object).next().equals(triple));
+ }
+
+ @Test
+ public void testAddSingleTypedLiteral() {
+ log.info("testAddSingleTypedLiteral()");
+ Triple triple = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return predicate;
+ }
+
+ @Override
+ public Resource getObject() {
+ return objectTyped;
+ }
+ };
+ boolean success = mgraph.add(triple);
+ assertTrue(success);
+ assertTrue(mgraph.size() == 1);
+ assertTrue(mgraph.filter(enridaga, predicate, objectTyped).hasNext());
+ assertTrue(mgraph.filter(enridaga, predicate, objectTyped).next().equals(triple));
+ }
+
+ @Ignore
+ @Test
+ public void testAddSingleXMLLiteral() {
+ log.info("testAddSingleXMLLiteral()");
+ Triple triple = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return predicate;
+ }
+
+ @Override
+ public Resource getObject() {
+ return objectXml;
+ }
+ };
+ boolean success = mgraph.add(triple);
+ assertTrue(success);
+ assertTrue(mgraph.size() == 1);
+ Triple rt = mgraph.filter(enridaga, predicate, null).next();
+ log.info(" > s: {} ", rt.getSubject());
+ log.info(" > p: {} ", rt.getPredicate());
+ log.info(" > o: {} ", rt.getObject());
+ log.info(" > tl?: {} ", rt.getObject() instanceof TypedLiteral);
+ assertTrue(mgraph.filter(enridaga, predicate, objectXml).hasNext());
+ assertTrue(mgraph.filter(enridaga, predicate, objectXml).next().equals(triple));
+ }
+
+
+ @Test
+ public void testFilter() {
+ log.info("testFilter(); Test filter(s,p,o)");
+ // We use testAdd to prepare this
+ testAddSingle();
+
+ Iterator<Triple> its = mgraph.filter(null, null, null);
+ while (its.hasNext()) {
+ Triple t = its.next();
+ log.info("Found --- triple: {}", t);
+ log.info("Found --- s: {} {}", t.getSubject(), t.getSubject().getClass());
+ log.info("Found --- p: {} {}", t.getPredicate(), t.getPredicate().getClass());
+ log.info("Found --- o: {} {}", t.getObject(), t.getObject().getClass());
+ assertEquals(t.getSubject(), enridaga);
+ assertEquals(t.getPredicate(), predicate);
+ assertEquals(t.getObject(), object);
+ }
+
+ Iterator<Triple> it = mgraph.filter(enridaga, predicate, object);
+ boolean found = false;
+ while (it.hasNext()) {
+ found = true;
+ Triple t = it.next();
+ log.debug("Found matching triple: {}", t);
+ assertEquals(t.getSubject(), enridaga);
+ assertEquals(t.getPredicate(), predicate);
+ assertEquals(t.getObject(), object);
+ }
+ assertTrue(found);
+ }
+
+ @Test
+ public void testFilterSubject() {
+ log.info("testFilterSubject(); Test filter(s,null,null)");
+ // We use testAdd to prepare this
+ testAddSingle();
+ Iterator<Triple> it = mgraph.filter(enridaga, null, null);
+ boolean found = false;
+ while (it.hasNext()) {
+ found = true;
+ Triple t = it.next();
+ if (log.isDebugEnabled()) {
+ log.debug("Found matching triple: {}", t);
+ TestUtils.stamp(t);
+ }
+ assertEquals(t.getSubject(), enridaga);
+ }
+ assertTrue(found);
+ }
+
+
+ @Test
+ public void testFilterSubjectBnode() throws VirtuosoException, SQLException, ClassNotFoundException {
+ log.info("testFilterSubjectBnode(); Test filter(s,null,null)");
+ final BNode bn = new BNode();
+ // We use testAdd to prepare this
+ Triple triple = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return bn;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return predicate;
+ }
+
+ @Override
+ public Resource getObject() {
+ return new BNode();
+ }
+ };
+
+ boolean success = mgraph.add(triple);
+ assertTrue(success);
+ Iterator<Triple> it = mgraph.filter(bn, predicate, null);
+ boolean found = false;
+ Triple t = null; // we will use it to make a further query
+ while (it.hasNext()) {
+ found = true;
+ t = it.next();
+ if (log.isDebugEnabled()) {
+ log.debug("Found matching triple: {}", t);
+ TestUtils.stamp(t);
+ }
+ assertEquals(t.getPredicate(), predicate);
+ }
+ assertTrue(found);
+
+ assertNotNull(t);
+
+ log.info("{}",t.getSubject());
+ it = mgraph.filter(t.getSubject(), predicate, t.getObject());
+ found = false;
+ while (it.hasNext()) {
+ found = true;
+ t = it.next();
+ if (log.isDebugEnabled()) {
+ log.debug("Found matching triple: {}", t);
+ TestUtils.stamp(t);
+ }
+ assertEquals(t.getPredicate(), predicate);
+ }
+ assertTrue(found);
+ }
+
+ @Test
+ public void testFilterPredicate() {
+ log.info("testFilterPredicate(); Test filter(null,p,null)");
+ // We use testAdd to prepare this
+ testAddSingle();
+ Iterator<Triple> it = mgraph.filter(null, predicate, null);
+ boolean found = false;
+ while (it.hasNext()) {
+ found = true;
+ Triple t = it.next();
+ if (log.isDebugEnabled()) {
+ log.debug("Found matching triple: {}", t);
+ TestUtils.stamp(t);
+ }
+ assertEquals(t.getPredicate(), predicate);
+ }
+ assertTrue(found);
+ }
+
+ @Test
+ public void testFilterObject() {
+ log.info("testFilterObject(); Test filter(null,null,o)");
+ // We use testAdd to prepare this
+ testAddSingle();
+ Iterator<Triple> it = mgraph.filter(null, null, object);
+ boolean found = false;
+ while (it.hasNext()) {
+ found = true;
+ Triple t = it.next();
+ if (log.isDebugEnabled()) {
+ log.debug("Found matching triple: {}", t);
+ TestUtils.stamp(t);
+ }
+ assertEquals(t.getObject(), object);
+ }
+ assertTrue(found);
+ }
+
+ @Test
+ public void testFilterObjectTyped() {
+ log.info("testFilterObjectTyped(); Test filter(null,null,o)");
+ // We use testAdd to prepare this
+ testAddSingleTypedLiteral();
+ Iterator<Triple> it = mgraph.filter(null, null, objectTyped);
+ boolean found = false;
+ while (it.hasNext()) {
+ found = true;
+ Triple t = it.next();
+ if (log.isDebugEnabled()) {
+ log.debug("Found matching triple: {}", t);
+ TestUtils.stamp(t);
+ }
+ assertEquals(t.getObject(), objectTyped);
+ }
+ assertTrue(found);
+ }
+
+ @Ignore
+ @Test
+ public void testFilterObjectXml() {
+ log.info("testFilterObjectXml(); Test filter(null,null,o)");
+ // We use testAdd to prepare this
+ testAddSingleXMLLiteral();
+ Iterator<Triple> it = mgraph.filter(null, null, objectXml);
+ boolean found = false;
+ while (it.hasNext()) {
+ found = true;
+ Triple t = it.next();
+ if (log.isDebugEnabled()) {
+ log.debug("Found matching triple: {}", t);
+ TestUtils.stamp(t);
+ }
+ assertEquals(t.getObject(), objectXml);
+ }
+ assertTrue(found);
+ }
+
+ @Test
+ public void testSize() {
+ log.info("testSize()");
+ // We use testAdd to prepare this
+ testAddSingle();
+ // Should be 1 at this time
+ log.debug("How many triples are in graph <{}>? {}", TEST_GRAPH_NAME,
+ mgraph.size());
+ assertTrue(mgraph.size() > 0);
+ }
+
+ @Test
+ public void testIncreaseSize() {
+ log.info("testIncreaseSize()");
+ int beforeSize = mgraph.size();
+ Triple t = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return knows;
+ }
+
+ @Override
+ public Resource getObject() {
+ return alexdma;
+ }
+ };
+ assertTrue(mgraph.add(t));
+ int afterSize = mgraph.size();
+ assertEquals(beforeSize + 1, afterSize);
+ }
+
+ @Test
+ public void testAddRemoveSize() {
+ log.info("testAddRemoveSize()");
+ int beforeSize = mgraph.size();
+ Triple t = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return knows;
+ }
+
+ @Override
+ public Resource getObject() {
+ return alexdma;
+ }
+ };
+ assertTrue(mgraph.add(t));
+ assertTrue(mgraph.remove(t));
+ int afterSize = mgraph.size();
+ assertEquals(beforeSize, afterSize);
+ }
+
+ @Test
+ public void testGetGraphReadOnly() {
+ log.info("testGetGraphReadOnly()");
+ Graph g = mgraph.getGraph();
+ Triple t = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return knows;
+ }
+
+ @Override
+ public Resource getObject() {
+ return anuzzolese;
+ }
+ };
+ // This should not be allowed
+ boolean success;
+ try {
+ success = g.add(t);
+ } catch (UnsupportedOperationException e) {
+ success = false;
+ }
+ assertFalse(success);
+ }
+
+ @Test
+ public void testContains() {
+ log.info("testContains()");
+ Triple t = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return knows;
+ }
+
+ @Override
+ public Resource getObject() {
+ return anuzzolese;
+ }
+ };
+ boolean addWorks = mgraph.add(t);
+ assertTrue(addWorks);
+
+ // This second triple is equivalent
+ Triple t2 = new Triple() {
+
+ @Override
+ public NonLiteral getSubject() {
+ return enridaga;
+ }
+
+ @Override
+ public UriRef getPredicate() {
+ return knows;
+ }
+
+ @Override
+ public Resource getObject() {
+ return anuzzolese;
+ }
+ };
+ Iterator<Triple> it = mgraph.filter(t2.getSubject(), t2.getPredicate(),
+ t2.getObject());
+ while (it.hasNext()) {
+ if (log.isDebugEnabled()) {
+ log.debug("Found matching triple");
+ TestUtils.stamp(it.next());
+ }else{
+ it.next();
+ }
+ }
+ assertTrue(mgraph.contains(t2));
+ // Also the related read-only graph
+ assertTrue(mgraph.getGraph().contains(t2));
+ }
+
+ @After
+ public void clear() throws VirtuosoException, ClassNotFoundException,
+ SQLException {
+ log.info("Clearing graph <{}> of size {}", TEST_GRAPH_NAME,
+ mgraph.size());
+ log.debug("Removing graph <{}>", TEST_GRAPH_NAME);
+ da.close();
+ da = null;
+ mgraph = null;
+ Statement st = TestUtils.getConnection().createStatement();
+ st.execute("SPARQL CLEAR GRAPH <" + TEST_GRAPH_NAME + ">");
+ st.close();
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccessTest.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccessTest.java b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccessTest.java
new file mode 100644
index 0000000..3ca89f0
--- /dev/null
+++ b/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccessTest.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage.access;
+
+import java.sql.SQLException;
+
+import org.apache.clerezza.rdf.core.BNode;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
+import org.apache.clerezza.rdf.core.impl.TripleImpl;
+import org.apache.clerezza.rdf.virtuoso.storage.TestUtils;
+import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class DataAccessTest {
+
+ private static DataAccess da = null;
+
+ static Logger log = LoggerFactory.getLogger(DataAccessTest.class);
+
+ @BeforeClass
+ public static void assume(){
+ org.junit.Assume.assumeTrue(!TestUtils.SKIP);
+ }
+
+ @Before
+ public void before() throws ClassNotFoundException, SQLException {
+ da = TestUtils.getProvider().createDataAccess();
+ da.clearGraph( "urn:x-test:DataAccessTest" );
+ }
+
+ @After
+ public void after() {
+ da.clearGraph( "urn:x-test:DataAccessTest" );
+ da.close();
+ da = null;
+ }
+
+ private void testTriple(Triple t){
+ String g = "urn:x-test:DataAccessTest";
+ da.insertQuad(g, t);
+
+ Assert.assertTrue(da.filter(g, null, null, null).hasNext());
+
+ Assert.assertTrue(da.filter(g, t.getSubject(), null, null).hasNext());
+ Assert.assertTrue(da.filter(g, null, t.getPredicate(), null).hasNext());
+ Assert.assertTrue(da.filter(g, null, null, t.getObject()).hasNext());
+
+ Assert.assertTrue(da.filter(g, null, t.getPredicate(), t.getObject()).hasNext());
+ Assert.assertTrue(da.filter(g, t.getSubject(), null, t.getObject()).hasNext());
+ Assert.assertTrue(da.filter(g, t.getSubject(), t.getPredicate(), null).hasNext());
+ Assert.assertTrue(da.filter(g, t.getSubject(), null, t.getObject()).hasNext());
+
+ Assert.assertTrue(da.filter(g, t.getSubject(), t.getPredicate(), t.getObject()).hasNext());
+
+ Assert.assertTrue(da.size(g) == 1);
+
+ da.deleteQuad(g, t);
+
+ Assert.assertTrue(da.size(g) == 0);
+ }
+
+ @Test
+ public void test_Uri_Uri_Uri(){
+ Triple t = new TripleImpl(new UriRef("urn:subject"), new UriRef("urn:predicate"), new UriRef("urn:object"));
+ testTriple(t);
+ }
+
+ @Test
+ public void test_Uri_Uri_PlainLiteral(){
+ Triple t = new TripleImpl(new UriRef("urn:subject"), new UriRef("urn:predicate"), new PlainLiteralImpl("Lorem Ipsum"));
+ testTriple(t);
+ }
+
+ @Test
+ public void test_Uri_Uri_BNode(){
+ Triple t = new TripleImpl(new UriRef("urn:subject"), new UriRef("urn:predicate"), new BNode());
+ testTriple(t);
+ }
+
+ @Test
+ public void testRenew(){
+ int i = 100;
+ while(i>0){
+ test_Uri_Uri_Uri();
+ test_Uri_Uri_PlainLiteral();
+ i--;
+ }
+ da.renew();
+ i = 100;
+ while(i>0){
+ test_Uri_Uri_Uri();
+ test_Uri_Uri_PlainLiteral();
+ i--;
+ }
+ da.renew();
+ i = 100;
+ while(i>0){
+ test_Uri_Uri_Uri();
+ test_Uri_Uri_PlainLiteral();
+ i--;
+ }
+ }
+
+}
[5/5] git commit: CLEREZZA-813 Moved the two virtuoso modules to the
clerezza root folder. Added to the main pom.xml
Posted by en...@apache.org.
CLEREZZA-813 Moved the two virtuoso modules to the clerezza root folder. Added to the main pom.xml
Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/bb87e83f
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/bb87e83f
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/bb87e83f
Branch: refs/heads/master
Commit: bb87e83fedb6843be6dd2c31c4a51e47707651ca
Parents: b8776a5
Author: enridaga <en...@apache.org>
Authored: Sat Mar 29 18:05:14 2014 +0000
Committer: enridaga <en...@apache.org>
Committed: Sat Mar 29 18:05:14 2014 +0000
----------------------------------------------------------------------
clerezza-virtuoso/README.md | 54 --
clerezza-virtuoso/ext.virtuoso.jdbc/pom.xml | 143 ---
.../repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar | Bin 217690 -> 0 bytes
.../repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom | 27 -
.../repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar | Bin 214811 -> 0 bytes
.../repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom | 27 -
.../virtuoso/virtjdbc/maven-metadata-local.xml | 30 -
.../rdf.virtuoso.storage/README.md | 2 -
clerezza-virtuoso/rdf.virtuoso.storage/pom.xml | 271 ------
.../rdf/virtuoso/storage/VirtuosoBNode.java | 45 -
.../rdf/virtuoso/storage/VirtuosoGraph.java | 94 --
.../rdf/virtuoso/storage/VirtuosoMGraph.java | 191 ----
.../rdf/virtuoso/storage/access/DataAccess.java | 949 -------------------
.../access/VirtuosoWeightedProvider.java | 937 ------------------
....clerezza.rdf.core.access.WeightedTcProvider | 1 -
.../src/main/resources/log4j.properties | 5 -
.../src/test/java/.DS_Store | Bin 6148 -> 0 bytes
.../clerezza/rdf/virtuoso/storage/.DS_Store | Bin 6148 -> 0 bytes
.../rdf/virtuoso/storage/ConnectionTest.java | 138 ---
.../rdf/virtuoso/storage/RdfIOTest.java | 352 -------
.../rdf/virtuoso/storage/TestUtils.java | 185 ----
.../rdf/virtuoso/storage/ThreadSafetyTest.java | 341 -------
.../rdf/virtuoso/storage/VirtuosoGraphTest.java | 32 -
.../virtuoso/storage/VirtuosoMGraphTest.java | 526 ----------
.../virtuoso/storage/access/DataAccessTest.java | 129 ---
.../access/VirtuosoWeightedProviderTest.java | 310 ------
.../src/test/resources/log4j.properties | 6 -
ext.virtuoso.jdbc/pom.xml | 143 +++
.../repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar | Bin 0 -> 217690 bytes
.../repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom | 27 +
.../repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar | Bin 0 -> 214811 bytes
.../repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom | 27 +
.../virtuoso/virtjdbc/maven-metadata-local.xml | 30 +
pom.xml | 4 +
rdf.virtuoso.storage/README.md | 49 +
rdf.virtuoso.storage/pom.xml | 271 ++++++
.../rdf/virtuoso/storage/VirtuosoBNode.java | 45 +
.../rdf/virtuoso/storage/VirtuosoGraph.java | 94 ++
.../rdf/virtuoso/storage/VirtuosoMGraph.java | 191 ++++
.../rdf/virtuoso/storage/access/DataAccess.java | 949 +++++++++++++++++++
.../access/VirtuosoWeightedProvider.java | 937 ++++++++++++++++++
....clerezza.rdf.core.access.WeightedTcProvider | 1 +
.../src/main/resources/log4j.properties | 5 +
.../rdf/virtuoso/storage/ConnectionTest.java | 138 +++
.../rdf/virtuoso/storage/RdfIOTest.java | 352 +++++++
.../rdf/virtuoso/storage/TestUtils.java | 185 ++++
.../rdf/virtuoso/storage/ThreadSafetyTest.java | 341 +++++++
.../rdf/virtuoso/storage/VirtuosoGraphTest.java | 32 +
.../virtuoso/storage/VirtuosoMGraphTest.java | 526 ++++++++++
.../virtuoso/storage/access/DataAccessTest.java | 129 +++
.../access/VirtuosoWeightedProviderTest.java | 310 ++++++
.../src/test/resources/log4j.properties | 6 +
52 files changed, 4792 insertions(+), 4795 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/README.md
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/README.md b/clerezza-virtuoso/README.md
deleted file mode 100644
index 03a501c..0000000
--- a/clerezza-virtuoso/README.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Virtuoso/Clerezza storage adapter
-
-This is an implementation of the storage API of Clerezza[1] to use Virtuoso as storage.
-
-
-## Build and Install
-To build this project you need Maven.
-
-### Simple build
-From the main folder:
-
- $ mvn clean install
-
-Results will be 2 bundles:
-
-* ext.virtuoso.jdbc : contains JDBC drivers form Virtuoso
-* rdf.virtuoso.storage : contains the implementation of the clerezza storage API for Virtuoso
-
-Bundles are in the /target folders:
-
-* ext.virtuoso.jdbc/target/ext.virtuoso.jdbc-<version>.jar
-* rdf.virtuoso.storage/target/rdf.virtuoso.storage-<version>.jar
-
-### Build forcing tests
-You must have a Virtuoso running server to do tests.
-To activate tests, you must execute maven with the virtuoso-do-tests profile, for example:
-
- $ mvn test -Pvirtuoso-do-tests
-
-By default, the tests will use the parameters configured in the pom.xml. Change the parameters' values to the ones that fit your installation of Virtuoso.
-
-You can configure the following parameters:
-
-* virtuoso.test (default is null, sets to true if you activate the 'virtuoso-do-tests' profile)
-* virtuoso.driver (default is 'virtuoso.jdbc4.Driver')
-* virtuoso.host (default is 'localhost')
-* virtuoso.port (default is '1111')
-* virtuoso.user (default is 'dba')
-* virtuoso.password (default is 'dba')
-
-To override them from cli, you can also do the following:
-
- $ mvn test -Pvirtuoso-do-tests -DargLine="-Dvirtuoso.password=mypassword -Dvirtuoso.port=1234"
-
-
-### Hot deploy on a Clerezza or Stanbol[2] running servers
-
-To deploy the bundles in a running Sling instance you can do:
-
- $ mvn install -PinstallBundle -Dsling.url=http://localhost:8080/system/console (change this to be the actual server admin interface)
-
-
-* [1] http://incubator.apache.org/clerezza/
-* [2] http://incubator.apache.org/stanbol/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/ext.virtuoso.jdbc/pom.xml
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/ext.virtuoso.jdbc/pom.xml b/clerezza-virtuoso/ext.virtuoso.jdbc/pom.xml
deleted file mode 100644
index bea990e..0000000
--- a/clerezza-virtuoso/ext.virtuoso.jdbc/pom.xml
+++ /dev/null
@@ -1,143 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
---><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.apache.clerezza</groupId>
- <artifactId>clerezza</artifactId>
- <version>0.5-SNAPSHOT</version>
- <relativePath>../../parent</relativePath>
- </parent>
- <artifactId>ext.virtuoso.jdbc</artifactId>
- <name>Clerezza/Virtuoso Ext - Virtuoso JDBC OSGi Bundle</name>
- <description>Virtuoso JDBC</description>
- <version>0.3-SNAPSHOT</version>
- <repositories>
- <repository>
- <releases>
- <updatePolicy>always</updatePolicy>
- </releases>
- <snapshots>
- <updatePolicy>always</updatePolicy>
- </snapshots>
- <id>virtuoso-jdbc4-embedded</id>
- <url>file://localhost/${project.basedir}/src/main/resources/maven/repo</url>
- </repository>
- </repositories>
- <dependencies>
- <dependency>
- <groupId>virtuoso</groupId>
- <artifactId>virtjdbc</artifactId>
- <type>jar</type>
- <version>4.1</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
- <Embed-Dependency>*;scope=compile;artifactId=!slf4j-api</Embed-Dependency>
- <!-- Embed-Transitive>true</Embed-Transitive -->
- <!-- Import-Package> </Import-Package -->
- <Export-Package>
- openlink.util.*,
- virtuoso.javax.*,
- virtuoso.jdbc4.*,
- virtuoso.sql.*
- </Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- <pluginManagement>
- <plugins>
- <!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>
- org.apache.felix
- </groupId>
- <artifactId>
- maven-scr-plugin
- </artifactId>
- <versionRange>
- [1.7.0,)
- </versionRange>
- <goals>
- <goal>scr</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore></ignore>
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
- <packaging>bundle</packaging>
- <profiles>
- <profile>
- <!-- This profile allows for installing/updating a bundle in a running
- Sling instance right after building it. Example: mvn clean install -P installBundle
- -Dsling.url=http://localhost:8080/system/console Or, to make it faster without
- cleaning up or running tests: mvn -o install -DskipTests -P installBundle
- -Dsling.url=http://localhost:8080/system/console -->
- <id>installBundle</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.sling</groupId>
- <artifactId>maven-sling-plugin</artifactId>
- <executions>
- <execution>
- <id>install-bundle</id>
- <goals>
- <goal>install</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar b/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar
deleted file mode 100644
index b207f0c..0000000
Binary files a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar and /dev/null differ
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom b/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom
deleted file mode 100644
index 02fa48e..0000000
--- a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
---><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <modelVersion>4.0.0</modelVersion>
- <groupId>virtuoso</groupId>
- <artifactId>virtjdbc</artifactId>
- <version>4.0</version>
- <description>POM was created from install:install-file</description>
-</project>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar b/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar
deleted file mode 100755
index 1c6ccec..0000000
Binary files a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar and /dev/null differ
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom b/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom
deleted file mode 100644
index 87605c7..0000000
--- a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
---><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <modelVersion>4.0.0</modelVersion>
- <groupId>virtuoso</groupId>
- <artifactId>virtjdbc</artifactId>
- <version>4.1</version>
- <description>POM was created from install:install-file</description>
-</project>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/maven-metadata-local.xml
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/maven-metadata-local.xml b/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/maven-metadata-local.xml
deleted file mode 100644
index a0d93d6..0000000
--- a/clerezza-virtuoso/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/maven-metadata-local.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
---><metadata>
- <groupId>virtuoso</groupId>
- <artifactId>virtjdbc</artifactId>
- <versioning>
- <release>4.1</release>
- <versions>
- <version>4.1</version>
- <version>4.0</version>
- </versions>
- </versioning>
-</metadata>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/README.md
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/README.md b/clerezza-virtuoso/rdf.virtuoso.storage/README.md
deleted file mode 100644
index 965d494..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-# Virtuoso Storage bindings for Clerezza
-
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/pom.xml
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/pom.xml b/clerezza-virtuoso/rdf.virtuoso.storage/pom.xml
deleted file mode 100644
index 1b1d668..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/pom.xml
+++ /dev/null
@@ -1,271 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-
---><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <artifactId>clerezza</artifactId>
- <groupId>org.apache.clerezza</groupId>
- <version>0.5-SNAPSHOT</version>
- <relativePath>../../parent</relativePath>
- </parent>
- <artifactId>rdf.virtuoso.storage</artifactId>
- <name>Clerezza - SCB Virtuoso storage provider</name>
- <description>A virtuoso based storage provider</description>
- <packaging>bundle</packaging>
- <version>0.3-SNAPSHOT</version>
-
- <dependencies>
- <!-- CLEREZZA -->
- <dependency>
- <groupId>org.apache.clerezza</groupId>
- <artifactId>rdf.core</artifactId>
- <version>0.14-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.wymiwyg</groupId>
- <artifactId>wymiwyg-commons-core</artifactId>
- </dependency>
- <!-- VIRTUOSO Dependencies -->
- <dependency>
- <groupId>clerezza-virtuoso</groupId>
- <artifactId>ext.virtuoso.jdbc</artifactId>
- <version>0.3-SNAPSHOT</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- OSGI -->
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.scr.annotations</artifactId>
- </dependency>
-
- <!-- LOGGING -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <!-- TEST (generic) -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
-<!-- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <scope>test</scope>
- <version></version>
- </dependency>
--->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.clerezza</groupId>
- <artifactId>platform.config</artifactId>
- <version>0.3-incubating</version>
- <type>bundle</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.clerezza</groupId>
- <artifactId>rdf.jena.parser</artifactId>
- <version>0.11</version>
- <type>bundle</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.hp.hpl.jena</groupId>
- <artifactId>jena</artifactId>
- <version>2.6.4</version>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.clerezza</groupId>
- <artifactId>rdf.jena.facade</artifactId>
- <version>0.13</version>
- <type>bundle</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.clerezza</groupId>
- <artifactId>rdf.jena.commons</artifactId>
- <version>0.6</version>
- <type>bundle</type>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <profiles>
- <profile>
- <id>virtuoso-do-tests</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
- <properties>
- <virtuoso.test>true</virtuoso.test>
- </properties>
- </profile>
- </profiles>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <executions>
- <execution>
- <id>default-test</id>
- <phase>test</phase>
- <goals>
- <goal>test</goal>
- </goals>
- <configuration>
- <systemPropertyVariables>
- <virtuoso.test>${virtuoso.test}</virtuoso.test>
- <virtuoso.driver>virtuoso.jdbc4.Driver</virtuoso.driver>
- <virtuoso.host>localhost</virtuoso.host>
- <virtuoso.port>1111</virtuoso.port>
- <virtuoso.user>dba</virtuoso.user>
- <virtuoso.password>dba</virtuoso.password>
- </systemPropertyVariables>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-scr-plugin</artifactId>
- <executions>
- <execution>
- <id>generate-scr-scrdescriptor</id>
- <goals>
- <goal>scr</goal>
- </goals>
- </execution>
- </executions>
- <!-- see http://felix.apache.org/site/apache-felix-scr-plugin-faq.html#ApacheFelixSCRPluginFAQ-NoClassDefFoundErrorduringbuild -->
- <dependencies>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <version>1.6.1</version>
- </dependency>
- </dependencies>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Include-Resource>
- src/main/resources,
- target/scr-plugin-generated
- </Include-Resource>
- <Service-Component>
- OSGI-INF/serviceComponents.xml
- </Service-Component>
- <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- <pluginManagement>
- <plugins>
-
- <!-- plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
- <Embed-Dependency>*;scope=compile|runtime;artifactId=!slf4j-api</Embed-Dependency>
- <Import-Package>*</Import-Package>
- <Export-Package>
- rdf.virtuoso.storage.*
- </Export-Package>
- </instructions>
- </configuration>
- </plugin -->
-
- <!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>
- org.apache.felix
- </groupId>
- <artifactId>
- maven-scr-plugin
- </artifactId>
- <versionRange>
- [1.7.0,)
- </versionRange>
- <goals>
- <goal>scr</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore></ignore>
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
-</project>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoBNode.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoBNode.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoBNode.java
deleted file mode 100644
index e8cc46f..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoBNode.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import org.apache.clerezza.rdf.core.BNode;
-
-public class VirtuosoBNode extends BNode {
- private String skolemId;
- public VirtuosoBNode(String skolemId) {
- this.skolemId = skolemId;
- }
-
- public String getSkolemId(){
- return skolemId;
- }
-
- public String asSkolemIri(){
- return new StringBuilder().append('<').append(skolemId).append('>').toString();
- }
-
- public String toString(){
- return skolemId;
- }
-
- @Override
- public boolean equals(Object obj) {
- return (obj instanceof VirtuosoBNode) && (obj.toString().equals(toString()));
- }
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraph.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraph.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraph.java
deleted file mode 100644
index 2516fdc..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraph.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import java.util.Collection;
-
-import org.apache.clerezza.rdf.core.Graph;
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/**
- * This is a read-only version of {@link VirtuosoMGraph}
- * @author enridaga
- *
- */
-public class VirtuosoGraph extends VirtuosoMGraph implements Graph{
-
- /**
- * Logger
- */
- protected Logger logger = LoggerFactory
- .getLogger(VirtuosoGraph.class);
-
- public VirtuosoGraph(String name, DataAccess dataAccess) {
- super(name, dataAccess);
- }
-
- @Override
- public synchronized boolean add(Triple e) {
- logger.warn("Attempting modifying an immutable graph");
- throw new UnsupportedOperationException();
- }
-
- @Override
- public synchronized boolean addAll(Collection<? extends Triple> c) {
- logger.warn("Attempting modifying an immutable graph");
- throw new UnsupportedOperationException();
- }
-
- @Override
- public synchronized void clear() {
- logger.warn("Attempting modifying an immutable graph");
- throw new UnsupportedOperationException();
- }
-
- @Override
- public synchronized boolean remove(Object o) {
- logger.warn("Attempting modifying an immutable graph");
- throw new UnsupportedOperationException();
- }
-
- @Override
- public synchronized boolean removeAll(Collection<?> col) {
- logger.warn("Attempting modifying an immutable graph");
- throw new UnsupportedOperationException();
- }
-
- /**
- * Must be a VirtuosoGraph with the same name.
- */
- @Override
- public boolean equals(Object o) {
- logger.debug("equals({})",o.getClass());
- if (o instanceof VirtuosoGraph) {
- logger.debug("{} is a VirtuosoGraph)",o);
- if (((VirtuosoGraph) o).getName().equals(this.getName())) {
- logger.debug("Names are equal! They are equal!");
- return true;
- }
- }else{
- logger.debug("Not a VirtuosoGraph instance: {}",o.getClass());
- }
- return false;
- }
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraph.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraph.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraph.java
deleted file mode 100644
index e4dc6d6..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraph.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import java.util.Iterator;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import org.apache.clerezza.rdf.core.Graph;
-import org.apache.clerezza.rdf.core.Literal;
-import org.apache.clerezza.rdf.core.MGraph;
-import org.apache.clerezza.rdf.core.NonLiteral;
-import org.apache.clerezza.rdf.core.Resource;
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.core.UriRef;
-import org.apache.clerezza.rdf.core.access.LockableMGraph;
-import org.apache.clerezza.rdf.core.impl.AbstractMGraph;
-import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/**
- * Implementation of MGraph for the Virtuoso quad store.
- *
- * @author enridaga
- *
- */
-public class VirtuosoMGraph extends AbstractMGraph implements MGraph,
- LockableMGraph {
-
- private final ReadWriteLock lock = new ReentrantReadWriteLock();
- private final Lock readLock = lock.readLock();
- private final Lock writeLock = lock.writeLock();
-
- /**
- * Logger
- */
- protected Logger logger = LoggerFactory.getLogger(VirtuosoMGraph.class);
-
- /**
- * The name of the graph
- */
- private String name = null;
- // private int size = 0;
-
- private VirtuosoGraph readOnly = null;
- private DataAccess dataAccess = null;
-
- /**
- * Creates a {@link VirtuosoMGraph} Virtuoso MGraph binds directly to the
- * store.
- *
- * @param connection
- */
- public VirtuosoMGraph(String name, DataAccess dataAccess) {
- logger.debug("VirtuosoMGraph(String {}, DataAccess {})", name,
- dataAccess);
- this.name = name;
- // this.provider = provider;
- this.dataAccess = dataAccess;
- }
-
- @Override
- public ReadWriteLock getLock() {
- logger.debug("getLock()");
- return lock;
- }
-
- @Override
- public Graph getGraph() {
- logger.debug("getGraph()");
- return asVirtuosoGraph();
- }
-
- public VirtuosoGraph asVirtuosoGraph() {
- logger.debug("asVirtuosoGraph()");
- if (this.readOnly == null) {
- logger.debug("create embedded singleton read-only instance");
- this.readOnly = new VirtuosoGraph(name, getDataAccess());
- }
- return readOnly;
- }
-
- protected DataAccess getDataAccess() {
- return this.dataAccess;
- }
-
- @Override
- protected Iterator<Triple> performFilter(NonLiteral subject,
- UriRef predicate, Resource object) {
- readLock.lock();
- Iterator<Triple> tit = getDataAccess().filter(getName(), subject,
- predicate, object);
- readLock.unlock();
- return tit;
- }
-
- /**
- * We load the size every time it is requested.
- */
- @Override
- public int size() {
- logger.debug("size()");
- readLock.lock();
- int size = getDataAccess().size(getName());
- readLock.unlock();
- return size;
- }
-
- @Override
- public void clear() {
- logger.debug("clear()");
- writeLock.lock();
- getDataAccess().clearGraph(getName());
- writeLock.unlock();
- }
-
- protected boolean performAdd(Triple triple) {
- logger.debug("performAdd(Triple {})", triple);
-
- // If the object is a very long literal we use plan B
- // Reason:
- // Virtuoso Error:
- // SR449: Key is too long, index RDF_QUAD, ruling part is 1901 bytes
- // that exceeds 1900 byte limit
- // We use alternative method for literals
- writeLock.lock();
- if (triple.getObject() instanceof Literal) {
- getDataAccess().performAddPlanB(getName(), triple);
- }else{
- getDataAccess().insertQuad(getName(), triple);
- }
- writeLock.unlock();
- return true;
- }
-
- protected boolean performRemove(Triple triple) {
- logger.debug("performRemove(Triple triple)", triple);
- writeLock.lock();
- getDataAccess().deleteQuad(getName(), triple);
- writeLock.unlock();
- return true;
- }
-
- /**
- * Returns the graph name
- *
- * @return
- */
- public String getName() {
- logger.debug("getName()");
- return name;
- }
-
- /**
- * Must be a VirtuosoMGraph with the same name. Subclasses are not assumed
- * to be equals (VirtuosoGraph is not the same as VirtuosoMGraph)
- */
- public boolean equals(Object o) {
- logger.debug("equals({})", o.getClass());
- // It must be an instance of VirtuosoMGraph
- if (o.getClass().equals(VirtuosoMGraph.class)) {
- logger.debug("{} is a VirtuosoMGraph)", o);
- if (((VirtuosoMGraph) o).getName().equals(this.getName())) {
- logger.debug("Names are equal! They are equal!");
- return true;
- }
- } else {
- logger.debug("Not a VirtuosoMGraph instance: {}", o.getClass());
- }
- return false;
- }
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccess.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccess.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccess.java
deleted file mode 100644
index 5bc29fc..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccess.java
+++ /dev/null
@@ -1,949 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage.access;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.clerezza.rdf.core.BNode;
-import org.apache.clerezza.rdf.core.Language;
-import org.apache.clerezza.rdf.core.NonLiteral;
-import org.apache.clerezza.rdf.core.PlainLiteral;
-import org.apache.clerezza.rdf.core.Resource;
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.core.TypedLiteral;
-import org.apache.clerezza.rdf.core.UriRef;
-import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
-import org.apache.clerezza.rdf.core.impl.TripleImpl;
-import org.apache.clerezza.rdf.core.impl.TypedLiteralImpl;
-import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoBNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.wymiwyg.commons.util.collections.BidiMap;
-import org.wymiwyg.commons.util.collections.BidiMapImpl;
-
-import virtuoso.jdbc4.VirtuosoConnection;
-import virtuoso.jdbc4.VirtuosoException;
-import virtuoso.jdbc4.VirtuosoExtendedString;
-import virtuoso.jdbc4.VirtuosoPreparedStatement;
-import virtuoso.jdbc4.VirtuosoRdfBox;
-import virtuoso.jdbc4.VirtuosoResultSet;
-
-/**
- *
- * @author enridaga
- *
- */
-public class DataAccess {
- private Logger logger = LoggerFactory.getLogger(DataAccess.class);
-
- final static String DRIVER = "virtuoso.jdbc4.Driver";
-
- // XXX This is only used to create a new bnode identifier in virtuoso
- final static String INSERT_NEW_BNODE = "SPARQL INSERT INTO iri(??) { [] `iri(??)` "
- + "`iri(??)`}";
-
- // XXX This is only used to delete a new bnode identifier in virtuoso
- final static String DELETE_NEW_BNODE = "SPARQL DELETE FROM iri(??) { ?s ?p ?o } WHERE { ?s ?p ?o . filter( ?p = iri(??) && "
- + " ?o = iri(??) ) }";
-
- final static String INSERT_QUAD = "SPARQL INSERT INTO iri(??) {`iri(??)` `iri(??)` "
- + "`bif:__rdf_long_from_batch_params(??,??,??)`}";
- final static String DELETE_QUAD = "SPARQL DELETE FROM iri(??) { ?s ?p ?o } WHERE { ?s ?p ?o . filter( ?s = iri(??) && ?p = iri(??) && "
- + " ?o = bif:__rdf_long_from_batch_params(??,??,??) ) } ";
- final static String LIST_GRAPHS = "SPARQL SELECT DISTINCT ?G WHERE {GRAPH ?G {[] [] []} }";
- final static String CLEAR_GRAPH = "SPARQL CLEAR GRAPH iri(??)";
- final static String COUNT_TRIPLES_OF_GRAPH = "SPARQL SELECT COUNT(*) WHERE { bind( iri(??) as ?graph ) . graph ?graph { [] [] [] } }";
- final static String SELECT__ = "SPARQL SELECT ?subject ?predicate ?object WHERE { bind( iri(??) as ?graph ) . GRAPH ?graph { ?subject ?predicate ?object ";
- final static String SELECT_TRIPLES_NULL_NULL_NULL = SELECT__ + " } }";
- final static String SELECT_TRIPLES_S_NULL_NULL = SELECT__ + " . FILTER( ?subject = iri(??) ) } }";
- final static String SELECT_TRIPLES_S_P_NULL = SELECT__ + " . FILTER( ?subject = iri(??) && ?predicate = iri(??) ) } }";
- final static String SELECT_TRIPLES_S_P_O = SELECT__ + " . FILTER( ?subject = iri(??) && ?predicate = iri(??) && ?object = bif:__rdf_long_from_batch_params(??,??,??) ) } }";
- final static String SELECT_TRIPLES_NULL_P_NULL = SELECT__ + " . FILTER( ?predicate = iri(??) ) } }";
- final static String SELECT_TRIPLES_NULL_P_O = SELECT__ + " . FILTER( ?predicate = iri(??) && ?object = bif:__rdf_long_from_batch_params(??,??,??) ) } }";
- final static String SELECT_TRIPLES_NULL_NULL_O = SELECT__ + " . FILTER( ?object = bif:__rdf_long_from_batch_params(??,??,??) ) } }";
- final static String SELECT_TRIPLES_S_NULL_O = SELECT__ + " . FILTER( ?subject = iri(??) && ?object = bif:__rdf_long_from_batch_params(??,??,??) ) } }";
-
- private final static String[] filterQueries = new String[] {
- SELECT_TRIPLES_NULL_NULL_NULL, SELECT_TRIPLES_S_NULL_NULL,
- SELECT_TRIPLES_S_P_O, SELECT_TRIPLES_NULL_NULL_O,
- SELECT_TRIPLES_NULL_P_NULL, SELECT_TRIPLES_S_P_NULL,
- SELECT_TRIPLES_NULL_P_O, SELECT_TRIPLES_S_NULL_O };
-
- /**
- * Bidirectional map for managing the conversion from virtuoso blank nodes
- * (strings) to clerezza blank nodes and vice versa.
- */
- private final BidiMap<VirtuosoBNode, BNode> bnodesMap;
-
- private Map<String, VirtuosoPreparedStatement> preparedStatements = null;
- private VirtuosoConnection connection = null;
- private String connectionString;
- private String user;
- private String pwd;
-
- // We protect the constructor from outside the package...
- DataAccess(String connectionString, String user, String pwd) {
- this.connectionString = connectionString;
- this.user = user;
- this.pwd = pwd;
-
- connection = createConnection(connectionString, user, pwd);
-
- // Init collections
- this.preparedStatements = new HashMap<String,VirtuosoPreparedStatement>();
- this.bnodesMap = new BidiMapImpl<VirtuosoBNode, BNode>();
-
- }
-
- private VirtuosoConnection createConnection(final String cs, final String u, final String p) {
- try {
- VirtuosoConnection c = AccessController.doPrivileged(
- new PrivilegedAction<VirtuosoConnection>() {
- public VirtuosoConnection run() {
- try {
- Class.forName(VirtuosoWeightedProvider.DRIVER, true, this
- .getClass().getClassLoader());
- return (VirtuosoConnection) DriverManager
- .getConnection(cs, u, p);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
- }
- );
- c.setAutoCommit(true);
- return c;
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- // A simple renewal policy
- private int statementCalls = 0;
- protected PreparedStatement getStatement(String query)
- throws VirtuosoException {
- if(statementCalls >= 10000){
- statementCalls=0;
- renew();
- }else{
- statementCalls++;
- }
- if (!preparedStatements.containsKey(query)) {
- VirtuosoPreparedStatement ps = (VirtuosoPreparedStatement) connection
- .prepareStatement(query);
- preparedStatements.put(query, ps);
- }
- return preparedStatements.get(query);
- }
-
- private VirtuosoBNode toVirtBnode(BNode bnode) {
- logger.debug("toVirtBnode(BNode {})", bnode);
- if (bnode instanceof VirtuosoBNode) {
- return ((VirtuosoBNode) bnode);
- } else {
- VirtuosoBNode virtBnode = bnodesMap.getKey(bnode);
- if (virtBnode == null) {
- // We create a local bnode mapped to the BNode given
- virtBnode = nextVirtBnode(bnode);
- bnodesMap.put(virtBnode, bnode);
- }
- return virtBnode;
- }
- }
-
- public void renew() {
- logger.trace("renewing...");
- close();
- connection = createConnection(connectionString, user, pwd);
- }
-
- public void close() {
- logger.trace("closing resources...");
- Collection<VirtuosoPreparedStatement> pss = preparedStatements.values();
- for (VirtuosoPreparedStatement ps : pss) {
- try {
- logger.trace("Closing prepared statement {}", ps);
- ps.close();
- } catch (Exception e) {
- logger.error("Cannot close statement", e);
- }
- }
- logger.trace("closed {} statements.", pss.size());
- preparedStatements.clear();
- try {
- connection.close();
- logger.trace("Connection closed");
- } catch (Exception e) {
- logger.error("Cannot close connection", e);
- }
- }
-
- private void close(String statementId){
- try {
- VirtuosoPreparedStatement ps = preparedStatements.get(statementId);
- if (ps == null) {
- logger.warn(
- "Attempting to close a statement that was not prepared: {}",
- statementId);
- } else {
- logger.trace("Closing prepared statement {}", ps);
- ps.close();
- }
- } catch (Exception e) {
- logger.error("Cannot close statement", e);
- } finally {
- // We won't reuse a statement that thrown a n exception on close...
- preparedStatements.remove(statementId);
- }
- }
-
- private void bindValue(PreparedStatement st, int i, Resource object)
- throws SQLException {
- if (object instanceof UriRef) {
- st.setInt(i, 1);
- st.setString(i + 1, ((UriRef) object).getUnicodeString());
- st.setNull(i + 2, java.sql.Types.VARCHAR);
- } else if (object instanceof BNode) {
- st.setInt(i, 1);
- st.setString(i + 1, ((VirtuosoBNode) object).getSkolemId());
- st.setNull(i + 2, java.sql.Types.VARCHAR);
- } else if (object instanceof TypedLiteral) {
- TypedLiteral tl = ((TypedLiteral) object);
- st.setInt(i, 4);
- st.setString(i + 1, tl.getLexicalForm());
- st.setString(i + 2, tl.getDataType().getUnicodeString());
- } else if (object instanceof PlainLiteral) {
- PlainLiteral pl = (PlainLiteral) object;
- if (pl.getLanguage() != null) {
- st.setInt(i, 5);
- st.setString(i + 1, pl.getLexicalForm());
- st.setString(i + 2, pl.getLanguage().toString());
- } else {
- st.setInt(i, 3);
- st.setString(i + 1, pl.getLexicalForm());
- st.setNull(i + 2, java.sql.Types.VARCHAR);
- }
- } else
- throw new IllegalArgumentException(object.toString());
- }
-
- private void bindPredicate(PreparedStatement st, int i, UriRef predicate)
- throws SQLException {
- st.setString(i, predicate.getUnicodeString());
- }
-
- private void bindSubject(PreparedStatement st, int i, NonLiteral subject)
- throws SQLException {
- if (subject instanceof UriRef) {
- st.setString(i, ((UriRef) subject).getUnicodeString());
- } else {
- st.setString(i, ((VirtuosoBNode) subject).getSkolemId());
- }
- }
-
- private void bindGraph(PreparedStatement st, int i, UriRef uriRef)
- throws SQLException {
- st.setString(i, uriRef.getUnicodeString());
- }
-
-
- private void bindGraph(PreparedStatement st, int i, String uri)
- throws SQLException {
- st.setString(i, uri);
- }
-
- /**
- * Generate a new local bnode to be used in virtuoso queries
- *
- * @return
- */
- private VirtuosoBNode nextVirtBnode(BNode bn) {
- logger.debug("nextVirtBnode(BNode)");
- /**
- * XXX Here we force virtuoso to generate a valid skolem uri for a blank
- * node we are going to insert for the first time.
- *
- * All this process should be more efficient, possibly invoking a native
- * procedure, instead of insert/select/delete a fake triple as it is
- * now.
- */
- UriRef g = new UriRef("urn:x-virtuoso:bnode-tmp");
- UriRef p = new UriRef("urn:x-virtuoso:bnode:object");
- UriRef o = new UriRef(new StringBuilder()
- .append("urn:x-virtuoso:bnode:").append(bn).toString());
-
- Exception e = null;
- VirtuosoResultSet rs = null;
-
- String bnodeId = null;
- // insert
- try {
- PreparedStatement insert = getStatement(INSERT_NEW_BNODE);
- bindGraph(insert, 1, g);
- bindPredicate(insert, 2, p);
- bindSubject(insert, 3, o);
- insert.executeUpdate();
-
- // select
- PreparedStatement select = getStatement(SELECT_TRIPLES_NULL_P_O);
- bindGraph(select, 1, g);
- bindPredicate(select, 2, p);
- bindValue(select, 3, o);
- rs = (VirtuosoResultSet) select.executeQuery();
- rs.next();
- bnodeId = rs.getString(1);
- rs.close();
-
- // delete
- PreparedStatement delete = getStatement(DELETE_NEW_BNODE);
- bindGraph(delete, 1, g);
- bindPredicate(delete, 2, p);
- bindSubject(delete, 3, o); // It is a IRI
- delete.executeUpdate();
-
- } catch (VirtuosoException ve) {
- logger.error("ERROR while executing statement", ve);
- e = ve;
- } catch (SQLException se) {
- logger.error("ERROR while executing statement", se);
- e = se;
- } finally {
- try {
- if (rs != null)
- rs.close();
- } catch (Exception ex) {
- logger.error("Error attempting to close result set", ex);
- }
- }
- if (e != null) {
- close(INSERT_NEW_BNODE);
- close(SELECT_TRIPLES_NULL_P_O);
- close(DELETE_NEW_BNODE);
- throw new RuntimeException(e);
- }
- return new VirtuosoBNode(bnodeId);
-
- }
- public void insertQuad(String graph, Triple triple) {
- NonLiteral s = triple.getSubject();
- UriRef p = triple.getPredicate() ;
- Resource o = triple.getObject();
-
- // Skolemize bnodes
- if(s instanceof BNode){
- s = toVirtBnode((BNode) s);
- }
- if(o instanceof BNode){
- o = toVirtBnode((BNode) o);
- }
-
- try {
- PreparedStatement st = getStatement(INSERT_QUAD);
- bindGraph(st, 1, graph);
- bindSubject(st, 2, s);
- bindPredicate(st, 3, p);
- bindValue(st, 4, o);
- st.executeUpdate();
- } catch (VirtuosoException e) {
- logger.error("Cannot execute statement", e);
- throw new RuntimeException(e);
- } catch (SQLException e) {
- logger.error("Cannot execute statement", e);
- throw new RuntimeException(e);
- }
- }
-
- public void deleteQuad(String graph, Triple triple) {
- NonLiteral s = triple.getSubject();
- UriRef p = triple.getPredicate() ;
- Resource o = triple.getObject();
-
- // Skolemize bnodes
- if(s instanceof BNode){
- s = toVirtBnode((BNode) s);
- }
- if(o instanceof BNode){
- o = toVirtBnode((BNode) o);
- }
- Exception e = null;
- try {
- PreparedStatement st = getStatement(DELETE_QUAD);
- bindGraph(st, 1, graph);
- bindSubject(st, 2, s);
- bindPredicate(st, 3, p);
- bindValue(st, 4, o);
- st.executeUpdate();
- } catch (VirtuosoException ex) {
- logger.error("Cannot execute statement", ex);
- e = ex;
- } catch (SQLException ex) {
- logger.error("Cannot execute statement", ex);
- e = ex;
- }
-
- if (e != null) {
- close(DELETE_QUAD);
- throw new RuntimeException(e);
- }
- }
-
- public Set<UriRef> listGraphs() {
- Exception e = null;
-
- Set<UriRef> graphs = new HashSet<UriRef>();
- try {
- PreparedStatement st = getStatement(LIST_GRAPHS);
- ResultSet rs = st.executeQuery();
- while (rs.next()) {
- UriRef graph = new UriRef(rs.getString(1));
- logger.debug(" > Graph {}", graph);
- graphs.add(graph);
- }
- } catch (VirtuosoException ex) {
- logger.error("Cannot execute query", ex);
- e = ex;
- } catch (SQLException ex) {
- logger.error("Cannot execute query", ex);
- e = ex;
- }
-
- if(e != null){
- close(LIST_GRAPHS);
- throw new RuntimeException(e);
- }
-
- return Collections.unmodifiableSet(graphs);
- }
-
- public void clearGraph(String graph) {
- Exception e = null;
- try {
- PreparedStatement st = getStatement(CLEAR_GRAPH);
- bindGraph(st, 1, graph);
- st.executeUpdate();
- } catch (VirtuosoException ex) {
- logger.error("Cannot execute statement", ex);
- e = ex;
- } catch (SQLException ex) {
- logger.error("Cannot execute statement", ex);
- e = ex;
- }
-
- if(e != null){
- close(CLEAR_GRAPH);
- throw new RuntimeException(e);
- }
- }
-
- private VirtuosoBNode toBNode(String virtbnode) {
- VirtuosoBNode bnode;
- bnode = new VirtuosoBNode(virtbnode);
- return bnode;
- }
-
- public Iterator<Triple> filter(String graph, NonLiteral subject,
- UriRef predicate, Resource object) {
- logger.debug("filter(String graph, NonLiteral s, UriRef p, Resource o)");
-
- // Override blank node object to be a skolemized IRI
- if (object != null && object instanceof BNode) {
- object = new UriRef(toVirtBnode((BNode) object).getSkolemId());
- }
-
- // Override blank node subjects to be a skolemized IRI
- if (subject != null && subject instanceof BNode) {
- subject = new UriRef(toVirtBnode((BNode) subject).getSkolemId());
- }
-
- if (logger.isTraceEnabled()) {
- logger.trace(" > g: {}", graph);
- logger.trace(" > s: {}", subject);
- logger.trace(" > p: {}", predicate);
- logger.trace(" > o: {}", object);
- }
-
- List<Triple> list = null;
- Exception e = null;
- Set<String> filters = new HashSet<String>(Arrays.asList(filterQueries));
-
- //
- if (subject == null) {
- filters.remove(SELECT_TRIPLES_S_P_O);
- filters.remove(SELECT_TRIPLES_S_NULL_NULL);
- filters.remove(SELECT_TRIPLES_S_P_NULL);
- filters.remove(SELECT_TRIPLES_S_NULL_O);
- } else {
- filters.remove(SELECT_TRIPLES_NULL_NULL_NULL);
- filters.remove(SELECT_TRIPLES_NULL_NULL_O);
- filters.remove(SELECT_TRIPLES_NULL_P_NULL);
- filters.remove(SELECT_TRIPLES_NULL_P_O);
- }
- if (predicate == null) {
- filters.remove(SELECT_TRIPLES_S_P_O);
- filters.remove(SELECT_TRIPLES_NULL_P_NULL);
- filters.remove(SELECT_TRIPLES_NULL_P_O);
- filters.remove(SELECT_TRIPLES_S_P_NULL);
- } else {
- filters.remove(SELECT_TRIPLES_S_NULL_O);
- filters.remove(SELECT_TRIPLES_NULL_NULL_NULL);
- filters.remove(SELECT_TRIPLES_NULL_NULL_O);
- filters.remove(SELECT_TRIPLES_S_NULL_NULL);
- }
- if (object == null) {
- filters.remove(SELECT_TRIPLES_S_P_O);
- filters.remove(SELECT_TRIPLES_S_NULL_O);
- filters.remove(SELECT_TRIPLES_NULL_P_O);
- filters.remove(SELECT_TRIPLES_NULL_NULL_O);
- } else {
- filters.remove(SELECT_TRIPLES_S_P_NULL);
- filters.remove(SELECT_TRIPLES_NULL_NULL_NULL);
- filters.remove(SELECT_TRIPLES_NULL_P_NULL);
- filters.remove(SELECT_TRIPLES_S_NULL_NULL);
- }
-
- // There must be only 1 boss
- String filter = filters.iterator().next();
- PreparedStatement ps = null;
- VirtuosoResultSet rs = null;
- try {
- logger.debug("query: {}", filter);
- ps = getStatement(filter);
- // In any case the first binding is the graph
- bindGraph(ps, 1, graph);
-
- int index = 2;
- if (subject != null) {
- bindSubject(ps, index, subject);
- index++;
- }
- if (predicate != null) {
- bindPredicate(ps, index, predicate);
- index++;
- }
- if (object != null) {
- bindValue(ps, index, object);
- }
-
- rs = (VirtuosoResultSet) ps.executeQuery();
- list = new ArrayList<Triple>();
-
- while (rs.next()) {
- list.add(new TripleBuilder(rs.getObject(1), rs.getObject(2), rs
- .getObject(3)).build());
- }
- } catch (VirtuosoException e1) {
- logger.error("ERROR while executing statement", ps);
- e = e1;
- } catch (SQLException e1) {
- logger.error("ERROR while executing statement", ps);
- e = e1;
- } finally {
- try {
- if (rs != null)
- rs.close();
- } catch (Throwable ex) {
- logger.error("Cannot close result set", ex);
- }
- }
-
- if (list == null || e != null) {
- // We also close the statement
- close(filter);
- throw new RuntimeException(e);
- }
- return list.iterator();
- }
-
- public int size(String graph){
- logger.trace("called size({})", graph);
- Exception e = null;
- PreparedStatement ps = null;
- VirtuosoResultSet rs = null;
- int size = -1;
- try {
- ps = getStatement(COUNT_TRIPLES_OF_GRAPH);
- logger.trace("statement got: {}", ps);
- // In any case the first binding is the graph
- bindGraph(ps, 1, graph);
- logger.trace("bound value: {}", graph);
- boolean r = ps.execute();
- logger.trace("Executed statement: {}", r);
- if(r){
- rs = (VirtuosoResultSet) ps.getResultSet();
- logger.trace("Got result set, has next?");
- boolean hn = rs.next();
- logger.trace(" > {}", hn);
- if(hn){
- size = rs.getInt(1);
- }else{
- e = new RuntimeException("Incosistent result. A result row was expected. None obtained.");
- }
- }else{
- e = new RuntimeException("Incosistent result. ResultSet expected but 'false' returned by statement execute() ");
- }
- } catch (VirtuosoException e1) {
- logger.error("ERROR while executing statement", ps);
- e = e1;
- } catch (SQLException e1) {
- logger.error("ERROR while executing statement", ps);
- e = e1;
- } finally {
- try {
- if (rs != null)
- rs.close();
- } catch (Throwable ex) {
- logger.error("Cannot close result set", ex);
- }
- }
-
- if (size == -1 || e != null) {
- // We also close the statement
- close(COUNT_TRIPLES_OF_GRAPH);
- throw new RuntimeException(e);
- }
-
- return size;
- }
-
- /**
- * Builds a clerezza Triple from Virtuoso result types
- *
- */
- private class TripleBuilder {
-
- Object s = null;
- Object p = null;
- Object o = null;
-
- public TripleBuilder(Object s, Object p, Object o) {
- if (logger.isDebugEnabled()) {
- logger.debug("TripleBuilder(Object s, Object p, Object o)");
- logger.debug("> s: {}", s);
- logger.debug("> p: {}", p);
- logger.debug("> o: {}", o);
- }
- this.s = s;
- this.p = p;
- this.o = o;
- }
-
- private NonLiteral buildSubject() {
- logger.debug("TripleBuilder.getSubject() : {}", s);
- if (s instanceof VirtuosoExtendedString) {
- VirtuosoExtendedString vs = (VirtuosoExtendedString) s;
- if (vs.iriType == VirtuosoExtendedString.IRI
- && (vs.strType & 0x01) == 0x01) {
- // Subject is IRI
- return new UriRef(vs.str);
- } else if (vs.iriType == VirtuosoExtendedString.BNODE) {
- return DataAccess.this.toBNode(vs.str);
- } else {
- // !Cannot happen
- throw new IllegalStateException(
- "Subject must be an IRI or a BNODE");
- }
- } else {
- throw new IllegalStateException(
- "Subject must be an instance of VirtuosoExtendedString");
- }
- }
-
- private UriRef buildPredicate() {
- logger.debug("TripleBuilder.getPredicate() : {}", p);
- if (p instanceof VirtuosoExtendedString) {
- VirtuosoExtendedString vs = (VirtuosoExtendedString) p;
- if (vs.iriType == VirtuosoExtendedString.IRI
- && (vs.strType & 0x01) == 0x01) {
- // Subject is IRI
- return new UriRef(vs.str);
- } else {
- // !Cannot happen
- throw new IllegalStateException("Predicate must be an IRI ");
- }
- } else {
- throw new IllegalStateException("Predicate must be an IRI");
- }
- }
-
- Resource buildObject() {
- logger.debug("TripleBuilder.getObject() : {}", o);
-
- if (o instanceof VirtuosoExtendedString) {
- // In case is IRI
- VirtuosoExtendedString vs = (VirtuosoExtendedString) o;
- if (vs.iriType == VirtuosoExtendedString.IRI
- && (vs.strType & 0x01) == 0x01) {
- // Is IRI
- return new UriRef(vs.str);
- } else if (vs.iriType == VirtuosoExtendedString.BNODE) {
- //
- return DataAccess.this.toBNode(vs.str);
- } else {
- // Is a plain literal
- return new PlainLiteralImpl(vs.str);
- }
- } else if (o instanceof VirtuosoRdfBox) {
- // In case is typed literal
- VirtuosoRdfBox rb = (VirtuosoRdfBox) o;
-
- String value;
- if (rb.rb_box.getClass().isAssignableFrom(String.class)) {
- value = (String) rb.rb_box;
- String lang = rb.getLang();
- String type = rb.getType();
- if (type == null) {
- Language language = lang == null ? null : new Language(
- lang);
- return new PlainLiteralImpl(value, language);
- } else {
- return new TypedLiteralImpl(value, new UriRef(type));
- }
- } else if (rb.rb_box instanceof VirtuosoExtendedString) {
- VirtuosoExtendedString vs = (VirtuosoExtendedString) rb.rb_box;
-
- if (vs.iriType == VirtuosoExtendedString.IRI
- && (vs.strType & 0x01) == 0x01) {
- // Is IRI
- return new UriRef(vs.str);
- } else if (vs.iriType == VirtuosoExtendedString.BNODE) {
- //
- return DataAccess.this.toBNode(vs.str);
- } else {
- String type = rb.getType();
- if (type == null) {
- String lang = rb.getLang();
- if (lang != null) {
- return new PlainLiteralImpl(vs.str,
- new Language(lang));
- }
- // Is a plain literal
- return new PlainLiteralImpl(vs.str);
- } else {
- return new TypedLiteralImpl(vs.str,
- new UriRef(type));
- }
- }
- }
- } else if (o == null) {
- // Raise an exception
- throw new IllegalStateException("Object cannot be NULL!");
- }
-
- // FIXME (not clear this...)
- return new PlainLiteralImpl(o.toString());
- }
-
- public Triple build() {
- logger.debug("TripleBuilder.build()");
- return new TripleImpl(buildSubject(), buildPredicate(),
- buildObject());
- }
- }
-
- /**
- * The following private methods are used to support the triple addition
- * plan B
- */
-
- public boolean performAddPlanB(String graph, Triple triple) {
-
- StringBuilder b = new StringBuilder();
- b.append(toVirtSubject(triple.getSubject())).append(" ")
- .append(toVirtPredicate(triple.getPredicate())).append(" ")
- .append(toVirtObject(triple.getObject())).append(" . ");
- String sql = new StringBuilder().append("db.dba.ttlp(?, '', '").append(graph).append("', 0)").toString();
- logger.debug("Exec Plan B: {}", sql);
- Exception e = null;
- PreparedStatement st = null;
- try {
- st = getStatement(sql);
- String s = b.toString();
- logger.trace(" TTL is \n{}\n", s);
- st.setNString(1, b.toString());
- st.execute();
- } catch (VirtuosoException ve) {
- logger.error("ERROR while executing statement", ve);
- e = ve;
- } catch (SQLException se) {
- logger.error("ERROR while executing statement", se);
- e = se;
- }
- if (e != null) {
- close(sql);
- if(logger.isDebugEnabled()){
- logger.error("S {}", triple.getSubject());
- logger.error("P {}", triple.getPredicate());
- logger.error("O {}", triple.getObject());
- logger.error(" O length: {}", triple.getObject().toString()
- .length());
- }
- logger.error("Sql: {}", sql);
- throw new RuntimeException(e);
- }
- return true;
- }
-
- /**
- * Returns a string to be used inline in SQL statements as Object of a
- * triple.
- *
- * @param object
- * @return
- */
- private String toVirtObject(Resource object) {
- logger.debug("toVirtObject(Resource {})", object);
- if (object == null)
- return null;
- if (object instanceof UriRef) {
- return toVirtIri((UriRef) object);
- } else if (object instanceof BNode) {
- return toVirtBnode((BNode) object).asSkolemIri();
- } else if (object instanceof PlainLiteral) {
- return toVirtPlainLiteral((PlainLiteral) object);
- } else if (object instanceof TypedLiteral) {
- return toVirtTypedLiteral((TypedLiteral) object);
- }
- // XXX throw exception here?
- return null;
- }
-
- /**
- * Returns a string to be used in SQL statements.
- *
- * @param object
- * @return
- */
- private String toVirtTypedLiteral(TypedLiteral object) {
- logger.debug("toVirtTypedLiteral(TypedLiteral {})", object);
- UriRef dt = object.getDataType();
- String literal = object.getLexicalForm();// .replaceAll("\"", "\\\\\"");
- StringBuilder prepared;
- // If XMLLiteral, prepare XML entities
- prepared = prepareString(
- literal,
- dt.getUnicodeString()
- .equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"));
- return new StringBuilder().append('"').append('"').append('"')
- .append(prepared).append('"').append('"').append('"')
- .append("^^").append(toVirtIri(dt)).toString();
- }
-
- private StringBuilder prepareString(String str, boolean xml) {
- StringBuilder retStr = new StringBuilder();
- for (int i = 0; i < str.length(); i++) {
- int cp = Character.codePointAt(str, i);
- int charCount = Character.charCount(cp);
- if (charCount > 1) {
- i += charCount - 1; // 2.
- if (i >= str.length()) {
- throw new IllegalArgumentException("truncated unexpectedly");
- }
- }
-
- if (cp < 128) {
- retStr.appendCodePoint(cp);
- } else {
- if (xml) {
- retStr.append(String.format("&#x%04x;", cp));
- } else {
- retStr.append(String.format("\\u%04x", cp));
- }
- }
- }
- return retStr;
- }
-
- /**
- * Returns a string to be used in SQL statements.
- *
- * @param object
- * @return
- */
- private String toVirtPlainLiteral(PlainLiteral object) {
- logger.debug("toVirtPlainLiteral(PlainLiteral {})", object);
- Language lang = object.getLanguage();
- String literal = object.getLexicalForm();
- StringBuilder sb = new StringBuilder().append('"').append('"')
- .append('"').append(prepareString(literal, false)).append('"')
- .append('"').append('"');
- if (lang == null) {
- return sb.toString();
- } else {
- return sb.append("@").append(lang).toString();
- }
- }
-
- /**
- * Returns a string to be used in SQL statements as Predicate of a triple.
- *
- * @param predicate
- * @return
- */
- private String toVirtPredicate(UriRef predicate) {
- logger.debug("toVirtPredicate(UriRef {}) ", predicate);
- if (predicate == null)
- return null;
- return toVirtIri(predicate);
- }
-
- private String toVirtIri(UriRef ur) {
- logger.debug("toVirtIri(UriRef {})", ur);
- return "<" + ur.getUnicodeString() + ">";
- }
-
- /**
- * Returns a string to be used in SQL statements as Subject of a triple.
- *
- * @param subject
- * @return
- */
- private String toVirtSubject(NonLiteral subject) {
- logger.debug("toVirtSubject(NonLiteral {})", subject);
- if (subject == null) {
- return null;
- }
- if (subject instanceof UriRef) {
- return toVirtIri((UriRef) subject);
- } else if (subject instanceof BNode) {
- return toVirtBnode((BNode) subject).asSkolemIri();
- } else {
- // These should be the only 2 implementations
- throw new IllegalArgumentException(
- "subject must be BNode or UriRef");
- }
- }
-
-}
[3/5] CLEREZZA-813 Moved the two virtuoso modules to the clerezza
root folder. Added to the main pom.xml
Posted by en...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccessTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccessTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccessTest.java
deleted file mode 100644
index 3ca89f0..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccessTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage.access;
-
-import java.sql.SQLException;
-
-import org.apache.clerezza.rdf.core.BNode;
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.core.UriRef;
-import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
-import org.apache.clerezza.rdf.core.impl.TripleImpl;
-import org.apache.clerezza.rdf.virtuoso.storage.TestUtils;
-import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class DataAccessTest {
-
- private static DataAccess da = null;
-
- static Logger log = LoggerFactory.getLogger(DataAccessTest.class);
-
- @BeforeClass
- public static void assume(){
- org.junit.Assume.assumeTrue(!TestUtils.SKIP);
- }
-
- @Before
- public void before() throws ClassNotFoundException, SQLException {
- da = TestUtils.getProvider().createDataAccess();
- da.clearGraph( "urn:x-test:DataAccessTest" );
- }
-
- @After
- public void after() {
- da.clearGraph( "urn:x-test:DataAccessTest" );
- da.close();
- da = null;
- }
-
- private void testTriple(Triple t){
- String g = "urn:x-test:DataAccessTest";
- da.insertQuad(g, t);
-
- Assert.assertTrue(da.filter(g, null, null, null).hasNext());
-
- Assert.assertTrue(da.filter(g, t.getSubject(), null, null).hasNext());
- Assert.assertTrue(da.filter(g, null, t.getPredicate(), null).hasNext());
- Assert.assertTrue(da.filter(g, null, null, t.getObject()).hasNext());
-
- Assert.assertTrue(da.filter(g, null, t.getPredicate(), t.getObject()).hasNext());
- Assert.assertTrue(da.filter(g, t.getSubject(), null, t.getObject()).hasNext());
- Assert.assertTrue(da.filter(g, t.getSubject(), t.getPredicate(), null).hasNext());
- Assert.assertTrue(da.filter(g, t.getSubject(), null, t.getObject()).hasNext());
-
- Assert.assertTrue(da.filter(g, t.getSubject(), t.getPredicate(), t.getObject()).hasNext());
-
- Assert.assertTrue(da.size(g) == 1);
-
- da.deleteQuad(g, t);
-
- Assert.assertTrue(da.size(g) == 0);
- }
-
- @Test
- public void test_Uri_Uri_Uri(){
- Triple t = new TripleImpl(new UriRef("urn:subject"), new UriRef("urn:predicate"), new UriRef("urn:object"));
- testTriple(t);
- }
-
- @Test
- public void test_Uri_Uri_PlainLiteral(){
- Triple t = new TripleImpl(new UriRef("urn:subject"), new UriRef("urn:predicate"), new PlainLiteralImpl("Lorem Ipsum"));
- testTriple(t);
- }
-
- @Test
- public void test_Uri_Uri_BNode(){
- Triple t = new TripleImpl(new UriRef("urn:subject"), new UriRef("urn:predicate"), new BNode());
- testTriple(t);
- }
-
- @Test
- public void testRenew(){
- int i = 100;
- while(i>0){
- test_Uri_Uri_Uri();
- test_Uri_Uri_PlainLiteral();
- i--;
- }
- da.renew();
- i = 100;
- while(i>0){
- test_Uri_Uri_Uri();
- test_Uri_Uri_PlainLiteral();
- i--;
- }
- da.renew();
- i = 100;
- while(i>0){
- test_Uri_Uri_Uri();
- test_Uri_Uri_PlainLiteral();
- i--;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
deleted file mode 100644
index 0ac3a27..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage.access;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.sql.SQLException;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.apache.clerezza.rdf.core.Graph;
-import org.apache.clerezza.rdf.core.MGraph;
-import org.apache.clerezza.rdf.core.NonLiteral;
-import org.apache.clerezza.rdf.core.PlainLiteral;
-import org.apache.clerezza.rdf.core.Resource;
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.core.UriRef;
-import org.apache.clerezza.rdf.core.access.NoSuchEntityException;
-import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
-import org.apache.clerezza.rdf.core.impl.SimpleMGraph;
-import org.apache.clerezza.rdf.core.impl.TripleImpl;
-import org.apache.clerezza.rdf.virtuoso.storage.TestUtils;
-import org.apache.clerezza.rdf.virtuoso.storage.access.VirtuosoWeightedProvider;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import virtuoso.jdbc4.VirtuosoException;
-
-/**
- *
- * Tests the VirtuosoWeightedProvider
- *
- * @author enridaga
- *
- */
-public class VirtuosoWeightedProviderTest {
- static final Logger log = LoggerFactory
- .getLogger(VirtuosoWeightedProviderTest.class);
-
- private static final String TEST_GRAPH_URI = "VirtuosoWeightedProviderTest";
-
- private static VirtuosoWeightedProvider wp = null;
-
- @BeforeClass
- public static void before() throws ClassNotFoundException, SQLException {
- org.junit.Assume.assumeTrue(!TestUtils.SKIP);
-
- log.info("Preparing VirtuosoWeightedProvider for test");
- wp = TestUtils.getProvider();
- }
-
- @Test
- public void weight() {
- log.info("Test setting the weight");
- int w = 200;
- wp.setWeight(w);
- assertTrue(wp.getWeight() == w);
- }
-
- @Test
- public void listGraphs() {
- log.info("Test listGraphs()");
- Set<UriRef> gs = wp.listGraphs();
- Iterator<UriRef> it = gs.iterator();
- log.debug("Graphs:");
- while (it.hasNext()) {
- UriRef r = it.next();
- // Must not be null
- assertNotNull(r);
- // Must not be empty string
- assertFalse(r.getUnicodeString().equals(""));
- log.debug(" > {}", r.getUnicodeString());
- }
- }
-
- @Test
- public void listGraphsIsUnmodifiable() {
- log.info("Test listGraphsIsUnmodifiable()");
- Set<UriRef> gs = wp.listGraphs();
- boolean exception = false;
- try {
- gs.add(new UriRef("example"));
- } catch (UnsupportedOperationException e) {
- log.debug(
- "Great, we had an {} exception while modifying an immutable set!",
- e.getClass());
- exception = true;
- }
- assertTrue(exception);
- }
-
- @Test
- public void listMGraphs() {
- log.info("Test listMGraphs()");
- Set<UriRef> mg = wp.listMGraphs();
- log.debug("Graphs:");
- for (UriRef r : mg) {
- // Must not be null
- assertNotNull(r);
- // Must not be empty string
- assertFalse(r.getUnicodeString().equals(""));
- log.debug("MGraph iri: {}", r.getUnicodeString());
- }
- }
-
- final UriRef enridaga = new UriRef("enridaga");
- final UriRef alexdma = new UriRef("alexdma");
- final UriRef anuzzolese = new UriRef("anuzzolese");
- final UriRef predicate = new UriRef("http://property/name");
- final PlainLiteral object = new PlainLiteralImpl("Enrico Daga");
- final UriRef knows = new UriRef(TestUtils.FOAF_NS + "knows");
-
- @Test
- public void createMGraph() {
- log.info("createMGraph()");
- try {
- MGraph mgraph = wp.createMGraph(new UriRef(TEST_GRAPH_URI));
- assertNotNull(mgraph);
- if (log.isDebugEnabled()) {
- log.debug("Created mgraph, adding a triple");
- log.debug("MGraph size is {}", mgraph.size());
- }
- mgraph.add(new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return knows;
- }
-
- @Override
- public Resource getObject() {
- return anuzzolese;
- }
- });
- log.debug("MGraph size is {}", mgraph.size());
- assertTrue(mgraph.size() == 1);
- } catch (RuntimeException re) {
- log.error("ERROR! ", re);
- assertFalse(true);
- }
- }
-
- @Test
- public void createGraph() throws VirtuosoException, ClassNotFoundException,
- SQLException {
- MGraph smg = new SimpleMGraph();
- Triple t = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return knows;
- }
-
- @Override
- public Resource getObject() {
- return anuzzolese;
- }
- };
- smg.add(t);
- UriRef name = new UriRef(TEST_GRAPH_URI);
- Graph g = wp.createGraph(name, smg);
- // Graph must contain the triple
- assertTrue(g.contains(t));
- // Graph size must be 1
- assertTrue(g.size() == 1);
- // Graph retrieved by id must contain the triple
- assertTrue(wp.getGraph(name).contains(t));
- // Graph retrieved by id must be equal to g
- assertTrue(wp.getGraph(name).equals(g));
- }
-
- @Test
- public void testEquals() {
- log.info("testEquals()");
- UriRef name = new UriRef(TEST_GRAPH_URI);
- MGraph g = wp.createMGraph(name);
- // Equals
- log.debug("Should be equal: {}", g.equals(wp.getMGraph(name)));
- assertTrue(g.equals(wp.getMGraph(name)));
- log.debug("{} <-> {}", g.getClass(), g.getGraph().getClass());
- log.debug("Should not be equal: {}", g.equals(g.getGraph()));
- // Not equals
- assertFalse(g.equals(g.getGraph()));
- }
-
- @Before
- @After
- public void clear() throws VirtuosoException, ClassNotFoundException,
- SQLException {
- log.info("clear()");
- log.debug("Removing test graphs <{}>", TEST_GRAPH_URI);
- try {
- wp.deleteTripleCollection(new UriRef(TEST_GRAPH_URI));
- } catch (NoSuchEntityException nsee) {
- // Nothing to do
- }
- try {
- wp.deleteTripleCollection(new UriRef("urn:my-empty-graph"));
- } catch (NoSuchEntityException nsee) {
- // Nothing to do
- }
- try {
- wp.deleteTripleCollection(new UriRef("urn:my-non-empty-graph"));
- } catch (NoSuchEntityException nsee) {
- // Nothing to do
- }
- }
-
- @Test
- public void testCreateEmptyMGraph(){
- log.info("testCreateEmptyMGraph()");
-// try {
- UriRef ur = new UriRef("urn:my-empty-graph");
- Assert.assertFalse(wp.listGraphs().contains(ur));
- Assert.assertFalse(wp.listMGraphs().contains(ur));
- wp.createMGraph(ur);
- Assert.assertTrue(wp.canRead(ur));
- Assert.assertTrue(wp.canModify(ur));
- Assert.assertTrue(wp.listGraphs().contains(ur));
- Assert.assertTrue(wp.listMGraphs().contains(ur));
- wp.deleteTripleCollection(ur);
- Assert.assertFalse(wp.listGraphs().contains(ur));
- Assert.assertFalse(wp.listMGraphs().contains(ur));
-// } catch (NoSuchEntityException nsee) {
-// // Nothing to do
-// }
- }
-
- @Test
- public void testEmptyAndNonEmptyGraphs(){
- log.info("testEmptyAndNonEmptyGraphs()");
-
- UriRef ur = new UriRef("urn:my-empty-graph");
- UriRef nur = new UriRef("urn:my-non-empty-graph");
-
- Assert.assertFalse(wp.listGraphs().contains(ur));
- Assert.assertFalse(wp.listMGraphs().contains(ur));
- wp.createMGraph(ur);
- Assert.assertTrue(wp.canRead(ur));
- Assert.assertTrue(wp.canModify(ur));
- wp.createMGraph(nur);
- Assert.assertTrue(wp.canRead(nur));
- Assert.assertTrue(wp.canModify(nur));
- Assert.assertTrue(wp.listGraphs().contains(nur));
- Assert.assertTrue(wp.listMGraphs().contains(nur));
-
- // Add a triple to the non-empty graph
- Triple t = new TripleImpl(new UriRef("urn:test:subject"), new UriRef("urn:test:predicate"),
- new PlainLiteralImpl("A literal"));
- wp.getMGraph(nur).add(t);
- // Show inserted triple
- Iterator<Triple> ti = wp.getMGraph(nur).iterator();
- while(ti.hasNext()){
- log.info(" > {}", ti.next());
- }
- Assert.assertTrue(wp.getMGraph(nur).contains(t));
- Assert.assertTrue(wp.getMGraph(ur).isEmpty());
- // We delete the empty graph
- wp.deleteTripleCollection(ur);
- Assert.assertFalse(wp.listGraphs().contains(ur));
- Assert.assertFalse(wp.listMGraphs().contains(ur));
- // But the other is still there
- Assert.assertTrue(wp.listGraphs().contains(nur));
- Assert.assertTrue(wp.listMGraphs().contains(nur));
- // And it still contains its triple
- Assert.assertTrue(wp.getMGraph(nur).contains(t));
- // We delete the triple
- wp.getMGraph(nur).remove(t);
- Assert.assertFalse(wp.getMGraph(nur).contains(t));
- Assert.assertTrue(wp.getMGraph(nur).isEmpty());
- // We delete the non empty graph
- wp.deleteTripleCollection(nur);
- Assert.assertFalse(wp.listGraphs().contains(nur));
- Assert.assertFalse(wp.listMGraphs().contains(nur));
-
- }
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/resources/log4j.properties b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/resources/log4j.properties
deleted file mode 100644
index ad89d4d..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/resources/log4j.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-log4j.rootLogger=INFO, S
-log4j.appender.S = org.apache.log4j.ConsoleAppender
-log4j.appender.S.layout = org.apache.log4j.PatternLayout
-log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
-
-log4j.logger.rdf.virtuoso.storage=DEBUG
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/ext.virtuoso.jdbc/pom.xml
----------------------------------------------------------------------
diff --git a/ext.virtuoso.jdbc/pom.xml b/ext.virtuoso.jdbc/pom.xml
new file mode 100644
index 0000000..1bf0bd1
--- /dev/null
+++ b/ext.virtuoso.jdbc/pom.xml
@@ -0,0 +1,143 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.clerezza</groupId>
+ <artifactId>clerezza</artifactId>
+ <version>0.5-SNAPSHOT</version>
+ <relativePath>../parent</relativePath>
+ </parent>
+ <artifactId>ext.virtuoso.jdbc</artifactId>
+ <name>Clerezza Ext - Virtuoso JDBC OSGi Bundle</name>
+ <description>Virtuoso JDBC</description>
+ <version>0.3-SNAPSHOT</version>
+ <repositories>
+ <repository>
+ <releases>
+ <updatePolicy>always</updatePolicy>
+ </releases>
+ <snapshots>
+ <updatePolicy>always</updatePolicy>
+ </snapshots>
+ <id>virtuoso-jdbc4-embedded</id>
+ <url>file://localhost/${project.basedir}/src/main/resources/maven/repo</url>
+ </repository>
+ </repositories>
+ <dependencies>
+ <dependency>
+ <groupId>virtuoso</groupId>
+ <artifactId>virtjdbc</artifactId>
+ <type>jar</type>
+ <version>4.1</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
+ <Embed-Dependency>*;scope=compile;artifactId=!slf4j-api</Embed-Dependency>
+ <!-- Embed-Transitive>true</Embed-Transitive -->
+ <!-- Import-Package> </Import-Package -->
+ <Export-Package>
+ openlink.util.*,
+ virtuoso.javax.*,
+ virtuoso.jdbc4.*,
+ virtuoso.sql.*
+ </Export-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ <pluginManagement>
+ <plugins>
+ <!--This plugin's configuration is used to store Eclipse m2e settings
+ only. It has no influence on the Maven build itself. -->
+ <plugin>
+ <groupId>org.eclipse.m2e</groupId>
+ <artifactId>lifecycle-mapping</artifactId>
+ <version>1.0.0</version>
+ <configuration>
+ <lifecycleMappingMetadata>
+ <pluginExecutions>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>
+ org.apache.felix
+ </groupId>
+ <artifactId>
+ maven-scr-plugin
+ </artifactId>
+ <versionRange>
+ [1.7.0,)
+ </versionRange>
+ <goals>
+ <goal>scr</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore></ignore>
+ </action>
+ </pluginExecution>
+ </pluginExecutions>
+ </lifecycleMappingMetadata>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+ <packaging>bundle</packaging>
+ <profiles>
+ <profile>
+ <!-- This profile allows for installing/updating a bundle in a running
+ Sling instance right after building it. Example: mvn clean install -P installBundle
+ -Dsling.url=http://localhost:8080/system/console Or, to make it faster without
+ cleaning up or running tests: mvn -o install -DskipTests -P installBundle
+ -Dsling.url=http://localhost:8080/system/console -->
+ <id>installBundle</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>maven-sling-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>install-bundle</id>
+ <goals>
+ <goal>install</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+</project>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar
----------------------------------------------------------------------
diff --git a/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar
new file mode 100644
index 0000000..b207f0c
Binary files /dev/null and b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.jar differ
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom
----------------------------------------------------------------------
diff --git a/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom
new file mode 100644
index 0000000..02fa48e
--- /dev/null
+++ b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.0/virtjdbc-4.0.pom
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?><!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+--><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>virtuoso</groupId>
+ <artifactId>virtjdbc</artifactId>
+ <version>4.0</version>
+ <description>POM was created from install:install-file</description>
+</project>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar
----------------------------------------------------------------------
diff --git a/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar
new file mode 100755
index 0000000..1c6ccec
Binary files /dev/null and b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.jar differ
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom
----------------------------------------------------------------------
diff --git a/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom
new file mode 100644
index 0000000..87605c7
--- /dev/null
+++ b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/4.1/virtjdbc-4.1.pom
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?><!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+--><project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>virtuoso</groupId>
+ <artifactId>virtjdbc</artifactId>
+ <version>4.1</version>
+ <description>POM was created from install:install-file</description>
+</project>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/maven-metadata-local.xml
----------------------------------------------------------------------
diff --git a/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/maven-metadata-local.xml b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/maven-metadata-local.xml
new file mode 100644
index 0000000..a0d93d6
--- /dev/null
+++ b/ext.virtuoso.jdbc/src/main/resources/maven/repo/virtuoso/virtjdbc/maven-metadata-local.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?><!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+--><metadata>
+ <groupId>virtuoso</groupId>
+ <artifactId>virtjdbc</artifactId>
+ <versioning>
+ <release>4.1</release>
+ <versions>
+ <version>4.1</version>
+ <version>4.0</version>
+ </versions>
+ </versioning>
+</metadata>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 7eebb9d..cf42652 100644
--- a/pom.xml
+++ b/pom.xml
@@ -156,6 +156,10 @@
<module>web.resources.yui</module>
<module>rdf.storage.externalizer</module>
<module>rdf.storage.web</module>
+
+ <module>ext.virtuoso.jdbc</module>
+ <module>rdf.virtuoso.storage</module>
+ <module>platform.launcher.virtuoso</module>
</modules>
</profile>
<profile>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/README.md
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/README.md b/rdf.virtuoso.storage/README.md
new file mode 100644
index 0000000..31fa1ab
--- /dev/null
+++ b/rdf.virtuoso.storage/README.md
@@ -0,0 +1,49 @@
+# rdf.virtuoso.storage
+
+This module includes an implementation of the storage SPI of Clerezza that connects to a Virtuoso instance.
+
+## Build and Install
+To build this project you need Maven.
+
+### Simple build
+
+ $ mvn clean install
+
+This module depends on:
+* ext.virtuoso.jdbc : contains JDBC drivers form Virtuoso
+
+Bundle is in the /target folder:
+* rdf.virtuoso.storage/target/rdf.virtuoso.storage-<version>.jar
+
+### Build forcing tests
+You must have a Virtuoso running server to do tests.
+Tests are skipped by default.
+To activate tests, you can set the system property "virtuoso.test" to true:
+
+ $ mvn test -Dvirtuoso.test=true
+
+By default, the tests will use the parameters configured in the pom.xml. Change the parameters' values to the ones that fit your installation of Virtuoso.
+
+You can configure the following parameters:
+
+* virtuoso.test (default is null)
+* virtuoso.driver (default is 'virtuoso.jdbc4.Driver')
+* virtuoso.host (default is 'localhost')
+* virtuoso.port (default is '1111')
+* virtuoso.user (default is 'dba')
+* virtuoso.password (default is 'dba')
+
+To override them from cli, you can also do the following:
+
+ $ mvn test -Dvirtuoso.test=true -DargLine="-Dvirtuoso.password=mypassword -Dvirtuoso.port=1234"
+
+### Deploy
+This bundle needs the following:
+* org.jboss.spec.javax.transaction:jboss-transaction-api_1.1_spec:1.0.1.Final
+* org.apache.clerezza:ext.virtuoso.jdbc:0.3
+
+To deploy the bundle in a running Felix instance you can do:
+
+ $ mvn install -PinstallBundle -Dsling.url=http://localhost:8080/system/console (change this to be the actual server admin interface)
+
+
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/pom.xml
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/pom.xml b/rdf.virtuoso.storage/pom.xml
new file mode 100644
index 0000000..fd88a50
--- /dev/null
+++ b/rdf.virtuoso.storage/pom.xml
@@ -0,0 +1,271 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <artifactId>clerezza</artifactId>
+ <groupId>org.apache.clerezza</groupId>
+ <version>0.5-SNAPSHOT</version>
+ <relativePath>../parent</relativePath>
+ </parent>
+ <artifactId>rdf.virtuoso.storage</artifactId>
+ <name>Clerezza - SCB Virtuoso storage provider</name>
+ <description>A virtuoso based storage provider</description>
+ <packaging>bundle</packaging>
+ <version>0.3-SNAPSHOT</version>
+
+ <dependencies>
+ <!-- CLEREZZA -->
+ <dependency>
+ <groupId>org.apache.clerezza</groupId>
+ <artifactId>rdf.core</artifactId>
+ <version>0.14-SNAPSHOT</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.wymiwyg</groupId>
+ <artifactId>wymiwyg-commons-core</artifactId>
+ </dependency>
+ <!-- VIRTUOSO Dependencies -->
+ <dependency>
+ <groupId>clerezza-virtuoso</groupId>
+ <artifactId>ext.virtuoso.jdbc</artifactId>
+ <version>0.3-SNAPSHOT</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- OSGI -->
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.scr.annotations</artifactId>
+ </dependency>
+
+ <!-- LOGGING -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- TEST (generic) -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+<!-- <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <scope>test</scope>
+ <version></version>
+ </dependency>
+-->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.clerezza</groupId>
+ <artifactId>platform.config</artifactId>
+ <version>0.3-incubating</version>
+ <type>bundle</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.clerezza</groupId>
+ <artifactId>rdf.jena.parser</artifactId>
+ <version>0.11</version>
+ <type>bundle</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.hp.hpl.jena</groupId>
+ <artifactId>jena</artifactId>
+ <version>2.6.4</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.clerezza</groupId>
+ <artifactId>rdf.jena.facade</artifactId>
+ <version>0.13</version>
+ <type>bundle</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.clerezza</groupId>
+ <artifactId>rdf.jena.commons</artifactId>
+ <version>0.6</version>
+ <type>bundle</type>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <profiles>
+ <profile>
+ <id>virtuoso-do-tests</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+ <properties>
+ <virtuoso.test>true</virtuoso.test>
+ </properties>
+ </profile>
+ </profiles>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>default-test</id>
+ <phase>test</phase>
+ <goals>
+ <goal>test</goal>
+ </goals>
+ <configuration>
+ <systemPropertyVariables>
+ <virtuoso.test>${virtuoso.test}</virtuoso.test>
+ <virtuoso.driver>virtuoso.jdbc4.Driver</virtuoso.driver>
+ <virtuoso.host>localhost</virtuoso.host>
+ <virtuoso.port>1111</virtuoso.port>
+ <virtuoso.user>dba</virtuoso.user>
+ <virtuoso.password>dba</virtuoso.password>
+ </systemPropertyVariables>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-scr-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>generate-scr-scrdescriptor</id>
+ <goals>
+ <goal>scr</goal>
+ </goals>
+ </execution>
+ </executions>
+ <!-- see http://felix.apache.org/site/apache-felix-scr-plugin-faq.html#ApacheFelixSCRPluginFAQ-NoClassDefFoundErrorduringbuild -->
+ <dependencies>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <version>1.6.1</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Include-Resource>
+ src/main/resources,
+ target/scr-plugin-generated
+ </Include-Resource>
+ <Service-Component>
+ OSGI-INF/serviceComponents.xml
+ </Service-Component>
+ <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ <pluginManagement>
+ <plugins>
+
+ <!-- plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
+ <Embed-Dependency>*;scope=compile|runtime;artifactId=!slf4j-api</Embed-Dependency>
+ <Import-Package>*</Import-Package>
+ <Export-Package>
+ rdf.virtuoso.storage.*
+ </Export-Package>
+ </instructions>
+ </configuration>
+ </plugin -->
+
+ <!--This plugin's configuration is used to store Eclipse m2e settings
+ only. It has no influence on the Maven build itself. -->
+ <plugin>
+ <groupId>org.eclipse.m2e</groupId>
+ <artifactId>lifecycle-mapping</artifactId>
+ <version>1.0.0</version>
+ <configuration>
+ <lifecycleMappingMetadata>
+ <pluginExecutions>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>
+ org.apache.felix
+ </groupId>
+ <artifactId>
+ maven-scr-plugin
+ </artifactId>
+ <versionRange>
+ [1.7.0,)
+ </versionRange>
+ <goals>
+ <goal>scr</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore></ignore>
+ </action>
+ </pluginExecution>
+ </pluginExecutions>
+ </lifecycleMappingMetadata>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+</project>
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoBNode.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoBNode.java b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoBNode.java
new file mode 100644
index 0000000..e8cc46f
--- /dev/null
+++ b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoBNode.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import org.apache.clerezza.rdf.core.BNode;
+
+public class VirtuosoBNode extends BNode {
+ private String skolemId;
+ public VirtuosoBNode(String skolemId) {
+ this.skolemId = skolemId;
+ }
+
+ public String getSkolemId(){
+ return skolemId;
+ }
+
+ public String asSkolemIri(){
+ return new StringBuilder().append('<').append(skolemId).append('>').toString();
+ }
+
+ public String toString(){
+ return skolemId;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return (obj instanceof VirtuosoBNode) && (obj.toString().equals(toString()));
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraph.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraph.java b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraph.java
new file mode 100644
index 0000000..2516fdc
--- /dev/null
+++ b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraph.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import java.util.Collection;
+
+import org.apache.clerezza.rdf.core.Graph;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * This is a read-only version of {@link VirtuosoMGraph}
+ * @author enridaga
+ *
+ */
+public class VirtuosoGraph extends VirtuosoMGraph implements Graph{
+
+ /**
+ * Logger
+ */
+ protected Logger logger = LoggerFactory
+ .getLogger(VirtuosoGraph.class);
+
+ public VirtuosoGraph(String name, DataAccess dataAccess) {
+ super(name, dataAccess);
+ }
+
+ @Override
+ public synchronized boolean add(Triple e) {
+ logger.warn("Attempting modifying an immutable graph");
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public synchronized boolean addAll(Collection<? extends Triple> c) {
+ logger.warn("Attempting modifying an immutable graph");
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public synchronized void clear() {
+ logger.warn("Attempting modifying an immutable graph");
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public synchronized boolean remove(Object o) {
+ logger.warn("Attempting modifying an immutable graph");
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public synchronized boolean removeAll(Collection<?> col) {
+ logger.warn("Attempting modifying an immutable graph");
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Must be a VirtuosoGraph with the same name.
+ */
+ @Override
+ public boolean equals(Object o) {
+ logger.debug("equals({})",o.getClass());
+ if (o instanceof VirtuosoGraph) {
+ logger.debug("{} is a VirtuosoGraph)",o);
+ if (((VirtuosoGraph) o).getName().equals(this.getName())) {
+ logger.debug("Names are equal! They are equal!");
+ return true;
+ }
+ }else{
+ logger.debug("Not a VirtuosoGraph instance: {}",o.getClass());
+ }
+ return false;
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraph.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraph.java b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraph.java
new file mode 100644
index 0000000..e4dc6d6
--- /dev/null
+++ b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraph.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage;
+
+import java.util.Iterator;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import org.apache.clerezza.rdf.core.Graph;
+import org.apache.clerezza.rdf.core.Literal;
+import org.apache.clerezza.rdf.core.MGraph;
+import org.apache.clerezza.rdf.core.NonLiteral;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.access.LockableMGraph;
+import org.apache.clerezza.rdf.core.impl.AbstractMGraph;
+import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Implementation of MGraph for the Virtuoso quad store.
+ *
+ * @author enridaga
+ *
+ */
+public class VirtuosoMGraph extends AbstractMGraph implements MGraph,
+ LockableMGraph {
+
+ private final ReadWriteLock lock = new ReentrantReadWriteLock();
+ private final Lock readLock = lock.readLock();
+ private final Lock writeLock = lock.writeLock();
+
+ /**
+ * Logger
+ */
+ protected Logger logger = LoggerFactory.getLogger(VirtuosoMGraph.class);
+
+ /**
+ * The name of the graph
+ */
+ private String name = null;
+ // private int size = 0;
+
+ private VirtuosoGraph readOnly = null;
+ private DataAccess dataAccess = null;
+
+ /**
+ * Creates a {@link VirtuosoMGraph} Virtuoso MGraph binds directly to the
+ * store.
+ *
+ * @param connection
+ */
+ public VirtuosoMGraph(String name, DataAccess dataAccess) {
+ logger.debug("VirtuosoMGraph(String {}, DataAccess {})", name,
+ dataAccess);
+ this.name = name;
+ // this.provider = provider;
+ this.dataAccess = dataAccess;
+ }
+
+ @Override
+ public ReadWriteLock getLock() {
+ logger.debug("getLock()");
+ return lock;
+ }
+
+ @Override
+ public Graph getGraph() {
+ logger.debug("getGraph()");
+ return asVirtuosoGraph();
+ }
+
+ public VirtuosoGraph asVirtuosoGraph() {
+ logger.debug("asVirtuosoGraph()");
+ if (this.readOnly == null) {
+ logger.debug("create embedded singleton read-only instance");
+ this.readOnly = new VirtuosoGraph(name, getDataAccess());
+ }
+ return readOnly;
+ }
+
+ protected DataAccess getDataAccess() {
+ return this.dataAccess;
+ }
+
+ @Override
+ protected Iterator<Triple> performFilter(NonLiteral subject,
+ UriRef predicate, Resource object) {
+ readLock.lock();
+ Iterator<Triple> tit = getDataAccess().filter(getName(), subject,
+ predicate, object);
+ readLock.unlock();
+ return tit;
+ }
+
+ /**
+ * We load the size every time it is requested.
+ */
+ @Override
+ public int size() {
+ logger.debug("size()");
+ readLock.lock();
+ int size = getDataAccess().size(getName());
+ readLock.unlock();
+ return size;
+ }
+
+ @Override
+ public void clear() {
+ logger.debug("clear()");
+ writeLock.lock();
+ getDataAccess().clearGraph(getName());
+ writeLock.unlock();
+ }
+
+ protected boolean performAdd(Triple triple) {
+ logger.debug("performAdd(Triple {})", triple);
+
+ // If the object is a very long literal we use plan B
+ // Reason:
+ // Virtuoso Error:
+ // SR449: Key is too long, index RDF_QUAD, ruling part is 1901 bytes
+ // that exceeds 1900 byte limit
+ // We use alternative method for literals
+ writeLock.lock();
+ if (triple.getObject() instanceof Literal) {
+ getDataAccess().performAddPlanB(getName(), triple);
+ }else{
+ getDataAccess().insertQuad(getName(), triple);
+ }
+ writeLock.unlock();
+ return true;
+ }
+
+ protected boolean performRemove(Triple triple) {
+ logger.debug("performRemove(Triple triple)", triple);
+ writeLock.lock();
+ getDataAccess().deleteQuad(getName(), triple);
+ writeLock.unlock();
+ return true;
+ }
+
+ /**
+ * Returns the graph name
+ *
+ * @return
+ */
+ public String getName() {
+ logger.debug("getName()");
+ return name;
+ }
+
+ /**
+ * Must be a VirtuosoMGraph with the same name. Subclasses are not assumed
+ * to be equals (VirtuosoGraph is not the same as VirtuosoMGraph)
+ */
+ public boolean equals(Object o) {
+ logger.debug("equals({})", o.getClass());
+ // It must be an instance of VirtuosoMGraph
+ if (o.getClass().equals(VirtuosoMGraph.class)) {
+ logger.debug("{} is a VirtuosoMGraph)", o);
+ if (((VirtuosoMGraph) o).getName().equals(this.getName())) {
+ logger.debug("Names are equal! They are equal!");
+ return true;
+ }
+ } else {
+ logger.debug("Not a VirtuosoMGraph instance: {}", o.getClass());
+ }
+ return false;
+ }
+}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccess.java
----------------------------------------------------------------------
diff --git a/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccess.java b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccess.java
new file mode 100644
index 0000000..5bc29fc
--- /dev/null
+++ b/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/DataAccess.java
@@ -0,0 +1,949 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.clerezza.rdf.virtuoso.storage.access;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.clerezza.rdf.core.BNode;
+import org.apache.clerezza.rdf.core.Language;
+import org.apache.clerezza.rdf.core.NonLiteral;
+import org.apache.clerezza.rdf.core.PlainLiteral;
+import org.apache.clerezza.rdf.core.Resource;
+import org.apache.clerezza.rdf.core.Triple;
+import org.apache.clerezza.rdf.core.TypedLiteral;
+import org.apache.clerezza.rdf.core.UriRef;
+import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
+import org.apache.clerezza.rdf.core.impl.TripleImpl;
+import org.apache.clerezza.rdf.core.impl.TypedLiteralImpl;
+import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoBNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wymiwyg.commons.util.collections.BidiMap;
+import org.wymiwyg.commons.util.collections.BidiMapImpl;
+
+import virtuoso.jdbc4.VirtuosoConnection;
+import virtuoso.jdbc4.VirtuosoException;
+import virtuoso.jdbc4.VirtuosoExtendedString;
+import virtuoso.jdbc4.VirtuosoPreparedStatement;
+import virtuoso.jdbc4.VirtuosoRdfBox;
+import virtuoso.jdbc4.VirtuosoResultSet;
+
+/**
+ *
+ * @author enridaga
+ *
+ */
+public class DataAccess {
+ private Logger logger = LoggerFactory.getLogger(DataAccess.class);
+
+ final static String DRIVER = "virtuoso.jdbc4.Driver";
+
+ // XXX This is only used to create a new bnode identifier in virtuoso
+ final static String INSERT_NEW_BNODE = "SPARQL INSERT INTO iri(??) { [] `iri(??)` "
+ + "`iri(??)`}";
+
+ // XXX This is only used to delete a new bnode identifier in virtuoso
+ final static String DELETE_NEW_BNODE = "SPARQL DELETE FROM iri(??) { ?s ?p ?o } WHERE { ?s ?p ?o . filter( ?p = iri(??) && "
+ + " ?o = iri(??) ) }";
+
+ final static String INSERT_QUAD = "SPARQL INSERT INTO iri(??) {`iri(??)` `iri(??)` "
+ + "`bif:__rdf_long_from_batch_params(??,??,??)`}";
+ final static String DELETE_QUAD = "SPARQL DELETE FROM iri(??) { ?s ?p ?o } WHERE { ?s ?p ?o . filter( ?s = iri(??) && ?p = iri(??) && "
+ + " ?o = bif:__rdf_long_from_batch_params(??,??,??) ) } ";
+ final static String LIST_GRAPHS = "SPARQL SELECT DISTINCT ?G WHERE {GRAPH ?G {[] [] []} }";
+ final static String CLEAR_GRAPH = "SPARQL CLEAR GRAPH iri(??)";
+ final static String COUNT_TRIPLES_OF_GRAPH = "SPARQL SELECT COUNT(*) WHERE { bind( iri(??) as ?graph ) . graph ?graph { [] [] [] } }";
+ final static String SELECT__ = "SPARQL SELECT ?subject ?predicate ?object WHERE { bind( iri(??) as ?graph ) . GRAPH ?graph { ?subject ?predicate ?object ";
+ final static String SELECT_TRIPLES_NULL_NULL_NULL = SELECT__ + " } }";
+ final static String SELECT_TRIPLES_S_NULL_NULL = SELECT__ + " . FILTER( ?subject = iri(??) ) } }";
+ final static String SELECT_TRIPLES_S_P_NULL = SELECT__ + " . FILTER( ?subject = iri(??) && ?predicate = iri(??) ) } }";
+ final static String SELECT_TRIPLES_S_P_O = SELECT__ + " . FILTER( ?subject = iri(??) && ?predicate = iri(??) && ?object = bif:__rdf_long_from_batch_params(??,??,??) ) } }";
+ final static String SELECT_TRIPLES_NULL_P_NULL = SELECT__ + " . FILTER( ?predicate = iri(??) ) } }";
+ final static String SELECT_TRIPLES_NULL_P_O = SELECT__ + " . FILTER( ?predicate = iri(??) && ?object = bif:__rdf_long_from_batch_params(??,??,??) ) } }";
+ final static String SELECT_TRIPLES_NULL_NULL_O = SELECT__ + " . FILTER( ?object = bif:__rdf_long_from_batch_params(??,??,??) ) } }";
+ final static String SELECT_TRIPLES_S_NULL_O = SELECT__ + " . FILTER( ?subject = iri(??) && ?object = bif:__rdf_long_from_batch_params(??,??,??) ) } }";
+
+ private final static String[] filterQueries = new String[] {
+ SELECT_TRIPLES_NULL_NULL_NULL, SELECT_TRIPLES_S_NULL_NULL,
+ SELECT_TRIPLES_S_P_O, SELECT_TRIPLES_NULL_NULL_O,
+ SELECT_TRIPLES_NULL_P_NULL, SELECT_TRIPLES_S_P_NULL,
+ SELECT_TRIPLES_NULL_P_O, SELECT_TRIPLES_S_NULL_O };
+
+ /**
+ * Bidirectional map for managing the conversion from virtuoso blank nodes
+ * (strings) to clerezza blank nodes and vice versa.
+ */
+ private final BidiMap<VirtuosoBNode, BNode> bnodesMap;
+
+ private Map<String, VirtuosoPreparedStatement> preparedStatements = null;
+ private VirtuosoConnection connection = null;
+ private String connectionString;
+ private String user;
+ private String pwd;
+
+ // We protect the constructor from outside the package...
+ DataAccess(String connectionString, String user, String pwd) {
+ this.connectionString = connectionString;
+ this.user = user;
+ this.pwd = pwd;
+
+ connection = createConnection(connectionString, user, pwd);
+
+ // Init collections
+ this.preparedStatements = new HashMap<String,VirtuosoPreparedStatement>();
+ this.bnodesMap = new BidiMapImpl<VirtuosoBNode, BNode>();
+
+ }
+
+ private VirtuosoConnection createConnection(final String cs, final String u, final String p) {
+ try {
+ VirtuosoConnection c = AccessController.doPrivileged(
+ new PrivilegedAction<VirtuosoConnection>() {
+ public VirtuosoConnection run() {
+ try {
+ Class.forName(VirtuosoWeightedProvider.DRIVER, true, this
+ .getClass().getClassLoader());
+ return (VirtuosoConnection) DriverManager
+ .getConnection(cs, u, p);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+ );
+ c.setAutoCommit(true);
+ return c;
+ } catch (SQLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ // A simple renewal policy
+ private int statementCalls = 0;
+ protected PreparedStatement getStatement(String query)
+ throws VirtuosoException {
+ if(statementCalls >= 10000){
+ statementCalls=0;
+ renew();
+ }else{
+ statementCalls++;
+ }
+ if (!preparedStatements.containsKey(query)) {
+ VirtuosoPreparedStatement ps = (VirtuosoPreparedStatement) connection
+ .prepareStatement(query);
+ preparedStatements.put(query, ps);
+ }
+ return preparedStatements.get(query);
+ }
+
+ private VirtuosoBNode toVirtBnode(BNode bnode) {
+ logger.debug("toVirtBnode(BNode {})", bnode);
+ if (bnode instanceof VirtuosoBNode) {
+ return ((VirtuosoBNode) bnode);
+ } else {
+ VirtuosoBNode virtBnode = bnodesMap.getKey(bnode);
+ if (virtBnode == null) {
+ // We create a local bnode mapped to the BNode given
+ virtBnode = nextVirtBnode(bnode);
+ bnodesMap.put(virtBnode, bnode);
+ }
+ return virtBnode;
+ }
+ }
+
+ public void renew() {
+ logger.trace("renewing...");
+ close();
+ connection = createConnection(connectionString, user, pwd);
+ }
+
+ public void close() {
+ logger.trace("closing resources...");
+ Collection<VirtuosoPreparedStatement> pss = preparedStatements.values();
+ for (VirtuosoPreparedStatement ps : pss) {
+ try {
+ logger.trace("Closing prepared statement {}", ps);
+ ps.close();
+ } catch (Exception e) {
+ logger.error("Cannot close statement", e);
+ }
+ }
+ logger.trace("closed {} statements.", pss.size());
+ preparedStatements.clear();
+ try {
+ connection.close();
+ logger.trace("Connection closed");
+ } catch (Exception e) {
+ logger.error("Cannot close connection", e);
+ }
+ }
+
+ private void close(String statementId){
+ try {
+ VirtuosoPreparedStatement ps = preparedStatements.get(statementId);
+ if (ps == null) {
+ logger.warn(
+ "Attempting to close a statement that was not prepared: {}",
+ statementId);
+ } else {
+ logger.trace("Closing prepared statement {}", ps);
+ ps.close();
+ }
+ } catch (Exception e) {
+ logger.error("Cannot close statement", e);
+ } finally {
+ // We won't reuse a statement that thrown a n exception on close...
+ preparedStatements.remove(statementId);
+ }
+ }
+
+ private void bindValue(PreparedStatement st, int i, Resource object)
+ throws SQLException {
+ if (object instanceof UriRef) {
+ st.setInt(i, 1);
+ st.setString(i + 1, ((UriRef) object).getUnicodeString());
+ st.setNull(i + 2, java.sql.Types.VARCHAR);
+ } else if (object instanceof BNode) {
+ st.setInt(i, 1);
+ st.setString(i + 1, ((VirtuosoBNode) object).getSkolemId());
+ st.setNull(i + 2, java.sql.Types.VARCHAR);
+ } else if (object instanceof TypedLiteral) {
+ TypedLiteral tl = ((TypedLiteral) object);
+ st.setInt(i, 4);
+ st.setString(i + 1, tl.getLexicalForm());
+ st.setString(i + 2, tl.getDataType().getUnicodeString());
+ } else if (object instanceof PlainLiteral) {
+ PlainLiteral pl = (PlainLiteral) object;
+ if (pl.getLanguage() != null) {
+ st.setInt(i, 5);
+ st.setString(i + 1, pl.getLexicalForm());
+ st.setString(i + 2, pl.getLanguage().toString());
+ } else {
+ st.setInt(i, 3);
+ st.setString(i + 1, pl.getLexicalForm());
+ st.setNull(i + 2, java.sql.Types.VARCHAR);
+ }
+ } else
+ throw new IllegalArgumentException(object.toString());
+ }
+
+ private void bindPredicate(PreparedStatement st, int i, UriRef predicate)
+ throws SQLException {
+ st.setString(i, predicate.getUnicodeString());
+ }
+
+ private void bindSubject(PreparedStatement st, int i, NonLiteral subject)
+ throws SQLException {
+ if (subject instanceof UriRef) {
+ st.setString(i, ((UriRef) subject).getUnicodeString());
+ } else {
+ st.setString(i, ((VirtuosoBNode) subject).getSkolemId());
+ }
+ }
+
+ private void bindGraph(PreparedStatement st, int i, UriRef uriRef)
+ throws SQLException {
+ st.setString(i, uriRef.getUnicodeString());
+ }
+
+
+ private void bindGraph(PreparedStatement st, int i, String uri)
+ throws SQLException {
+ st.setString(i, uri);
+ }
+
+ /**
+ * Generate a new local bnode to be used in virtuoso queries
+ *
+ * @return
+ */
+ private VirtuosoBNode nextVirtBnode(BNode bn) {
+ logger.debug("nextVirtBnode(BNode)");
+ /**
+ * XXX Here we force virtuoso to generate a valid skolem uri for a blank
+ * node we are going to insert for the first time.
+ *
+ * All this process should be more efficient, possibly invoking a native
+ * procedure, instead of insert/select/delete a fake triple as it is
+ * now.
+ */
+ UriRef g = new UriRef("urn:x-virtuoso:bnode-tmp");
+ UriRef p = new UriRef("urn:x-virtuoso:bnode:object");
+ UriRef o = new UriRef(new StringBuilder()
+ .append("urn:x-virtuoso:bnode:").append(bn).toString());
+
+ Exception e = null;
+ VirtuosoResultSet rs = null;
+
+ String bnodeId = null;
+ // insert
+ try {
+ PreparedStatement insert = getStatement(INSERT_NEW_BNODE);
+ bindGraph(insert, 1, g);
+ bindPredicate(insert, 2, p);
+ bindSubject(insert, 3, o);
+ insert.executeUpdate();
+
+ // select
+ PreparedStatement select = getStatement(SELECT_TRIPLES_NULL_P_O);
+ bindGraph(select, 1, g);
+ bindPredicate(select, 2, p);
+ bindValue(select, 3, o);
+ rs = (VirtuosoResultSet) select.executeQuery();
+ rs.next();
+ bnodeId = rs.getString(1);
+ rs.close();
+
+ // delete
+ PreparedStatement delete = getStatement(DELETE_NEW_BNODE);
+ bindGraph(delete, 1, g);
+ bindPredicate(delete, 2, p);
+ bindSubject(delete, 3, o); // It is a IRI
+ delete.executeUpdate();
+
+ } catch (VirtuosoException ve) {
+ logger.error("ERROR while executing statement", ve);
+ e = ve;
+ } catch (SQLException se) {
+ logger.error("ERROR while executing statement", se);
+ e = se;
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Exception ex) {
+ logger.error("Error attempting to close result set", ex);
+ }
+ }
+ if (e != null) {
+ close(INSERT_NEW_BNODE);
+ close(SELECT_TRIPLES_NULL_P_O);
+ close(DELETE_NEW_BNODE);
+ throw new RuntimeException(e);
+ }
+ return new VirtuosoBNode(bnodeId);
+
+ }
+ public void insertQuad(String graph, Triple triple) {
+ NonLiteral s = triple.getSubject();
+ UriRef p = triple.getPredicate() ;
+ Resource o = triple.getObject();
+
+ // Skolemize bnodes
+ if(s instanceof BNode){
+ s = toVirtBnode((BNode) s);
+ }
+ if(o instanceof BNode){
+ o = toVirtBnode((BNode) o);
+ }
+
+ try {
+ PreparedStatement st = getStatement(INSERT_QUAD);
+ bindGraph(st, 1, graph);
+ bindSubject(st, 2, s);
+ bindPredicate(st, 3, p);
+ bindValue(st, 4, o);
+ st.executeUpdate();
+ } catch (VirtuosoException e) {
+ logger.error("Cannot execute statement", e);
+ throw new RuntimeException(e);
+ } catch (SQLException e) {
+ logger.error("Cannot execute statement", e);
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void deleteQuad(String graph, Triple triple) {
+ NonLiteral s = triple.getSubject();
+ UriRef p = triple.getPredicate() ;
+ Resource o = triple.getObject();
+
+ // Skolemize bnodes
+ if(s instanceof BNode){
+ s = toVirtBnode((BNode) s);
+ }
+ if(o instanceof BNode){
+ o = toVirtBnode((BNode) o);
+ }
+ Exception e = null;
+ try {
+ PreparedStatement st = getStatement(DELETE_QUAD);
+ bindGraph(st, 1, graph);
+ bindSubject(st, 2, s);
+ bindPredicate(st, 3, p);
+ bindValue(st, 4, o);
+ st.executeUpdate();
+ } catch (VirtuosoException ex) {
+ logger.error("Cannot execute statement", ex);
+ e = ex;
+ } catch (SQLException ex) {
+ logger.error("Cannot execute statement", ex);
+ e = ex;
+ }
+
+ if (e != null) {
+ close(DELETE_QUAD);
+ throw new RuntimeException(e);
+ }
+ }
+
+ public Set<UriRef> listGraphs() {
+ Exception e = null;
+
+ Set<UriRef> graphs = new HashSet<UriRef>();
+ try {
+ PreparedStatement st = getStatement(LIST_GRAPHS);
+ ResultSet rs = st.executeQuery();
+ while (rs.next()) {
+ UriRef graph = new UriRef(rs.getString(1));
+ logger.debug(" > Graph {}", graph);
+ graphs.add(graph);
+ }
+ } catch (VirtuosoException ex) {
+ logger.error("Cannot execute query", ex);
+ e = ex;
+ } catch (SQLException ex) {
+ logger.error("Cannot execute query", ex);
+ e = ex;
+ }
+
+ if(e != null){
+ close(LIST_GRAPHS);
+ throw new RuntimeException(e);
+ }
+
+ return Collections.unmodifiableSet(graphs);
+ }
+
+ public void clearGraph(String graph) {
+ Exception e = null;
+ try {
+ PreparedStatement st = getStatement(CLEAR_GRAPH);
+ bindGraph(st, 1, graph);
+ st.executeUpdate();
+ } catch (VirtuosoException ex) {
+ logger.error("Cannot execute statement", ex);
+ e = ex;
+ } catch (SQLException ex) {
+ logger.error("Cannot execute statement", ex);
+ e = ex;
+ }
+
+ if(e != null){
+ close(CLEAR_GRAPH);
+ throw new RuntimeException(e);
+ }
+ }
+
+ private VirtuosoBNode toBNode(String virtbnode) {
+ VirtuosoBNode bnode;
+ bnode = new VirtuosoBNode(virtbnode);
+ return bnode;
+ }
+
+ public Iterator<Triple> filter(String graph, NonLiteral subject,
+ UriRef predicate, Resource object) {
+ logger.debug("filter(String graph, NonLiteral s, UriRef p, Resource o)");
+
+ // Override blank node object to be a skolemized IRI
+ if (object != null && object instanceof BNode) {
+ object = new UriRef(toVirtBnode((BNode) object).getSkolemId());
+ }
+
+ // Override blank node subjects to be a skolemized IRI
+ if (subject != null && subject instanceof BNode) {
+ subject = new UriRef(toVirtBnode((BNode) subject).getSkolemId());
+ }
+
+ if (logger.isTraceEnabled()) {
+ logger.trace(" > g: {}", graph);
+ logger.trace(" > s: {}", subject);
+ logger.trace(" > p: {}", predicate);
+ logger.trace(" > o: {}", object);
+ }
+
+ List<Triple> list = null;
+ Exception e = null;
+ Set<String> filters = new HashSet<String>(Arrays.asList(filterQueries));
+
+ //
+ if (subject == null) {
+ filters.remove(SELECT_TRIPLES_S_P_O);
+ filters.remove(SELECT_TRIPLES_S_NULL_NULL);
+ filters.remove(SELECT_TRIPLES_S_P_NULL);
+ filters.remove(SELECT_TRIPLES_S_NULL_O);
+ } else {
+ filters.remove(SELECT_TRIPLES_NULL_NULL_NULL);
+ filters.remove(SELECT_TRIPLES_NULL_NULL_O);
+ filters.remove(SELECT_TRIPLES_NULL_P_NULL);
+ filters.remove(SELECT_TRIPLES_NULL_P_O);
+ }
+ if (predicate == null) {
+ filters.remove(SELECT_TRIPLES_S_P_O);
+ filters.remove(SELECT_TRIPLES_NULL_P_NULL);
+ filters.remove(SELECT_TRIPLES_NULL_P_O);
+ filters.remove(SELECT_TRIPLES_S_P_NULL);
+ } else {
+ filters.remove(SELECT_TRIPLES_S_NULL_O);
+ filters.remove(SELECT_TRIPLES_NULL_NULL_NULL);
+ filters.remove(SELECT_TRIPLES_NULL_NULL_O);
+ filters.remove(SELECT_TRIPLES_S_NULL_NULL);
+ }
+ if (object == null) {
+ filters.remove(SELECT_TRIPLES_S_P_O);
+ filters.remove(SELECT_TRIPLES_S_NULL_O);
+ filters.remove(SELECT_TRIPLES_NULL_P_O);
+ filters.remove(SELECT_TRIPLES_NULL_NULL_O);
+ } else {
+ filters.remove(SELECT_TRIPLES_S_P_NULL);
+ filters.remove(SELECT_TRIPLES_NULL_NULL_NULL);
+ filters.remove(SELECT_TRIPLES_NULL_P_NULL);
+ filters.remove(SELECT_TRIPLES_S_NULL_NULL);
+ }
+
+ // There must be only 1 boss
+ String filter = filters.iterator().next();
+ PreparedStatement ps = null;
+ VirtuosoResultSet rs = null;
+ try {
+ logger.debug("query: {}", filter);
+ ps = getStatement(filter);
+ // In any case the first binding is the graph
+ bindGraph(ps, 1, graph);
+
+ int index = 2;
+ if (subject != null) {
+ bindSubject(ps, index, subject);
+ index++;
+ }
+ if (predicate != null) {
+ bindPredicate(ps, index, predicate);
+ index++;
+ }
+ if (object != null) {
+ bindValue(ps, index, object);
+ }
+
+ rs = (VirtuosoResultSet) ps.executeQuery();
+ list = new ArrayList<Triple>();
+
+ while (rs.next()) {
+ list.add(new TripleBuilder(rs.getObject(1), rs.getObject(2), rs
+ .getObject(3)).build());
+ }
+ } catch (VirtuosoException e1) {
+ logger.error("ERROR while executing statement", ps);
+ e = e1;
+ } catch (SQLException e1) {
+ logger.error("ERROR while executing statement", ps);
+ e = e1;
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Throwable ex) {
+ logger.error("Cannot close result set", ex);
+ }
+ }
+
+ if (list == null || e != null) {
+ // We also close the statement
+ close(filter);
+ throw new RuntimeException(e);
+ }
+ return list.iterator();
+ }
+
+ public int size(String graph){
+ logger.trace("called size({})", graph);
+ Exception e = null;
+ PreparedStatement ps = null;
+ VirtuosoResultSet rs = null;
+ int size = -1;
+ try {
+ ps = getStatement(COUNT_TRIPLES_OF_GRAPH);
+ logger.trace("statement got: {}", ps);
+ // In any case the first binding is the graph
+ bindGraph(ps, 1, graph);
+ logger.trace("bound value: {}", graph);
+ boolean r = ps.execute();
+ logger.trace("Executed statement: {}", r);
+ if(r){
+ rs = (VirtuosoResultSet) ps.getResultSet();
+ logger.trace("Got result set, has next?");
+ boolean hn = rs.next();
+ logger.trace(" > {}", hn);
+ if(hn){
+ size = rs.getInt(1);
+ }else{
+ e = new RuntimeException("Incosistent result. A result row was expected. None obtained.");
+ }
+ }else{
+ e = new RuntimeException("Incosistent result. ResultSet expected but 'false' returned by statement execute() ");
+ }
+ } catch (VirtuosoException e1) {
+ logger.error("ERROR while executing statement", ps);
+ e = e1;
+ } catch (SQLException e1) {
+ logger.error("ERROR while executing statement", ps);
+ e = e1;
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ } catch (Throwable ex) {
+ logger.error("Cannot close result set", ex);
+ }
+ }
+
+ if (size == -1 || e != null) {
+ // We also close the statement
+ close(COUNT_TRIPLES_OF_GRAPH);
+ throw new RuntimeException(e);
+ }
+
+ return size;
+ }
+
+ /**
+ * Builds a clerezza Triple from Virtuoso result types
+ *
+ */
+ private class TripleBuilder {
+
+ Object s = null;
+ Object p = null;
+ Object o = null;
+
+ public TripleBuilder(Object s, Object p, Object o) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("TripleBuilder(Object s, Object p, Object o)");
+ logger.debug("> s: {}", s);
+ logger.debug("> p: {}", p);
+ logger.debug("> o: {}", o);
+ }
+ this.s = s;
+ this.p = p;
+ this.o = o;
+ }
+
+ private NonLiteral buildSubject() {
+ logger.debug("TripleBuilder.getSubject() : {}", s);
+ if (s instanceof VirtuosoExtendedString) {
+ VirtuosoExtendedString vs = (VirtuosoExtendedString) s;
+ if (vs.iriType == VirtuosoExtendedString.IRI
+ && (vs.strType & 0x01) == 0x01) {
+ // Subject is IRI
+ return new UriRef(vs.str);
+ } else if (vs.iriType == VirtuosoExtendedString.BNODE) {
+ return DataAccess.this.toBNode(vs.str);
+ } else {
+ // !Cannot happen
+ throw new IllegalStateException(
+ "Subject must be an IRI or a BNODE");
+ }
+ } else {
+ throw new IllegalStateException(
+ "Subject must be an instance of VirtuosoExtendedString");
+ }
+ }
+
+ private UriRef buildPredicate() {
+ logger.debug("TripleBuilder.getPredicate() : {}", p);
+ if (p instanceof VirtuosoExtendedString) {
+ VirtuosoExtendedString vs = (VirtuosoExtendedString) p;
+ if (vs.iriType == VirtuosoExtendedString.IRI
+ && (vs.strType & 0x01) == 0x01) {
+ // Subject is IRI
+ return new UriRef(vs.str);
+ } else {
+ // !Cannot happen
+ throw new IllegalStateException("Predicate must be an IRI ");
+ }
+ } else {
+ throw new IllegalStateException("Predicate must be an IRI");
+ }
+ }
+
+ Resource buildObject() {
+ logger.debug("TripleBuilder.getObject() : {}", o);
+
+ if (o instanceof VirtuosoExtendedString) {
+ // In case is IRI
+ VirtuosoExtendedString vs = (VirtuosoExtendedString) o;
+ if (vs.iriType == VirtuosoExtendedString.IRI
+ && (vs.strType & 0x01) == 0x01) {
+ // Is IRI
+ return new UriRef(vs.str);
+ } else if (vs.iriType == VirtuosoExtendedString.BNODE) {
+ //
+ return DataAccess.this.toBNode(vs.str);
+ } else {
+ // Is a plain literal
+ return new PlainLiteralImpl(vs.str);
+ }
+ } else if (o instanceof VirtuosoRdfBox) {
+ // In case is typed literal
+ VirtuosoRdfBox rb = (VirtuosoRdfBox) o;
+
+ String value;
+ if (rb.rb_box.getClass().isAssignableFrom(String.class)) {
+ value = (String) rb.rb_box;
+ String lang = rb.getLang();
+ String type = rb.getType();
+ if (type == null) {
+ Language language = lang == null ? null : new Language(
+ lang);
+ return new PlainLiteralImpl(value, language);
+ } else {
+ return new TypedLiteralImpl(value, new UriRef(type));
+ }
+ } else if (rb.rb_box instanceof VirtuosoExtendedString) {
+ VirtuosoExtendedString vs = (VirtuosoExtendedString) rb.rb_box;
+
+ if (vs.iriType == VirtuosoExtendedString.IRI
+ && (vs.strType & 0x01) == 0x01) {
+ // Is IRI
+ return new UriRef(vs.str);
+ } else if (vs.iriType == VirtuosoExtendedString.BNODE) {
+ //
+ return DataAccess.this.toBNode(vs.str);
+ } else {
+ String type = rb.getType();
+ if (type == null) {
+ String lang = rb.getLang();
+ if (lang != null) {
+ return new PlainLiteralImpl(vs.str,
+ new Language(lang));
+ }
+ // Is a plain literal
+ return new PlainLiteralImpl(vs.str);
+ } else {
+ return new TypedLiteralImpl(vs.str,
+ new UriRef(type));
+ }
+ }
+ }
+ } else if (o == null) {
+ // Raise an exception
+ throw new IllegalStateException("Object cannot be NULL!");
+ }
+
+ // FIXME (not clear this...)
+ return new PlainLiteralImpl(o.toString());
+ }
+
+ public Triple build() {
+ logger.debug("TripleBuilder.build()");
+ return new TripleImpl(buildSubject(), buildPredicate(),
+ buildObject());
+ }
+ }
+
+ /**
+ * The following private methods are used to support the triple addition
+ * plan B
+ */
+
+ public boolean performAddPlanB(String graph, Triple triple) {
+
+ StringBuilder b = new StringBuilder();
+ b.append(toVirtSubject(triple.getSubject())).append(" ")
+ .append(toVirtPredicate(triple.getPredicate())).append(" ")
+ .append(toVirtObject(triple.getObject())).append(" . ");
+ String sql = new StringBuilder().append("db.dba.ttlp(?, '', '").append(graph).append("', 0)").toString();
+ logger.debug("Exec Plan B: {}", sql);
+ Exception e = null;
+ PreparedStatement st = null;
+ try {
+ st = getStatement(sql);
+ String s = b.toString();
+ logger.trace(" TTL is \n{}\n", s);
+ st.setNString(1, b.toString());
+ st.execute();
+ } catch (VirtuosoException ve) {
+ logger.error("ERROR while executing statement", ve);
+ e = ve;
+ } catch (SQLException se) {
+ logger.error("ERROR while executing statement", se);
+ e = se;
+ }
+ if (e != null) {
+ close(sql);
+ if(logger.isDebugEnabled()){
+ logger.error("S {}", triple.getSubject());
+ logger.error("P {}", triple.getPredicate());
+ logger.error("O {}", triple.getObject());
+ logger.error(" O length: {}", triple.getObject().toString()
+ .length());
+ }
+ logger.error("Sql: {}", sql);
+ throw new RuntimeException(e);
+ }
+ return true;
+ }
+
+ /**
+ * Returns a string to be used inline in SQL statements as Object of a
+ * triple.
+ *
+ * @param object
+ * @return
+ */
+ private String toVirtObject(Resource object) {
+ logger.debug("toVirtObject(Resource {})", object);
+ if (object == null)
+ return null;
+ if (object instanceof UriRef) {
+ return toVirtIri((UriRef) object);
+ } else if (object instanceof BNode) {
+ return toVirtBnode((BNode) object).asSkolemIri();
+ } else if (object instanceof PlainLiteral) {
+ return toVirtPlainLiteral((PlainLiteral) object);
+ } else if (object instanceof TypedLiteral) {
+ return toVirtTypedLiteral((TypedLiteral) object);
+ }
+ // XXX throw exception here?
+ return null;
+ }
+
+ /**
+ * Returns a string to be used in SQL statements.
+ *
+ * @param object
+ * @return
+ */
+ private String toVirtTypedLiteral(TypedLiteral object) {
+ logger.debug("toVirtTypedLiteral(TypedLiteral {})", object);
+ UriRef dt = object.getDataType();
+ String literal = object.getLexicalForm();// .replaceAll("\"", "\\\\\"");
+ StringBuilder prepared;
+ // If XMLLiteral, prepare XML entities
+ prepared = prepareString(
+ literal,
+ dt.getUnicodeString()
+ .equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"));
+ return new StringBuilder().append('"').append('"').append('"')
+ .append(prepared).append('"').append('"').append('"')
+ .append("^^").append(toVirtIri(dt)).toString();
+ }
+
+ private StringBuilder prepareString(String str, boolean xml) {
+ StringBuilder retStr = new StringBuilder();
+ for (int i = 0; i < str.length(); i++) {
+ int cp = Character.codePointAt(str, i);
+ int charCount = Character.charCount(cp);
+ if (charCount > 1) {
+ i += charCount - 1; // 2.
+ if (i >= str.length()) {
+ throw new IllegalArgumentException("truncated unexpectedly");
+ }
+ }
+
+ if (cp < 128) {
+ retStr.appendCodePoint(cp);
+ } else {
+ if (xml) {
+ retStr.append(String.format("&#x%04x;", cp));
+ } else {
+ retStr.append(String.format("\\u%04x", cp));
+ }
+ }
+ }
+ return retStr;
+ }
+
+ /**
+ * Returns a string to be used in SQL statements.
+ *
+ * @param object
+ * @return
+ */
+ private String toVirtPlainLiteral(PlainLiteral object) {
+ logger.debug("toVirtPlainLiteral(PlainLiteral {})", object);
+ Language lang = object.getLanguage();
+ String literal = object.getLexicalForm();
+ StringBuilder sb = new StringBuilder().append('"').append('"')
+ .append('"').append(prepareString(literal, false)).append('"')
+ .append('"').append('"');
+ if (lang == null) {
+ return sb.toString();
+ } else {
+ return sb.append("@").append(lang).toString();
+ }
+ }
+
+ /**
+ * Returns a string to be used in SQL statements as Predicate of a triple.
+ *
+ * @param predicate
+ * @return
+ */
+ private String toVirtPredicate(UriRef predicate) {
+ logger.debug("toVirtPredicate(UriRef {}) ", predicate);
+ if (predicate == null)
+ return null;
+ return toVirtIri(predicate);
+ }
+
+ private String toVirtIri(UriRef ur) {
+ logger.debug("toVirtIri(UriRef {})", ur);
+ return "<" + ur.getUnicodeString() + ">";
+ }
+
+ /**
+ * Returns a string to be used in SQL statements as Subject of a triple.
+ *
+ * @param subject
+ * @return
+ */
+ private String toVirtSubject(NonLiteral subject) {
+ logger.debug("toVirtSubject(NonLiteral {})", subject);
+ if (subject == null) {
+ return null;
+ }
+ if (subject instanceof UriRef) {
+ return toVirtIri((UriRef) subject);
+ } else if (subject instanceof BNode) {
+ return toVirtBnode((BNode) subject).asSkolemIri();
+ } else {
+ // These should be the only 2 implementations
+ throw new IllegalArgumentException(
+ "subject must be BNode or UriRef");
+ }
+ }
+
+}
[4/5] CLEREZZA-813 Moved the two virtuoso modules to the clerezza
root folder. Added to the main pom.xml
Posted by en...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
deleted file mode 100644
index 1e4628b..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/org/apache/clerezza/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
+++ /dev/null
@@ -1,937 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage.access;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.Writer;
-import java.math.BigInteger;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.clerezza.rdf.core.Graph;
-import org.apache.clerezza.rdf.core.MGraph;
-import org.apache.clerezza.rdf.core.TripleCollection;
-import org.apache.clerezza.rdf.core.UriRef;
-import org.apache.clerezza.rdf.core.access.EntityAlreadyExistsException;
-import org.apache.clerezza.rdf.core.access.EntityUndeletableException;
-import org.apache.clerezza.rdf.core.access.NoSuchEntityException;
-import org.apache.clerezza.rdf.core.access.TcManager;
-import org.apache.clerezza.rdf.core.access.WeightedTcProvider;
-import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoGraph;
-import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoMGraph;
-import org.apache.felix.scr.annotations.Activate;
-import org.apache.felix.scr.annotations.Component;
-import org.apache.felix.scr.annotations.Deactivate;
-import org.apache.felix.scr.annotations.Properties;
-import org.apache.felix.scr.annotations.Property;
-import org.apache.felix.scr.annotations.Service;
-import org.osgi.framework.Constants;
-import org.osgi.service.cm.ConfigurationException;
-import org.osgi.service.component.ComponentContext;
-import org.osgi.service.component.ComponentException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import virtuoso.jdbc4.VirtuosoConnection;
-import virtuoso.jdbc4.VirtuosoException;
-import virtuoso.jdbc4.VirtuosoPreparedStatement;
-import virtuoso.jdbc4.VirtuosoResultSet;
-import virtuoso.jdbc4.VirtuosoStatement;
-
-/**
- * A {@link org.apache.clerezza.rdf.core.access.WeightedTcProvider} for
- * Virtuoso.
- *
- * @author enridaga
- *
- */
-@Component(metatype = true, immediate = true)
-@Service(WeightedTcProvider.class)
-@Properties({
- @Property(name = "password", description = "User password"),
- @Property(name = "host", description = "The host running the Virtuoso server"),
- @Property(name = "port", description = "The port number"),
- @Property(name = "user", description = "User name"),
- @Property(name = "weight", intValue = 110, description = "Weight assigned to this provider"),
- @Property(name = TcManager.GENERAL_PURPOSE_TC, boolValue = true) })
-public class VirtuosoWeightedProvider implements WeightedTcProvider {
-
- // JDBC driver class (XXX move to DataAccess?)
- public static final String DRIVER = "virtuoso.jdbc4.Driver";
-
- // Default value for the property "weight"
- public static final int DEFAULT_WEIGHT = 110;
-
- // Names of properties in OSGi configuration
- public static final String HOST = "host";
- public static final String PORT = "port";
- public static final String USER = "user";
- public static final String PASSWORD = "password";
- public static final String WEIGHT = "weight";
-
- // Name of the graph used to contain the registry of the created graphs
- public static final String ACTIVE_GRAPHS_GRAPH = "urn:x-virtuoso:active-graphs";
-
- // Loaded graphs
- private Map<UriRef, VirtuosoMGraph> graphs = new HashMap<UriRef, VirtuosoMGraph>();
-
- // DataAccess registry
- private Set<DataAccess> dataAccessSet = new HashSet<DataAccess>();
-
- // Logger
- private Logger logger = LoggerFactory
- .getLogger(VirtuosoWeightedProvider.class);
-
- // Fields
- private String host;
- private Integer port;
- private String user;
- private String pwd;
- private String connStr;
- private int weight = DEFAULT_WEIGHT;
-
- /**
- * Creates a new {@link VirtuosoWeightedProvider}.
- *
- * Before the weighted provider can be used, the method
- * <code>activate</code> has to be called.
- */
- public VirtuosoWeightedProvider() {
- logger.debug("Created VirtuosoWeightedProvider.");
- }
-
- public VirtuosoWeightedProvider(String jdbcConnectionString,
- String jdbcUser, String jdbcPassword) {
- connStr = jdbcConnectionString;
- user = jdbcUser;
- pwd = jdbcPassword;
- }
-
- /**
- * Activates this component.<br />
- *
- * @param cCtx
- * Execution context of this component. A value of null is
- * acceptable when you set the property connection
- * @throws ConfigurationException
- * @throws IllegalArgumentException
- * No component context given and connection was not set.
- */
- @Activate
- public void activate(ComponentContext cCtx) {
- logger.trace("activate(ComponentContext {})", cCtx);
- logger.info("Activating VirtuosoWeightedProvider...");
-
- if (cCtx == null) {
- logger.error("No component context given and connection was not set");
- throw new IllegalArgumentException(
- "No component context given and connection was not set");
- } else if (cCtx != null) {
- logger.debug("Context is given: {}", cCtx);
- String pid = (String) cCtx.getProperties().get(
- Constants.SERVICE_PID);
- try {
-
- // Bind logging of DriverManager
- if (logger.isDebugEnabled()) {
- logger.debug("Activating logging for DriverManager");
- // DriverManager.setLogWriter(new PrintWriter(System.err));
- DriverManager.setLogWriter(new PrintWriter(new Writer() {
- private Logger l = LoggerFactory
- .getLogger(DriverManager.class);
- private StringBuilder b = new StringBuilder();
-
- @Override
- public void write(char[] cbuf, int off, int len)
- throws IOException {
- b.append(cbuf, off, len);
- }
-
- @Override
- public void flush() throws IOException {
- l.debug("{}", b.toString());
- b = new StringBuilder();
- }
-
- @Override
- public void close() throws IOException {
- l.debug("{}", b.toString());
- l.debug("Log DriverManager PrintWriter closed");
- }
- }));
- }
-
- // FIXME The following should not be needed...
- try {
- this.weight = (Integer) cCtx.getProperties().get(WEIGHT);
- } catch (NumberFormatException nfe) {
- logger.warn(nfe.toString());
- logger.warn("Setting weight to defaults");
- this.weight = DEFAULT_WEIGHT;
- }
-
- /**
- * Initialize connection properties
- */
- // We take the configuration of the SCR component
- Object phost = cCtx.getProperties().get(HOST);
- Object pport = cCtx.getProperties().get(PORT);
- Object puser = cCtx.getProperties().get(USER);
- Object ppwd = cCtx.getProperties().get(PASSWORD);
-
- // If the component is not configured, we inspect system properties
- // Maybe this is a first launch, otherwise we set a value as default
- if(phost == null && System.getProperty("virtuoso.host") != null){
- phost = System.getProperty("virtuoso.host");
- } else if(phost == null){
- phost = "localhost";
- }
- if(pport == null && System.getProperty("virtuoso.port") != null){
- pport = System.getProperty("virtuoso.port");
- } else if(pport == null){
- pport = Integer.valueOf(1111);
- }
- if(puser == null && System.getProperty("virtuoso.user") != null){
- puser = System.getProperty("virtuoso.user");
- } else if(puser == null){
- puser = "dba";
- }
- if(ppwd == null && System.getProperty("virtuoso.password") != null){
- ppwd = System.getProperty("virtuoso.password");
- } else if(ppwd == null){
- ppwd = "dba";
- }
- // We set the configuration
- host = (String) phost;
- port = (Integer) pport;
- user = (String) puser;
- pwd = (String) ppwd;
-
- // Build connection string
- connStr = getConnectionString(host, port);
-
- // Check connection
- VirtuosoConnection connection = getConnection(connStr, user,
- pwd);
- logger.info("Connection to {} initialized. User is {}", connStr, user);
- // everything went ok
- connection.close();
- } catch (VirtuosoException e) {
- logger.error(
- "A problem occurred while initializing connection to Virtuoso",
- e);
- logger.error("Be sure you have configured the connection parameters correctly in the OSGi/SCR configuration");
- cCtx.disableComponent(pid);
- throw new ComponentException(e.getLocalizedMessage());
- } catch (SQLException e) {
- logger.error(
- "A problem occurred while initializing connection to Virtuoso",
- e);
- logger.error("Be sure you have configured the connection parameters correctly in the OSGi/SCR configuration");
- cCtx.disableComponent(pid);
- throw new ComponentException(e.getLocalizedMessage());
- } catch (ClassNotFoundException e) {
- logger.error(
- "A problem occurred while initializing connection to Virtuoso",
- e);
- logger.error("Be sure you have configured the connection parameters correctly in the OSGi/SCR configuration");
- cCtx.disableComponent(pid);
- throw new ComponentException(e.getLocalizedMessage());
- }
- }
- // Load remembered graphs
- Set<UriRef> remembered = readRememberedGraphs();
- for (UriRef name : remembered) {
- if (canModify(name)) {
- graphs.put(name, new VirtuosoMGraph(name.getUnicodeString(),
- createDataAccess()));
- } else {
- graphs.put(name, new VirtuosoGraph(name.getUnicodeString(),
- createDataAccess()));
- }
- }
- logger.info("Activated VirtuosoWeightedProvider.");
- }
-
- public static final String getConnectionString(String hostName,
- Integer portNumber) {
- return new StringBuilder().append("jdbc:virtuoso://").append(hostName)
- .append(":").append(portNumber).append("/CHARSET=UTF-8")
- .toString();
- }
-
- private Set<UriRef> readRememberedGraphs() {
- logger.trace(" readRememberedGraphs()");
- String SQL = "SPARQL SELECT DISTINCT ?G FROM <" + ACTIVE_GRAPHS_GRAPH
- + "> WHERE { ?G a <urn:x-virtuoso/active-graph> }";
- VirtuosoConnection connection = null;
- Exception e = null;
- VirtuosoStatement st = null;
- VirtuosoResultSet rs = null;
- Set<UriRef> remembered = new HashSet<UriRef>();
- try {
- connection = getConnection();
- st = (VirtuosoStatement) connection.createStatement();
- logger.debug("Executing SQL: {}", SQL);
- rs = (VirtuosoResultSet) st.executeQuery(SQL);
- while (rs.next()) {
- UriRef name = new UriRef(rs.getString(1));
- logger.debug(" > Graph {}", name);
- remembered.add(name);
- }
- } catch (VirtuosoException e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- } catch (SQLException e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- } catch (ClassNotFoundException e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- } finally {
-
- try {
- if (rs != null)
- rs.close();
- } catch (Exception ex) {
- }
- ;
- try {
- if (st != null)
- st.close();
- } catch (Exception ex) {
- }
- ;
- if (connection != null) {
- try {
- connection.close();
- } catch (VirtuosoException e1) {
- logger.error("Cannot close connection", e1);
- }
- }
- }
- if (e != null) {
- throw new RuntimeException(e);
- }
- return remembered;
- }
-
- private void rememberGraphs(UriRef... graphs) {
- logger.trace(" saveActiveGraphs()");
- if (graphs.length > 0) {
- // Returns the list of graphs in the virtuoso quad store
- String SQL = "SPARQL INSERT INTO <" + ACTIVE_GRAPHS_GRAPH
- + "> { `iri(??)` a <urn:x-virtuoso/active-graph> }";
- VirtuosoConnection connection = null;
- Exception e = null;
- VirtuosoPreparedStatement st = null;
- VirtuosoResultSet rs = null;
- try {
- try {
- connection = getConnection();
- connection.setAutoCommit(false);
- st = (VirtuosoPreparedStatement) connection
- .prepareStatement(SQL);
- logger.debug("Executing SQL: {}", SQL);
- for (UriRef u : graphs) {
- logger.trace(" > remembering {}", u);
- st.setString(1, u.getUnicodeString());
- st.executeUpdate();
- }
- connection.commit();
- } catch (Exception e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- connection.rollback();
- }
- } catch (SQLException e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- } finally {
- try {
- if (rs != null)
- rs.close();
- } catch (Exception ex) {
- }
- ;
- try {
- if (st != null)
- st.close();
- } catch (Exception ex) {
- }
- ;
- if (connection != null) {
- try {
- connection.close();
- } catch (VirtuosoException e1) {
- logger.error("Cannot close connection", e1);
- }
- }
- }
- if (e != null) {
- throw new RuntimeException(e);
- }
- }
- }
-
- private void forgetGraphs(UriRef... graphs) {
- logger.trace(" forgetGraphs()");
- if (graphs.length > 0) {
- // Returns the list of graphs in the virtuoso quad store
- String SQL = "SPARQL WITH <"
- + ACTIVE_GRAPHS_GRAPH
- + "> DELETE { ?s ?p ?v } WHERE { ?s ?p ?v . FILTER( ?s = iri(??) ) }";
- VirtuosoConnection connection = null;
- Exception e = null;
- VirtuosoPreparedStatement st = null;
- VirtuosoResultSet rs = null;
- try {
- try {
- connection = getConnection();
- connection.setAutoCommit(false);
- st = (VirtuosoPreparedStatement) connection
- .prepareStatement(SQL);
- logger.debug("Executing SQL: {}", SQL);
- for (UriRef u : graphs) {
- logger.trace(" > remembering {}", u);
- st.setString(1, u.getUnicodeString());
- st.executeUpdate();
- }
- connection.commit();
- } catch (Exception e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- connection.rollback();
- }
- } catch (SQLException e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- } finally {
- try {
- if (rs != null)
- rs.close();
- } catch (Exception ex) {
- }
- ;
- try {
- if (st != null)
- st.close();
- } catch (Exception ex) {
- }
- ;
- if (connection != null) {
- try {
- connection.close();
- } catch (VirtuosoException e1) {
- logger.error("Cannot close connection", e1);
- }
- }
- }
- if (e != null) {
- throw new RuntimeException(e);
- }
- }
- }
-
- /**
- * Deactivates this component.
- *
- * @param cCtx
- * component context provided by OSGi
- */
- @Deactivate
- public void deactivate(ComponentContext cCtx) {
- logger.debug("deactivate(ComponentContext {})", cCtx);
- // Save active (possibly empty) graphs to a dedicated graph
- rememberGraphs();
- // XXX Important. Close all opened resources
- for (DataAccess mg : dataAccessSet) {
- mg.close();
- }
- logger.info("Shutdown complete.");
- }
-
- public VirtuosoConnection getConnection() throws SQLException,
- ClassNotFoundException {
- return getConnection(connStr, user, pwd);
- }
-
- private VirtuosoConnection getConnection(final String connStr,final String user,
- final String pwd) throws SQLException, ClassNotFoundException {
- logger.debug("getConnection(String {}, String {}, String *******)",
- connStr, user);
- /**
- * FIXME For some reasons, it looks the DriverManager is instantiating a
- * new virtuoso.jdbc4.Driver instance upon any activation. (Enable DEBUG
- * to see this)
- */
- logger.debug("Loading JDBC Driver");
- try {
- VirtuosoConnection c = AccessController
- .doPrivileged(new PrivilegedAction<VirtuosoConnection>() {
- public VirtuosoConnection run() {
- try {
- Class.forName(VirtuosoWeightedProvider.DRIVER,
- true, this.getClass().getClassLoader());
- return (VirtuosoConnection) DriverManager
- .getConnection(connStr, user, pwd);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
- });
- c.setAutoCommit(true);
- return c;
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Retrieves the Graph (unmodifiable) with the given UriRef If no graph
- * exists with such name, throws a NoSuchEntityException
- */
- @Override
- public Graph getGraph(UriRef name) throws NoSuchEntityException {
- logger.debug("getGraph(UriRef {}) ", name);
- // If it is read-only, returns the Graph
- // If it is not read-only, returns the getGraph() version of the MGraph
- VirtuosoMGraph g = loadGraphOnce(name);
- if (g instanceof Graph) {
- return (Graph) g;
- } else {
- return g.getGraph();
- }
- }
-
- /**
- * Retrieves the MGraph (modifiable) with the given UriRef. If no graph
- * exists with such name, throws a NoSuchEntityException.
- *
- * @return mgraph
- */
- @Override
- public MGraph getMGraph(UriRef name) throws NoSuchEntityException {
- logger.debug("getMGraph(UriRef {}) ", name);
- VirtuosoMGraph g = loadGraphOnce(name);
- if (g instanceof Graph) {
- // We have this graph but only in read-only mode!
- throw new NoSuchEntityException(name);
- }
- return g;
- }
-
- /**
- * Load the graph once. It check whether a graph object have been already
- * created for that UriRef, if yes returns it.
- *
- * If not check if at least 1 triple is present in the quad for such graph
- * identifier. If yes, creates a new graph object and loads it in the map,
- * referring to it on next calls.
- *
- * This method returns a VirtuosoGraph if the graph is read-only
- *
- * @param name
- * @return
- */
- private VirtuosoMGraph loadGraphOnce(UriRef name) {
- logger.debug("loadGraphOnce({})", name);
-
- // Check whether the graph have been already loaded once
- if (graphs.containsKey(name)) {
- logger.debug("{} is already loaded", name);
- return graphs.get(name);
- } else {
- VirtuosoMGraph graph = null;
- logger.debug("Attempt to load {}", name);
- // Let's create the graph object
- String SQL = "SPARQL SELECT ?G WHERE { GRAPH ?G {[] [] []} . FILTER(?G = "
- + name + ")} LIMIT 1";
-
- Statement st = null;
- VirtuosoResultSet rs = null;
- VirtuosoConnection connection = null;
- Exception e = null;
- try {
- connection = getConnection(connStr, user, pwd);
- st = connection.createStatement();
- logger.debug("Executing SQL: {}", SQL);
- st.execute(SQL);
- rs = (VirtuosoResultSet) st.getResultSet();
- if (rs.next() == false) {
- // The graph is empty, it is not readable or does not exists
- logger.debug("Graph does not exists: {}", name);
- throw new NoSuchEntityException(name);
- } else {
- // The graph exists and it is readable ...
- logger.trace("Graph {} is readable", name);
- // is it writable?
- logger.trace("Is {} writable?", name);
- if (canModify(name)) {
- logger.trace("Creating writable graph {}",
- name);
- graphs.put(name,
- new VirtuosoMGraph(name.getUnicodeString(),
- createDataAccess()));
- } else {
- logger.trace("Creating read-only graph {}",
- name);
- graphs.put(name,
- new VirtuosoMGraph(name.getUnicodeString(),
- createDataAccess()).asVirtuosoGraph());
- }
- graph = graphs.get(name);
- }
-
- } catch (VirtuosoException ve) {
- logger.error("Error while executing query/connection.", ve);
- e = ve;
- } catch (SQLException se) {
- logger.error("Error while executing query/connection.", se);
- e = se;
- } catch (ClassNotFoundException ce) {
- logger.error("Error while executing query/connection.", ce);
- e = ce;
- } finally {
- try {
- if (rs != null)
- rs.close();
- } catch (Exception ex) {
- }
- ;
- try {
- if (st != null)
- st.close();
- } catch (Exception ex) {
- }
- ;
- if (connection != null) {
- try {
- connection.close();
- } catch (VirtuosoException e1) {
- logger.error("Cannot close connection", e1);
- }
- }
- }
- if (e != null) {
- throw new RuntimeException(e);
- }
- return graph;
- }
-
- }
-
- public DataAccess createDataAccess() {
- DataAccess da = new DataAccess(connStr, user, pwd);
- dataAccessSet.add(da);
- // Remember all opened ones
- return da;
- }
-
- /**
- * Generic implementation of the get(M)Graph method. If the named graph is
- * modifiable, behaves the same as getMGraph(UriRef name), elsewhere,
- * behaves as getGraph(UriRef name)
- */
- @Override
- public TripleCollection getTriples(UriRef name)
- throws NoSuchEntityException {
- logger.debug("getTriples(UriRef {}) ", name);
- return loadGraphOnce(name);
- }
-
- /**
- * Returns the list of graphs in the virtuoso quad store. The returned set
- * is unmodifiable.
- *
- * @return graphs
- */
- @Override
- public Set<UriRef> listGraphs() {
- logger.debug("listGraphs()");
- Set<UriRef> graphs = new HashSet<UriRef>();
- // XXX Add the active (possibly empty) mgraphs
- graphs.addAll(this.graphs.keySet());
- // Returns the list of graphs in the virtuoso quad store
- String SQL = "SPARQL SELECT DISTINCT ?G WHERE {GRAPH ?G {[] [] []} }";
- VirtuosoConnection connection = null;
- Exception e = null;
- VirtuosoStatement st = null;
- VirtuosoResultSet rs = null;
- try {
- connection = getConnection();
- st = (VirtuosoStatement) connection.createStatement();
- logger.debug("Executing SQL: {}", SQL);
- rs = (VirtuosoResultSet) st.executeQuery(SQL);
- while (rs.next()) {
- UriRef graph = new UriRef(rs.getString(1));
- logger.debug(" > Graph {}", graph);
- graphs.add(graph);
- }
- } catch (VirtuosoException e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- } catch (SQLException e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- } catch (ClassNotFoundException e1) {
- logger.error("Error while executing query/connection.", e1);
- e = e1;
- } finally {
-
- try {
- if (rs != null)
- rs.close();
- } catch (Exception ex) {
- }
- ;
- try {
- if (st != null)
- st.close();
- } catch (Exception ex) {
- }
- ;
- if (connection != null) {
- try {
- connection.close();
- } catch (VirtuosoException e1) {
- logger.error("Cannot close connection", e1);
- }
- }
- }
- if (e != null) {
- throw new RuntimeException(e);
- }
- return Collections.unmodifiableSet(graphs);
- }
-
- @Override
- public Set<UriRef> listMGraphs() {
- logger.debug("listMGraphs()");
- Set<UriRef> graphs = listGraphs();
- Set<UriRef> mgraphs = new HashSet<UriRef>();
- logger.debug("Modifiable graphs:");
- for (UriRef u : graphs) {
- if (canModify(u)) {
- logger.debug(" > {}", u);
- mgraphs.add(u);
- }
- }
- return Collections.unmodifiableSet(mgraphs);
- }
-
- private long getPermissions(String graph) {
- VirtuosoConnection connection = null;
- ResultSet rs = null;
- Statement st = null;
- logger.debug("getPermissions(String {})", graph);
- Exception e = null;
- Long result = null;
- try {
- connection = getConnection();
- String sql = "SELECT DB.DBA.RDF_GRAPH_USER_PERMS_GET ('" + graph
- + "','" + connection.getMetaData().getUserName() + "') ";
- logger.debug("Executing SQL: {}", sql);
- st = connection.createStatement();
- st.execute(sql);
- rs = st.getResultSet();
- rs.next();
- result = rs.getLong(1);
- logger.debug("Permission: {}", result);
- } catch (VirtuosoException ve) {
- logger.error("A virtuoso SQL exception occurred.");
- e = ve;
- } catch (SQLException se) {
- logger.error("An SQL exception occurred.");
- e = se;
- } catch (ClassNotFoundException e1) {
- logger.error("An ClassNotFoundException occurred.");
- e = e1;
- } finally {
- try {
- if (rs != null)
- rs.close();
- } catch (Exception ex) {
- }
- ;
- try {
- if (st != null)
- st.close();
- } catch (Exception ex) {
- }
- ;
- if (connection != null) {
- try {
- connection.close();
- } catch (VirtuosoException e1) {
- logger.error("Cannot close connection", e1);
- }
- }
- }
- if (e != null) {
- throw new RuntimeException(e);
- }
- return result;
- }
-
- public boolean canRead(UriRef graph) {
- logger.debug("canRead(UriRef {})", graph);
- return (isRead(getPermissions(graph.getUnicodeString())));
- }
-
- public boolean canModify(UriRef graph) {
- logger.debug("canModify(UriRef {})", graph);
- return (isWrite(getPermissions(graph.getUnicodeString())));
- }
-
- private boolean testPermission(long value, int bit) {
- logger.debug("testPermission(long {},int {})", value, bit);
- return BigInteger.valueOf(value).testBit(bit);
- }
-
- private boolean isRead(long permission) {
- logger.debug("isRead(long {})", permission);
- return testPermission(permission, 1);
- }
-
- private boolean isWrite(long permission) {
- logger.debug("isWrite(long {})", permission);
- return testPermission(permission, 2);
- }
-
- @Override
- public Set<UriRef> listTripleCollections() {
- logger.debug("listTripleCollections()");
- // I think this should behave the same as listGraphs() in our case.
- return listGraphs();
- }
-
- private VirtuosoMGraph createVirtuosoMGraph(UriRef name)
- throws UnsupportedOperationException, EntityAlreadyExistsException {
- logger.debug("createVirtuosoMGraph(UriRef {})", name);
- // If the graph already exists, we throw an exception
- try {
- loadGraphOnce(name);
- throw new EntityAlreadyExistsException(name);
- } catch (NoSuchEntityException nsee) {
- if (canModify(name)) {
- graphs.put(name, new VirtuosoMGraph(name.getUnicodeString(),
- createDataAccess()));
- rememberGraphs(name);
- return graphs.get(name);
- } else {
- logger.error("Cannot create MGraph {}", name);
- throw new UnsupportedOperationException();
- }
- }
- }
-
- /**
- * Creates an initially empty MGraph. If the name already exists in the
- * store, throws an {@see EntityAlreadyExistsException}
- */
- @Override
- public MGraph createMGraph(UriRef name)
- throws UnsupportedOperationException, EntityAlreadyExistsException {
- logger.debug("createMGraph(UriRef {})", name);
- return createVirtuosoMGraph(name);
- }
-
- /**
- * Creates a new graph with the given triples, then returns the readable
- * (not modifiable) version of the graph
- *
- */
- @Override
- public Graph createGraph(UriRef name, TripleCollection triples)
- throws UnsupportedOperationException, EntityAlreadyExistsException {
- logger.debug("createGraph(UriRef {}, TripleCollection {})", name,
- triples);
- VirtuosoMGraph mgraph = createVirtuosoMGraph(name);
- mgraph.addAll(triples);
- return mgraph.getGraph();
- }
-
- /**
- * Clears the given graph and removes it from the loaded graphs.
- *
- */
- @Override
- public void deleteTripleCollection(UriRef name)
- throws UnsupportedOperationException, NoSuchEntityException,
- EntityUndeletableException {
- logger.debug("deleteTripleCollection(UriRef {})", name);
- TripleCollection g = (VirtuosoMGraph) getTriples(name);
- if (g instanceof Graph) {
- throw new EntityUndeletableException(name);
- } else {
- ((MGraph) g).clear();
- graphs.remove(name);
- forgetGraphs(name);
- }
- }
-
- /**
- * Returns the names of a graph. Personally don't know why a graph should
- * have more then 1 identifier. Anyway, this does not happen with Virtuoso
- *
- * @return names
- */
- @Override
- public Set<UriRef> getNames(Graph graph) {
- logger.debug("getNames(Graph {})", graph);
- return Collections.singleton(new UriRef(((VirtuosoMGraph) graph)
- .getName()));
- }
-
- /**
- * Returns the weight of this provider.
- *
- */
- @Override
- public int getWeight() {
- logger.debug("getWeight()");
- /**
- * The weight
- */
- return this.weight;
- }
-
- /**
- * Sets the weight
- *
- * @param weight
- */
- public void setWeight(int weight) {
- logger.debug("setWeight(int {})", weight);
- this.weight = weight;
- }
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.access.WeightedTcProvider
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.access.WeightedTcProvider b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.access.WeightedTcProvider
deleted file mode 100644
index bfb2afc..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/resources/META-INF/services/org.apache.clerezza.rdf.core.access.WeightedTcProvider
+++ /dev/null
@@ -1 +0,0 @@
-rdf.virtuoso.storage.access.VirtuosoWeightedProvider
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/resources/log4j.properties b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/resources/log4j.properties
deleted file mode 100644
index 201aca8..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,5 +0,0 @@
-#log4j.rootLogger=DEBUG, S
-#log4j.appender.S = org.apache.log4j.ConsoleAppender
-#log4j.appender.S.layout = org.apache.log4j.PatternLayout
-#log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
-
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/.DS_Store
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/.DS_Store b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/.DS_Store
deleted file mode 100644
index 353ff0a..0000000
Binary files a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/.DS_Store and /dev/null differ
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/.DS_Store
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/.DS_Store b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/.DS_Store
deleted file mode 100644
index 88ced45..0000000
Binary files a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/.DS_Store and /dev/null differ
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ConnectionTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ConnectionTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ConnectionTest.java
deleted file mode 100644
index 6a1e4b5..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ConnectionTest.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.sql.DatabaseMetaData;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Map.Entry;
-import java.util.Properties;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import virtuoso.jdbc4.VirtuosoConnection;
-import virtuoso.jdbc4.VirtuosoException;
-
-/**
- * Tests the connection to the Virtuoso DBMS
- *
- * @author enridaga
- */
-public class ConnectionTest {
-
- static final Logger log = LoggerFactory.getLogger(ConnectionTest.class);
-
- private static VirtuosoConnection connection = null;
-
- @BeforeClass
- public static void before() throws ClassNotFoundException, SQLException {
- org.junit.Assume.assumeTrue(!TestUtils.SKIP);
- connection = TestUtils.getConnection();
- }
-
- @Test
- public void testIsClosed() {
- assertFalse(connection.isClosed());
- }
-
- @Test
- public void testIsConnectionLost() {
- assertFalse(connection.isConnectionLost(0));
- }
-
- @Test
- public void testIsReadOnly() throws VirtuosoException {
- assertFalse(connection.isReadOnly());
- }
-
- @Test
- public void testConnection() {
- log.info("testConnection()");
- try {
-
- Statement st = connection.createStatement();
- log.debug("Populate graph <mytest>");
- String[] queries = {
- "sparql clear graph <mytest>",
- "sparql insert into graph <mytest> { <xxx> <P01> \"test1\"@en }",
- "sparql insert into graph <mytest> { <xxx> <P01> \"test2\"@it }",
- "sparql PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> insert into graph <mytest> { <xxx> <P01> \"test3\"^^xsd:string }",
- "sparql insert into graph <mytest> { <xxx> <P01> \"test4\" }",
- "sparql insert into graph <mytest> { <xxx> <P01> \"test5\" . <xxx> <P02> _:b1"
- + " . _:b1 <P03> <yyy> " + " . _:b3 <P05> <zzz> "
- + " . _:b3 <P05> <ppp> " +
- // This is to consider that we can force it
- " . <nodeID://b10005> <P05> <ooo> " + " }",
- "sparql insert into graph <mytest> { <nodeID://b10005> <property> <nodeID://b10007>}",
- "sparql insert into graph <mytest> { <enridaga> <property> \"Literal value\"^^<http://datatype#type>}",
- "sparql insert into graph <mytest> { <nodeID://b10005> <property> <nodeID://b10007>}" };
- for (String q : queries) {
- log.debug("Querying: {}", q);
- st.execute(q);
- }
-
- String query = "sparql SELECT * from <mytest> WHERE {?s ?p ?o}";
- log.debug("Querying: {}", query);
- ResultSet rs = st.executeQuery(query);
- TestUtils.stamp(rs);
- } catch (SQLException e) {
- log.error("SQL ERROR: ", e);
- assertTrue(false);
- } catch (Exception e) {
- log.error("SQL ERROR: ", e);
- assertTrue(false);
- }
- }
-
- @Test
- public void test() throws ClassNotFoundException, SQLException {
- DatabaseMetaData dm = connection.getMetaData();
- log.debug("Username is {}", dm.getUserName());
- Properties p = connection.getClientInfo();
- if (p == null) {
- log.warn("Client info is null...");
- } else
- for (Entry<Object, Object> e : p.entrySet()) {
- log.info("Client info property: {} => {}", e.getKey(),
- e.getValue());
- }
- String SQL = "SELECT DISTINCT id_to_iri(G) FROM DB.DBA.RDF_QUAD quad ";
- VirtuosoConnection cn = TestUtils.getConnection();
- long startAt = System.currentTimeMillis();
- // get the list of quad using SQL
- log.debug("Executing SQL: {}", SQL);
- cn.createStatement().executeQuery(SQL);
- long endAt = System.currentTimeMillis();
- log.debug("Using SQL: {}ms", endAt - startAt);
- SQL = "SPARQL SELECT DISTINCT ?G WHERE {GRAPH ?G {?S ?P ?O} }";
- startAt = System.currentTimeMillis();
- // get the list of quad using SQL+SPARQL
- log.debug("Executing SQL: {}", SQL);
- cn.createStatement().executeQuery(SQL);
- endAt = System.currentTimeMillis();
- log.debug("Using SQL+SPARQL: {}ms", endAt - startAt);
- }
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/RdfIOTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/RdfIOTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/RdfIOTest.java
deleted file mode 100644
index 7221c9b..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/RdfIOTest.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import java.io.IOException;
-import java.net.URL;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Iterator;
-
-import org.apache.clerezza.platform.config.SystemConfig;
-import org.apache.clerezza.rdf.core.BNode;
-import org.apache.clerezza.rdf.core.MGraph;
-import org.apache.clerezza.rdf.core.NonLiteral;
-import org.apache.clerezza.rdf.core.Resource;
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.core.TypedLiteral;
-import org.apache.clerezza.rdf.core.UriRef;
-import org.apache.clerezza.rdf.core.impl.TripleImpl;
-import org.apache.clerezza.rdf.core.impl.TypedLiteralImpl;
-import org.apache.clerezza.rdf.core.serializedform.ParsingProvider;
-import org.apache.clerezza.rdf.core.serializedform.SupportedFormat;
-import org.apache.clerezza.rdf.jena.parser.JenaParserProvider;
-import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoBNode;
-import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoMGraph;
-import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import virtuoso.jdbc4.VirtuosoException;
-
-public class RdfIOTest {
- static VirtuosoMGraph mgraph = null;
- static final String TEST_GRAPH_NAME = "RdfIOTest";
- static final String XSD = "http://www.w3.org/2001/XMLSchema#";
- static Logger log = LoggerFactory.getLogger(RdfIOTest.class);
- static DataAccess da;
-
- @BeforeClass
- public static void assume(){
- org.junit.Assume.assumeTrue(!TestUtils.SKIP);
- }
-
- /**
- * Clean before any test
- *
- * @throws ClassNotFoundException
- * @throws SQLException
- */
- @Before
- public void before() throws ClassNotFoundException, SQLException {
-
- da = TestUtils.getProvider().createDataAccess();
- mgraph = new VirtuosoMGraph(TEST_GRAPH_NAME, da);
- mgraph.clear();
- log.debug("Clearing graph <{}>", TEST_GRAPH_NAME);
- }
-
- /**
- * Clean after a test
- *
- * @throws VirtuosoException
- * @throws ClassNotFoundException
- * @throws SQLException
- */
- @After
- public void clear() throws VirtuosoException, ClassNotFoundException,
- SQLException {
- log.debug("Clearing graph <{}> of size {}", TEST_GRAPH_NAME,
- mgraph.size());
- // clear all resources
- da.close();
-
- da = null;
- mgraph = null;
-
- log.debug("Removing graph <{}>", TEST_GRAPH_NAME);
- Statement st = TestUtils.getConnection().createStatement();
- st.execute("SPARQL CLEAR GRAPH <" + TEST_GRAPH_NAME + ">");
- st.close();
- }
-
- @Test
- public void xsdString() throws ClassNotFoundException, SQLException {
- log.info("Text an xsd:string");
- TypedLiteral object = new TypedLiteralImpl("lorem ipsum", new UriRef(
- XSD + "string"));
- UriRef subject = new UriRef("urn:io-test:reto");
- UriRef predicate = new UriRef("urn:io-test:hasText");
-
- Triple read = writeAndRead(subject, predicate, object);
- Assert.assertTrue(read
- .equals(new TripleImpl(subject, predicate, object)));
- Assert.assertTrue(read.getObject() instanceof TypedLiteral);
- TypedLiteral l = (TypedLiteral) read.getObject();
- Assert.assertEquals(l.getLexicalForm(), "lorem ipsum");
- Assert.assertEquals(l.getDataType(), new UriRef(XSD + "string"));
-
- }
-
- @Test
- public void longString() throws ClassNotFoundException, SQLException, InterruptedException {
- log.info("Test a long xsd:string");
- StringBuilder longStr = new StringBuilder();
- int c = 250000;
- while (c > 0) {
- longStr.append(" lorem ipsum ");
- c--;
- }
- int size = longStr.length();
- TypedLiteral object = new TypedLiteralImpl(longStr.toString(),
- new UriRef(XSD + "string"));
- UriRef subject = new UriRef("urn:io-test:reto");
- UriRef predicate = new UriRef("urn:io-test:hasText");
- Triple read = writeAndRead(subject, predicate, object);
- Assert.assertTrue(read
- .equals(new TripleImpl(subject, predicate, object)));
- Assert.assertTrue(read.getObject() instanceof TypedLiteral);
- TypedLiteral l = (TypedLiteral) read.getObject();
- Assert.assertEquals(l.getDataType(), new UriRef(XSD + "string"));
- Assert.assertTrue(l.getLexicalForm().length() == size);
- }
-
- private Triple writeAndRead(NonLiteral subject, UriRef predicate,
- Resource object) throws ClassNotFoundException, SQLException {
- Triple t = new TripleImpl(subject, predicate, object);
- mgraph.add(t);
- Triple read = mgraph.getGraph().iterator().next();
- return read;
- }
-
- @Test
- public void subjectAsUriTest() throws ClassNotFoundException, SQLException {
- log.info("Test subject as UriRef");
-
- NonLiteral subject;
- UriRef predicate = new UriRef("urn:io-test:predicate");
- UriRef object = new UriRef("urn:io-test:object");
-
- // subject may be UriRef
- subject = new UriRef("urn:io-test:enridaga");
- Triple read = writeAndRead(subject, predicate, object);
- Assert.assertTrue(read.getSubject().equals(subject));
- Assert.assertEquals(read.getSubject(), new UriRef(
- "urn:io-test:enridaga"));
- Assert.assertNotSame(read.getSubject(), new UriRef(
- "urn:io-test:alexdma"));
- Assert.assertEquals(read, new TripleImpl(subject, predicate, object));
-
- }
-
- @Test
- public void subjectAsBnodeTest() throws ClassNotFoundException,
- SQLException {
- log.info("Test subject as BNode");
-
- NonLiteral subject;
- UriRef predicate = new UriRef("urn:io-test:predicate");
- UriRef object = new UriRef("urn:io-test:object");
-
- // subject may be BNode
- subject = new BNode();
- Triple read = writeAndRead(subject, predicate, object);
- // bnodes cannot be equals!
- Assert.assertFalse(read.getSubject().equals(subject));
- Assert.assertTrue(read.getSubject() instanceof BNode);
- Assert.assertNotSame(read.getSubject(), new UriRef(
- "urn:io-test:enridaga"));
- Assert.assertNotSame(read.getSubject(), new UriRef(
- "urn:io-test:alexdma"));
- // bnodes cannot be equals!
- Assert.assertNotSame(read, new TripleImpl(subject, predicate, object));
- }
-
- @Test
- public void objectAsUriTest() throws ClassNotFoundException, SQLException {
- log.info("Test object as UriRef");
-
- NonLiteral subject = new UriRef("urn:io-test:enridaga");
- UriRef predicate = new UriRef("urn:io-test:predicate");
- UriRef object = new UriRef("urn:io-test:object");
-
- Triple read = writeAndRead(subject, predicate, object);
- //
- Assert.assertTrue(read.getObject().equals(object));
- Assert.assertTrue(read.getObject() instanceof UriRef);
- Assert.assertEquals(read.getObject(), new UriRef("urn:io-test:object"));
- Assert.assertNotSame(read.getSubject(), new UriRef(
- "urn:io-test:alexdma"));
- Assert.assertEquals(read, new TripleImpl(subject, predicate, object));
- }
-
- @Test
- public void objectAsBnodeTest() throws ClassNotFoundException, SQLException {
- log.info("Test object as Bnode");
-
- NonLiteral subject = new UriRef("urn:io-test:subject");
- UriRef predicate = new UriRef("urn:io-test:predicate");
- Resource object;
-
- // subject may be BNode
- object = new BNode();
- Triple read = writeAndRead(subject, predicate, object);
- // bnodes cannot be equals!
- Assert.assertFalse(read.getObject().equals(object));
- Assert.assertTrue(read.getSubject().equals(subject));
-
- Assert.assertTrue(read.getObject() instanceof BNode);
- Assert.assertTrue(read.getObject() instanceof VirtuosoBNode);
-
- Assert.assertNotSame(read.getObject(), new UriRef(
- "urn:io-test:enridaga"));
- Assert.assertNotSame(read.getObject(),
- new UriRef("urn:io-test:alexdma"));
- // these bnodes cannot be equals!
- Assert.assertNotSame(read, new TripleImpl(subject, predicate, object));
- }
-
- @Test
- public void bnodesTest() throws ClassNotFoundException, SQLException {
- log.info("Test iterations and filter with bnode");
-
- NonLiteral s1 = new BNode();
- NonLiteral s2 = new BNode();
- NonLiteral s3 = new BNode();
- NonLiteral s4 = new BNode();
-
- UriRef p1 = new UriRef("p1");
- UriRef p2 = new UriRef("p2");
- UriRef p3 = new UriRef("p3");
-
- mgraph.add(new TripleImpl(s1, p1, s2));
- // Get the bnode of s1
- Triple first = mgraph.filter(null, p1, null).next();
-
- Assert.assertTrue(first.getSubject() instanceof VirtuosoBNode);
- Assert.assertTrue(first.getObject() instanceof VirtuosoBNode);
-
- BNode s1intern = (BNode) first.getSubject();
- BNode s2intern = (BNode) first.getObject();
-
- mgraph.add(new TripleImpl(s2intern, p1, s3));
- Triple second = mgraph.filter(s2intern, p1, null).next();
- Assert.assertTrue(second.getObject() instanceof VirtuosoBNode);
-
- mgraph.add(new TripleImpl(s1intern, p2, s4));
- Triple third = mgraph.filter(s1intern, p2, null).next();
- Assert.assertTrue(third.getObject() instanceof VirtuosoBNode);
- BNode s4intern = (BNode) third.getObject();
-
- mgraph.add(new TripleImpl(s1intern, p2, s4intern));
- mgraph.add(new TripleImpl(s4intern, p3, s1intern));
-
- Iterator<Triple> all = mgraph.iterator();
- while(all.hasNext()){
- Triple l = all.next();
- log.info("{} {} {}",new Object[]{ l.getSubject(), l.getPredicate(), l.getObject()});
- }
- Iterator<Triple> i = mgraph.filter(null, p2, null);
- int n = 0;
- while (i.hasNext()) {
- n++;
- Triple s1t = i.next();
- Iterator<Triple> s1i = mgraph.filter(s1t.getSubject(), null, null);
- boolean found = false;
- while (s1i.hasNext()) {
- Triple s1it = s1i.next();
- found = true;
- log.info("{} {}",s1it.getSubject(), s1t.getSubject());
- Assert.assertTrue(s1it.getSubject().equals(s1t.getSubject()));
- Assert.assertTrue(s1it.getPredicate().equals(p1)
- || s1it.getPredicate().equals(p2));
-
- }
- Assert.assertTrue(found);
- Assert.assertTrue(s1t.getObject() instanceof VirtuosoBNode);
- Assert.assertTrue(s1t.getSubject() instanceof VirtuosoBNode);
- Iterator<Triple> s4i = mgraph.filter((NonLiteral) s1t.getObject(),
- null, null);
- log.info("s4 {} ",s1t.getObject());
- while (s4i.hasNext()) {
- Triple s4it = s4i.next();
- log.info("{} {}",s4it.getSubject(), s1t.getObject());
- Assert.assertTrue(s4it.getSubject().equals(s1t.getObject()));
- Assert.assertTrue(s4it.getPredicate().equals(p3));
- }
- }
- Assert.assertEquals(n, 1);
-
- }
-
- @Test
- public void sysconfigTest(){
-
- SystemConfig sc = new SystemConfig();
- MGraph systemGraph = mgraph;
- URL config = sc.getClass().getResource(SystemConfig.CONFIG_FILE);
- if (config == null) {
- throw new RuntimeException("no config file found");
- }
- ParsingProvider parser = new JenaParserProvider();
- try {
- parser.parse(systemGraph, config.openStream(),
- SupportedFormat.RDF_XML, null);
- } catch (IOException ex) {
- log.warn("Cannot parse coniguration at URL: {}", config);
- throw new RuntimeException(ex);
- }
- }
-
- @Test
- public void testUnicodeChars() throws ClassNotFoundException, SQLException {
- log.info("Text an xsd:string");
-
- String s = "lorem ipsum è é £ ò ç à ù β ät ü ä";
- TypedLiteral object = new TypedLiteralImpl(s, new UriRef(
- XSD + "string"));
- UriRef subject = new UriRef("urn:io-test:reto");
- UriRef predicate = new UriRef("urn:io-test:hasText");
-
- Triple read = writeAndRead(subject, predicate, object);
- log.info("o: {} :: {}", object, read.getObject());
- Assert.assertTrue(read
- .equals(new TripleImpl(subject, predicate, object)));
- Assert.assertTrue(read.getObject() instanceof TypedLiteral);
- TypedLiteral l = (TypedLiteral) read.getObject();
- Assert.assertEquals(l.getLexicalForm(), s);
- Assert.assertEquals(l.getDataType(), new UriRef(XSD + "string"));
-
- }
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/TestUtils.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/TestUtils.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/TestUtils.java
deleted file mode 100644
index e96d62b..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/TestUtils.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.virtuoso.storage.access.VirtuosoWeightedProvider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import virtuoso.jdbc4.VirtuosoConnection;
-import virtuoso.jdbc4.VirtuosoExtendedString;
-import virtuoso.jdbc4.VirtuosoRdfBox;
-import virtuoso.jdbc4.VirtuosoResultSet;
-
-/**
- * Utilities for tests
- *
- * @author enridaga
- *
- */
-public class TestUtils {
-
- public static final String FOAF_NS = "http://xmlns.com/foaf/0.1/";
-
- private static VirtuosoWeightedProvider provider = null;
- private static String jdbcConnectionString = null;
- private static String jdbcUser = null;
- private static String jdbcPassword = null;
- private static String jdbcDriver = null;
-
- static Logger log = LoggerFactory.getLogger(TestUtils.class);
- public static boolean SKIP = false;
- static {
- String skipProperty = System.getProperty("virtuoso.test");
- if (skipProperty == null) {
- log.info("virtuoso.skip property is not set. We skip tests by default.");
- SKIP = true;
- } else
- SKIP = !skipProperty.equals("true");
- }
-
- public static VirtuosoConnection getConnection() throws SQLException, ClassNotFoundException{
- return getProvider().getConnection();
- }
- public static VirtuosoWeightedProvider getProvider()
- throws ClassNotFoundException, SQLException {
- if (provider == null) {
- initProvider();
- }
- return provider;
- }
-
- private static void initProvider() throws ClassNotFoundException,
- SQLException {
- if (SKIP) {
- log.warn("Skipping tests.");
- return;
- }
- String host = System.getProperty("virtuoso.host");
- String port = System.getProperty("virtuoso.port");
- jdbcUser = System.getProperty("virtuoso.user");
- jdbcPassword = System.getProperty("virtuoso.password");
- jdbcDriver = System.getProperty("virtuoso.driver");
- if (host == null) {
- host = "localhost";
- log.info("Missing param 'host', setting to default: {}", host);
- }
- if (port == null) {
- port = "1111";
- log.info("Missing param 'port', setting to default: {}", port);
- }
- if (jdbcUser == null) {
- jdbcUser = "dba";
- log.info("Missing param 'user', setting to default: {}", jdbcUser);
- }
- if (jdbcPassword == null) {
- jdbcPassword = "dba";
- log.info("Missing param 'password', setting to default: {}",
- jdbcPassword);
- }
- if (jdbcDriver == null) {
- jdbcDriver = "virtuoso.jdbc4.Driver";
- log.info("Missing param 'password', setting to default: {}",
- jdbcDriver);
- }
-
- StringBuilder cb = new StringBuilder();
- cb.append("jdbc:virtuoso://");
- cb.append(host);
- cb.append(":");
- cb.append(port).append("/CHARSET=UTF-8");
- jdbcConnectionString = cb.toString();
-// Class.forName(VirtuosoWeightedProvider.DRIVER);
- log.info("Create provider");
-// connection = (VirtuosoConnection) DriverManager.getConnection(
-// jdbcConnectionString, jdbcUser, jdbcPassword);
- provider = new VirtuosoWeightedProvider(jdbcConnectionString, jdbcUser, jdbcPassword);
- log.debug("Connection URL: {}", jdbcConnectionString);
- log.debug("Connection user: {}", jdbcUser);
- }
-
- public static void stamp(ResultSet rs) {
- try {
- ResultSetMetaData rsmd;
-
- StringBuilder output = new StringBuilder();
- output.append(System.getProperty("line.separator"));
- output.append("------------------------------");
- output.append(System.getProperty("line.separator"));
- rsmd = rs.getMetaData();
-
- while (rs.next()) {
- for (int i = 1; i <= rsmd.getColumnCount(); i++) {
- String s = rs.getString(i);
- Object o = ((VirtuosoResultSet) rs).getObject(i);
- if (o instanceof VirtuosoExtendedString) {
- // In case is IRI
- VirtuosoExtendedString vs = (VirtuosoExtendedString) o;
- if (vs.iriType == VirtuosoExtendedString.IRI
- && (vs.strType & 0x01) == 0x01) {
- output.append(" <" + vs.str + "> ");
- log.debug(" {} is IRI", vs.str);
- } else if (vs.iriType == VirtuosoExtendedString.BNODE) {
- log.debug(" {} is BNODE", vs.str);
- output.append(" <" + vs.str + "> ");
- } else {
- // In case is untyped literal
- log.debug(" {} is an untyped literal", vs.str);
- output.append(vs.str);
- }
- } else if (o instanceof VirtuosoRdfBox) {
- // In case is typed literal
- VirtuosoRdfBox rb = (VirtuosoRdfBox) o;
- output.append(rb.rb_box + " lang=" + rb.getLang()
- + " type=" + rb.getType());
- log.debug(" {} is an typed literal", rb.rb_box);
-
- } else if (rs.wasNull()) {
- log.debug(" NULL ");
- output.append("NULL");
- } else {
- // Is simple untyped string
- output.append(s);
- }
-
- }
- output.append("\n");
- }
-
- output.append(System.getProperty("line.separator"));
- output.append("------------------------------");
- output.append(System.getProperty("line.separator"));
- log.info(output.toString());
- } catch (Exception e) {
- log.error("ERROR", e);
- }
- }
-
- public static void stamp(Triple next) {
- log.info("> TRIPLE : "+next.getSubject().toString() + " "
- + next.getPredicate().toString() + " "
- + next.getObject().toString());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ThreadSafetyTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ThreadSafetyTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ThreadSafetyTest.java
deleted file mode 100644
index fb418ab..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/ThreadSafetyTest.java
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.core.UriRef;
-import org.apache.clerezza.rdf.core.impl.TripleImpl;
-import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoMGraph;
-import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/**
- *
- * Credit: This code is largely cloned by the thread safe test in
- * {@see org.apache.clerezza.rdf.sesame.storage.ThreadSafetyTest}
- *
- * @author enridaga
- *
- */
-public class ThreadSafetyTest {
-
- private ExecutorService executor;
- private VirtuosoMGraph mgraph;
- private DataAccess da = null;
- static Logger log = LoggerFactory.getLogger(ThreadSafetyTest.class);
-
- @BeforeClass
- public static void assume(){
- org.junit.Assume.assumeTrue(!TestUtils.SKIP);
- }
-
- @Before
- public void setUp() throws Exception {
-
- da = TestUtils.getProvider().createDataAccess();
- da.clearGraph("ThreadSafetyTest");
- mgraph = new VirtuosoMGraph("ThreadSafetyTest",
- da);
- mgraph.clear();
- executor = Executors.newCachedThreadPool();
- }
-
- @After
- public void tearDown() throws Exception {
- try {
- executor.shutdown();
- if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
- fail("Timeout while waiting for termination");
- }
- } finally {
- mgraph.clear();
- mgraph = null;
- da.close();
- da = null;
- }
- }
-
- @Test
- public void testProduceFirstAndThenConsume() throws Exception {
- log.info("testProduceFirstAndThenConsume()");
- // Produce first...
- Future<Result> fp = executor.submit(new Producer("A", 100));
- fp.get().assertResult();
-
- // ...and then consume
- Future<Result> fc = executor.submit(new Consumer("A", 100));
- fc.get().assertResult();
- Iterator<Triple> it = mgraph.iterator();
- while (it.hasNext()) {
- TestUtils.stamp(it.next());
- }
- // test graph size
- assertEquals(0, mgraph.size());
- }
-
- @Test
- public void testProduceAndConsumeSingle() throws Exception {
- log.info("testProduceAndConsumeSingle()");
- List<Task> tasks = Arrays.asList(
- new Consumer("A", 100), new Producer("A", 100));
- List<Future<Result>> futures = executor.invokeAll(tasks);
- for (Future<Result> future : futures) {
- future.get().assertResult();
- }
- assertEquals(0, mgraph.size());
- }
-
- @Test
- public void testProduceAndConsumeMultiple() throws Exception {
- log.info("testProduceAndConsumeMultiple()");
- List<Task> tasks = Arrays.asList(
- new Consumer("A", 100), new Producer("A", 100),
- new Consumer("B", 100), new Producer("B", 100),
- new Consumer("C", 100), new Producer("C", 100),
- new Consumer("D", 100), new Producer("D", 100));
- List<Future<Result>> futures = executor.invokeAll(tasks);
- for (Future<Result> future : futures) {
- future.get().assertResult();
- }
- assertEquals(0, mgraph.size());
- }
-
- @Test
- public void testProduceAndConsumeMixed() throws Exception {
- log.info("testProduceAndConsumeMixed()");
- List<? extends Task> tasks = Arrays.asList(
- new Consumer("A", 110), new Consumer("A", 170),
- new Consumer("B", 100), new Consumer("B", 500),
- new Consumer("C", 230), new Consumer("C", 230),
- new Consumer("D", 540), new Consumer("D", 10),
- new Producer("D", 50), new Producer("D", 500),
- new Producer("C", 400), new Producer("C", 60),
- new Producer("B", 300), new Producer("B", 300),
- new Producer("A", 200), new Producer("A", 80));
- List<Future<Result>> futures = executor.invokeAll(tasks);
- for (Future<Result> future : futures) {
- future.get().assertResult();
- }
- assertEquals(0, mgraph.size());
- }
- /**
- * The <code>Task</code> specifies a <code>Callable</code> whoes execution
- * results in an <code>Integer</code>.
- */
- private abstract class Task implements Callable<Result> {
-
- protected final String collectionName;
- protected final UriRef subject;
- protected final UriRef predicate;
- protected final int numElements;
-
- /**
- * Creates a new <code>Task</code>.
- *
- * @param collectionName
- * Name of the task's collection.
- * @param numElements
- * The number of elements to process.
- */
- protected Task(String collectionName, int numElements) {
- if (collectionName == null) {
- throw new IllegalArgumentException("Invalid name: null");
- } else if (collectionName.length() <= 0) {
- throw new IllegalArgumentException("Invalid name: '"
- + collectionName + "'");
- } else if (numElements < 0) {
- throw new IllegalArgumentException("Invalid numElements: "
- + numElements);
- }
- this.numElements = numElements;
- this.collectionName = collectionName;
- subject = new UriRef("http://example.org/" + "collection/"
- + collectionName);
- predicate = new UriRef("http://example.org/ontology/contains");
- }
-
- /**
- * Causes the currently executing thread object to temporarily pause and
- * allow other threads to execute.
- */
- protected void yield() {
- try {
- Thread.sleep(5);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- }
-
- /**
- * This class represents a task that produces triples that are stored in the
- * graph.
- */
- private class Producer extends Task {
-
- /**
- * Creates a new <code>Producer</code> task.
- *
- * @param collectionName
- * Name of the task's collection.
- * @param numElements
- * The number of elements to produce.
- */
- public Producer(String collectionName, int numElements) {
- super(collectionName, numElements);
- }
-
- @Override
- public Result call() throws InterruptedException {
- int counter = 0;
- for (int elementName = 1; counter < numElements; elementName++) {
- yield();
- final Triple t = createTriple(elementName);
- if (mgraph.add(t)) {
- counter++;
- yield();
- } else {
- System.out.println("WARNING: element " + t + "NOT created");
- }
- }
- return new Result(collectionName, "Produced elements", numElements,
- counter);
- }
-
- /**
- * Creates a new collection element triple.
- *
- * @param value
- * Value of the collection element.
- * @return A new triple representing the collection element.
- */
- protected Triple createTriple(int value) {
- final UriRef object = new UriRef("http://example.org/"
- + collectionName + "/" + Integer.valueOf(value)
- + Math.random());
- return new TripleImpl(subject, predicate, object);
- }
- }
-
- /**
- * This class represents a task that produces triples that are stored in the
- * graph.
- */
- private class Consumer extends Task {
-
- /**
- * Creates a new <code>Consumer</code> task.
- *
- * @param collectionName
- * Name of the task's collection.
- * @param numElements
- * The number of elements to consume.
- */
- public Consumer(String collectionName, int numElements) {
- super(collectionName, numElements);
- }
-
- /**
- * Performs this task.
- *
- * @return the number of elements successfully added to the graph.
- */
- @Override
- public Result call() throws InterruptedException {
- int counter = 0;
- while (counter < numElements) {
- yield();
-
- Triple triple = null;
- mgraph.getLock().writeLock().lock();
- try {
- // System.out.println("synchonized");
- Iterator<Triple> i = mgraph
- .filter(subject, predicate, null);
- if (i.hasNext()) {
- triple = i.next();
- }
-
- if (triple != null && mgraph.remove(triple)) {
- counter++;
- }
- } finally {
- mgraph.getLock().writeLock().unlock();
- }
- }
- return new Result(collectionName, "Consumed elements", numElements,
- counter);
- }
- }
-
- /**
- * Task result that asserts the number of processed elements.
- */
- private class Result {
-
- private final int expected;
- private final int actual;
- private final String msg;
- private final String cn;
-
- /**
- * Creates a new task result that asserts the element count.
- *
- * @param cn
- * Name of the affected collection.
- * @param msg
- * Assertion message to print.
- * @param expected
- * Expected number of processed elements.
- * @param actual
- * Actual number of processed elements.
- */
- public Result(String cn, String msg, int expected, int actual) {
- this.expected = expected;
- this.actual = actual;
- this.msg = msg;
- this.cn = cn;
- }
-
- /**
- * Asserts this result.
- */
- public void assertResult() {
- assertEquals("[" + cn + "] " + msg, expected, actual);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraphTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraphTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraphTest.java
deleted file mode 100644
index 2280a3f..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoGraphTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import org.apache.clerezza.rdf.core.Graph;
-import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoGraph;
-
-/**
- * Tests the {@link VirtuosoGraph} implementation of {@link Graph}
- *
- * @author enridaga
- *
- */
-public class VirtuosoGraphTest {
-
-}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/bb87e83f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraphTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraphTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraphTest.java
deleted file mode 100644
index 0d7b1ec..0000000
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/org/apache/clerezza/rdf/virtuoso/storage/VirtuosoMGraphTest.java
+++ /dev/null
@@ -1,526 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.clerezza.rdf.virtuoso.storage;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Iterator;
-
-import org.apache.clerezza.rdf.core.BNode;
-import org.apache.clerezza.rdf.core.Graph;
-import org.apache.clerezza.rdf.core.Language;
-import org.apache.clerezza.rdf.core.NonLiteral;
-import org.apache.clerezza.rdf.core.PlainLiteral;
-import org.apache.clerezza.rdf.core.Resource;
-import org.apache.clerezza.rdf.core.Triple;
-import org.apache.clerezza.rdf.core.TypedLiteral;
-import org.apache.clerezza.rdf.core.UriRef;
-import org.apache.clerezza.rdf.core.impl.PlainLiteralImpl;
-import org.apache.clerezza.rdf.core.impl.TypedLiteralImpl;
-import org.apache.clerezza.rdf.virtuoso.storage.VirtuosoMGraph;
-import org.apache.clerezza.rdf.virtuoso.storage.access.DataAccess;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import virtuoso.jdbc4.VirtuosoException;
-
-public class VirtuosoMGraphTest {
- static VirtuosoMGraph mgraph = null;
- static DataAccess da = null;
- static final String TEST_GRAPH_NAME = "VirtuosoMGraphTest";
-
- static Logger log = LoggerFactory.getLogger(VirtuosoMGraphTest.class);
-
- @BeforeClass
- public static void assume(){
- org.junit.Assume.assumeTrue(!TestUtils.SKIP);
- }
-
- /**
- * Clean before any test
- *
- * @throws ClassNotFoundException
- * @throws SQLException
- */
- @Before
- public void before() throws ClassNotFoundException, SQLException {
-
- da = TestUtils.getProvider().createDataAccess();
- mgraph = new VirtuosoMGraph(TEST_GRAPH_NAME, da);
- mgraph.clear();
- log.debug("Clearing graph <{}>", TEST_GRAPH_NAME);
- }
-
- final UriRef enridaga = new UriRef("enridaga");
- final UriRef alexdma = new UriRef("alexdma");
- final UriRef anuzzolese = new UriRef("anuzzolese");
- final UriRef predicate = new UriRef("http://property/name");
- final PlainLiteral object = new PlainLiteralImpl("Enrico Daga", new Language("it"));
- final TypedLiteral objectTyped = new TypedLiteralImpl("Enrico Daga", new UriRef("http://www.w3.org/2001/XMLSchema#string"));
- final TypedLiteral objectXml = new TypedLiteralImpl("<div>Enrico Daga</div>" ,
- new UriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"));
- final UriRef knows = new UriRef(TestUtils.FOAF_NS + "knows");
-
- @Test
- public void testAddSingle() {
- log.info("testAddSingle()");
- Triple triple = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return predicate;
- }
-
- @Override
- public Resource getObject() {
- return object;
- }
- };
- boolean success = mgraph.add(triple);
- assertTrue(success);
- assertTrue(mgraph.size() == 1);
- assertTrue(mgraph.filter(enridaga, predicate, object).hasNext());
- assertTrue(mgraph.filter(enridaga, predicate, object).next().equals(triple));
- }
-
- @Test
- public void testAddSingleTypedLiteral() {
- log.info("testAddSingleTypedLiteral()");
- Triple triple = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return predicate;
- }
-
- @Override
- public Resource getObject() {
- return objectTyped;
- }
- };
- boolean success = mgraph.add(triple);
- assertTrue(success);
- assertTrue(mgraph.size() == 1);
- assertTrue(mgraph.filter(enridaga, predicate, objectTyped).hasNext());
- assertTrue(mgraph.filter(enridaga, predicate, objectTyped).next().equals(triple));
- }
-
- @Ignore
- @Test
- public void testAddSingleXMLLiteral() {
- log.info("testAddSingleXMLLiteral()");
- Triple triple = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return predicate;
- }
-
- @Override
- public Resource getObject() {
- return objectXml;
- }
- };
- boolean success = mgraph.add(triple);
- assertTrue(success);
- assertTrue(mgraph.size() == 1);
- Triple rt = mgraph.filter(enridaga, predicate, null).next();
- log.info(" > s: {} ", rt.getSubject());
- log.info(" > p: {} ", rt.getPredicate());
- log.info(" > o: {} ", rt.getObject());
- log.info(" > tl?: {} ", rt.getObject() instanceof TypedLiteral);
- assertTrue(mgraph.filter(enridaga, predicate, objectXml).hasNext());
- assertTrue(mgraph.filter(enridaga, predicate, objectXml).next().equals(triple));
- }
-
-
- @Test
- public void testFilter() {
- log.info("testFilter(); Test filter(s,p,o)");
- // We use testAdd to prepare this
- testAddSingle();
-
- Iterator<Triple> its = mgraph.filter(null, null, null);
- while (its.hasNext()) {
- Triple t = its.next();
- log.info("Found --- triple: {}", t);
- log.info("Found --- s: {} {}", t.getSubject(), t.getSubject().getClass());
- log.info("Found --- p: {} {}", t.getPredicate(), t.getPredicate().getClass());
- log.info("Found --- o: {} {}", t.getObject(), t.getObject().getClass());
- assertEquals(t.getSubject(), enridaga);
- assertEquals(t.getPredicate(), predicate);
- assertEquals(t.getObject(), object);
- }
-
- Iterator<Triple> it = mgraph.filter(enridaga, predicate, object);
- boolean found = false;
- while (it.hasNext()) {
- found = true;
- Triple t = it.next();
- log.debug("Found matching triple: {}", t);
- assertEquals(t.getSubject(), enridaga);
- assertEquals(t.getPredicate(), predicate);
- assertEquals(t.getObject(), object);
- }
- assertTrue(found);
- }
-
- @Test
- public void testFilterSubject() {
- log.info("testFilterSubject(); Test filter(s,null,null)");
- // We use testAdd to prepare this
- testAddSingle();
- Iterator<Triple> it = mgraph.filter(enridaga, null, null);
- boolean found = false;
- while (it.hasNext()) {
- found = true;
- Triple t = it.next();
- if (log.isDebugEnabled()) {
- log.debug("Found matching triple: {}", t);
- TestUtils.stamp(t);
- }
- assertEquals(t.getSubject(), enridaga);
- }
- assertTrue(found);
- }
-
-
- @Test
- public void testFilterSubjectBnode() throws VirtuosoException, SQLException, ClassNotFoundException {
- log.info("testFilterSubjectBnode(); Test filter(s,null,null)");
- final BNode bn = new BNode();
- // We use testAdd to prepare this
- Triple triple = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return bn;
- }
-
- @Override
- public UriRef getPredicate() {
- return predicate;
- }
-
- @Override
- public Resource getObject() {
- return new BNode();
- }
- };
-
- boolean success = mgraph.add(triple);
- assertTrue(success);
- Iterator<Triple> it = mgraph.filter(bn, predicate, null);
- boolean found = false;
- Triple t = null; // we will use it to make a further query
- while (it.hasNext()) {
- found = true;
- t = it.next();
- if (log.isDebugEnabled()) {
- log.debug("Found matching triple: {}", t);
- TestUtils.stamp(t);
- }
- assertEquals(t.getPredicate(), predicate);
- }
- assertTrue(found);
-
- assertNotNull(t);
-
- log.info("{}",t.getSubject());
- it = mgraph.filter(t.getSubject(), predicate, t.getObject());
- found = false;
- while (it.hasNext()) {
- found = true;
- t = it.next();
- if (log.isDebugEnabled()) {
- log.debug("Found matching triple: {}", t);
- TestUtils.stamp(t);
- }
- assertEquals(t.getPredicate(), predicate);
- }
- assertTrue(found);
- }
-
- @Test
- public void testFilterPredicate() {
- log.info("testFilterPredicate(); Test filter(null,p,null)");
- // We use testAdd to prepare this
- testAddSingle();
- Iterator<Triple> it = mgraph.filter(null, predicate, null);
- boolean found = false;
- while (it.hasNext()) {
- found = true;
- Triple t = it.next();
- if (log.isDebugEnabled()) {
- log.debug("Found matching triple: {}", t);
- TestUtils.stamp(t);
- }
- assertEquals(t.getPredicate(), predicate);
- }
- assertTrue(found);
- }
-
- @Test
- public void testFilterObject() {
- log.info("testFilterObject(); Test filter(null,null,o)");
- // We use testAdd to prepare this
- testAddSingle();
- Iterator<Triple> it = mgraph.filter(null, null, object);
- boolean found = false;
- while (it.hasNext()) {
- found = true;
- Triple t = it.next();
- if (log.isDebugEnabled()) {
- log.debug("Found matching triple: {}", t);
- TestUtils.stamp(t);
- }
- assertEquals(t.getObject(), object);
- }
- assertTrue(found);
- }
-
- @Test
- public void testFilterObjectTyped() {
- log.info("testFilterObjectTyped(); Test filter(null,null,o)");
- // We use testAdd to prepare this
- testAddSingleTypedLiteral();
- Iterator<Triple> it = mgraph.filter(null, null, objectTyped);
- boolean found = false;
- while (it.hasNext()) {
- found = true;
- Triple t = it.next();
- if (log.isDebugEnabled()) {
- log.debug("Found matching triple: {}", t);
- TestUtils.stamp(t);
- }
- assertEquals(t.getObject(), objectTyped);
- }
- assertTrue(found);
- }
-
- @Ignore
- @Test
- public void testFilterObjectXml() {
- log.info("testFilterObjectXml(); Test filter(null,null,o)");
- // We use testAdd to prepare this
- testAddSingleXMLLiteral();
- Iterator<Triple> it = mgraph.filter(null, null, objectXml);
- boolean found = false;
- while (it.hasNext()) {
- found = true;
- Triple t = it.next();
- if (log.isDebugEnabled()) {
- log.debug("Found matching triple: {}", t);
- TestUtils.stamp(t);
- }
- assertEquals(t.getObject(), objectXml);
- }
- assertTrue(found);
- }
-
- @Test
- public void testSize() {
- log.info("testSize()");
- // We use testAdd to prepare this
- testAddSingle();
- // Should be 1 at this time
- log.debug("How many triples are in graph <{}>? {}", TEST_GRAPH_NAME,
- mgraph.size());
- assertTrue(mgraph.size() > 0);
- }
-
- @Test
- public void testIncreaseSize() {
- log.info("testIncreaseSize()");
- int beforeSize = mgraph.size();
- Triple t = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return knows;
- }
-
- @Override
- public Resource getObject() {
- return alexdma;
- }
- };
- assertTrue(mgraph.add(t));
- int afterSize = mgraph.size();
- assertEquals(beforeSize + 1, afterSize);
- }
-
- @Test
- public void testAddRemoveSize() {
- log.info("testAddRemoveSize()");
- int beforeSize = mgraph.size();
- Triple t = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return knows;
- }
-
- @Override
- public Resource getObject() {
- return alexdma;
- }
- };
- assertTrue(mgraph.add(t));
- assertTrue(mgraph.remove(t));
- int afterSize = mgraph.size();
- assertEquals(beforeSize, afterSize);
- }
-
- @Test
- public void testGetGraphReadOnly() {
- log.info("testGetGraphReadOnly()");
- Graph g = mgraph.getGraph();
- Triple t = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return knows;
- }
-
- @Override
- public Resource getObject() {
- return anuzzolese;
- }
- };
- // This should not be allowed
- boolean success;
- try {
- success = g.add(t);
- } catch (UnsupportedOperationException e) {
- success = false;
- }
- assertFalse(success);
- }
-
- @Test
- public void testContains() {
- log.info("testContains()");
- Triple t = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return knows;
- }
-
- @Override
- public Resource getObject() {
- return anuzzolese;
- }
- };
- boolean addWorks = mgraph.add(t);
- assertTrue(addWorks);
-
- // This second triple is equivalent
- Triple t2 = new Triple() {
-
- @Override
- public NonLiteral getSubject() {
- return enridaga;
- }
-
- @Override
- public UriRef getPredicate() {
- return knows;
- }
-
- @Override
- public Resource getObject() {
- return anuzzolese;
- }
- };
- Iterator<Triple> it = mgraph.filter(t2.getSubject(), t2.getPredicate(),
- t2.getObject());
- while (it.hasNext()) {
- if (log.isDebugEnabled()) {
- log.debug("Found matching triple");
- TestUtils.stamp(it.next());
- }else{
- it.next();
- }
- }
- assertTrue(mgraph.contains(t2));
- // Also the related read-only graph
- assertTrue(mgraph.getGraph().contains(t2));
- }
-
- @After
- public void clear() throws VirtuosoException, ClassNotFoundException,
- SQLException {
- log.info("Clearing graph <{}> of size {}", TEST_GRAPH_NAME,
- mgraph.size());
- log.debug("Removing graph <{}>", TEST_GRAPH_NAME);
- da.close();
- da = null;
- mgraph = null;
- Statement st = TestUtils.getConnection().createStatement();
- st.execute("SPARQL CLEAR GRAPH <" + TEST_GRAPH_NAME + ">");
- st.close();
- }
-}