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/08 01:03:29 UTC

[2/3] git commit: Worked on CLEREZZA-889 and CLEREZZA-890 Created a DataAccess to enclose a connection and all JDBC activity. Removed the relevant code from VirtuosoMGraph. Changed references where necessary. VirtuosoWeigthedProvider assures all DataAcce

Worked on CLEREZZA-889 and CLEREZZA-890 Created a DataAccess to enclose a connection and all JDBC activity. Removed the relevant code from VirtuosoMGraph. Changed references where necessary. VirtuosoWeigthedProvider assures all DataAccess are properly closed on deactivation. The DataAccess class include proper prepared statements and uses a shared connection. Future work includes renewal policies for the JDBC connection.


Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/67d8506f
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/67d8506f
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/67d8506f

Branch: refs/heads/master
Commit: 67d8506f5d3eceb0fb90e4a562a2edb5111b6cad
Parents: ec85afb
Author: enridaga <en...@apache.org>
Authored: Sat Mar 8 00:00:34 2014 +0000
Committer: enridaga <en...@apache.org>
Committed: Sat Mar 8 00:00:34 2014 +0000

----------------------------------------------------------------------
 .../rdf/virtuoso/storage/VirtuosoBNode.java     |   2 +-
 .../rdf/virtuoso/storage/VirtuosoGraph.java     |   6 +-
 .../rdf/virtuoso/storage/VirtuosoMGraph.java    | 973 +------------------
 .../rdf/virtuoso/storage/access/DataAccess.java | 855 ++++++++++++++++
 .../access/VirtuosoWeightedProvider.java        |  25 +-
 .../java/rdf/virtuoso/storage/RdfIOTest.java    |  48 +-
 .../rdf/virtuoso/storage/ThreadSafetyTest.java  |  11 +-
 .../virtuoso/storage/VirtuosoMGraphTest.java    | 129 ++-
 .../virtuoso/storage/access/DataAccessTest.java | 107 ++
 .../access/VirtuosoWeightedProviderTest.java    |  69 +-
 10 files changed, 1250 insertions(+), 975 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/clerezza/blob/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoBNode.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoBNode.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoBNode.java
index d540a97..d73d784 100644
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoBNode.java
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoBNode.java
@@ -2,7 +2,7 @@ package rdf.virtuoso.storage;
 
 import org.apache.clerezza.rdf.core.BNode;
 
-class VirtuosoBNode extends BNode {
+public class VirtuosoBNode extends BNode {
 	private String skolemId;
 	public VirtuosoBNode(String skolemId) {
 		this.skolemId = skolemId;

http://git-wip-us.apache.org/repos/asf/clerezza/blob/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoGraph.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoGraph.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoGraph.java
index a6669e8..ada5779 100644
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoGraph.java
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoGraph.java
@@ -25,7 +25,7 @@ import org.apache.clerezza.rdf.core.Triple;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import rdf.virtuoso.storage.access.VirtuosoWeightedProvider;
+import rdf.virtuoso.storage.access.DataAccess;
 
 /**
  * This is a read-only version of {@link VirtuosoMGraph}
@@ -40,8 +40,8 @@ public class VirtuosoGraph extends VirtuosoMGraph implements Graph{
 	protected Logger logger = LoggerFactory
 			.getLogger(VirtuosoGraph.class);
 	
-	public VirtuosoGraph(String name, VirtuosoWeightedProvider provider) {
-		super(name, provider);
+	public VirtuosoGraph(String name, DataAccess dataAccess) {
+		super(name, dataAccess);
 	}
 
 	@Override

http://git-wip-us.apache.org/repos/asf/clerezza/blob/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoMGraph.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoMGraph.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoMGraph.java
index 0adad7b..4d876c4 100644
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoMGraph.java
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/VirtuosoMGraph.java
@@ -18,44 +18,24 @@
  */
 package rdf.virtuoso.storage;
 
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.ArrayList;
 import java.util.Iterator;
-import java.util.List;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
-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.Literal;
 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.TypedLiteral;
 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.core.impl.PlainLiteralImpl;
-import org.apache.clerezza.rdf.core.impl.TripleImpl;
-import org.apache.clerezza.rdf.core.impl.TypedLiteralImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.wymiwyg.commons.util.collections.BidiMap;
-import org.wymiwyg.commons.util.collections.BidiMapImpl;
 
-import rdf.virtuoso.storage.access.VirtuosoWeightedProvider;
-import virtuoso.jdbc4.VirtuosoConnection;
-import virtuoso.jdbc4.VirtuosoException;
-import virtuoso.jdbc4.VirtuosoExtendedString;
-import virtuoso.jdbc4.VirtuosoRdfBox;
-import virtuoso.jdbc4.VirtuosoResultSet;
-import virtuoso.jdbc4.VirtuosoStatement;
+import rdf.virtuoso.storage.access.DataAccess;
 
 /**
  * Implementation of MGraph for the Virtuoso quad store.
@@ -65,23 +45,12 @@ import virtuoso.jdbc4.VirtuosoStatement;
  */
 public class VirtuosoMGraph extends AbstractMGraph implements MGraph,
 		LockableMGraph {
-	// XXX Do not change this, sometimes the database crashes with some literals
-	// using the standard syntax
-//	private static final int PLAN_B_LITERAL_SIZE = 0; 
-
-	private static final int CHECKPOINT = 1000;
 	
 	private final ReadWriteLock lock = new ReentrantReadWriteLock();
 	private final Lock readLock = lock.readLock();
 	private final Lock writeLock = lock.writeLock();
 
 	/**
-	 * Bidirectional map for managing the conversion from virtuoso blank nodes
-	 * (strings) to clerezza blank nodes and vice versa.
-	 */
-	private final BidiMap<VirtuosoBNode, BNode> bnodesMap;
-
-	/**
 	 * Logger
 	 */
 	protected Logger logger = LoggerFactory.getLogger(VirtuosoMGraph.class);
@@ -90,10 +59,10 @@ public class VirtuosoMGraph extends AbstractMGraph implements MGraph,
 	 * The name of the graph
 	 */
 	private String name = null;
-	private int size = 0;
+	// private int size = 0;
 
 	private VirtuosoGraph readOnly = null;
-	private VirtuosoWeightedProvider provider = null;
+	private DataAccess dataAccess = null;
 
 	/**
 	 * Creates a {@link VirtuosoMGraph} Virtuoso MGraph binds directly to the
@@ -101,25 +70,12 @@ public class VirtuosoMGraph extends AbstractMGraph implements MGraph,
 	 * 
 	 * @param connection
 	 */
-	public VirtuosoMGraph(String name, VirtuosoWeightedProvider provider) {
-		logger.debug("VirtuosoMGraph(String {}, VirtuosoWeightedProvider {})",
-				name, provider);
+	public VirtuosoMGraph(String name, DataAccess dataAccess) {
+		logger.debug("VirtuosoMGraph(String {}, DataAccess {})", name,
+				dataAccess);
 		this.name = name;
-		this.provider = provider;
-		this.bnodesMap = new BidiMapImpl<VirtuosoBNode, BNode>();
-	}
-
-	/**
-	 * Gets the connection
-	 * 
-	 * @return
-	 * @throws ClassNotFoundException
-	 * @throws SQLException
-	 */
-	protected VirtuosoConnection getConnection() throws SQLException,
-			ClassNotFoundException {
-		logger.debug("getConnection()");
-		return this.provider.getConnection();
+		// this.provider = provider;
+		this.dataAccess = dataAccess;
 	}
 
 	@Override
@@ -138,118 +94,23 @@ public class VirtuosoMGraph extends AbstractMGraph implements MGraph,
 		logger.debug("asVirtuosoGraph()");
 		if (this.readOnly == null) {
 			logger.debug("create embedded singleton read-only instance");
-			this.readOnly = new VirtuosoGraph(name, provider);
+			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) {
-		if (logger.isDebugEnabled()) {
-			logger.debug("performFilter(NonLiteral s, UriRef p, Resource o)");
-			logger.debug(" > s: {}", subject);
-			logger.debug(" > p: {}", predicate);
-			logger.debug(" > o: {}", object);
-		}
-		StringBuilder sb = new StringBuilder();
-		String virtSubject = toVirtSubject(subject);
-		String virtPredicate = toVirtPredicate(predicate);
-		String virtObject = toVirtObject(object);
-		sb.append("SPARQL SELECT ");
-		if (virtSubject != null) {
-			sb.append(" ").append(virtSubject).append(" as ?subject");
-		} else {
-			sb.append(" ?subject ");
-		}
-		if (virtPredicate != null) {
-			sb.append(" ").append(virtPredicate).append(" as ?predicate");
-		} else {
-			sb.append(" ?predicate ");
-		}
-		if (virtObject != null) {
-			sb.append(" ").append(virtObject).append(" as ?object");
-		} else {
-			sb.append(" ?object ");
-		}
-		sb.append(" WHERE { GRAPH <").append(this.getName()).append("> { ");
-		if (virtSubject != null) {
-			sb.append(" ").append(virtSubject).append(" ");
-		} else {
-			sb.append(" ?subject ");
-		}
-		if (virtPredicate != null) {
-			sb.append(" ").append(virtPredicate).append(" ");
-		} else {
-			sb.append(" ?predicate ");
-		}
-		if (virtObject != null) {
-			sb.append(" ").append(virtObject).append(" ");
-		} else {
-			sb.append(" ?object ");
-		}
-
-		sb.append(" } } ");
-
-		String sql = sb.toString();
-//		logger.trace("Executing SQL: {}", sql);
-		VirtuosoStatement st = null;
-		List<Triple> list = null;
-		Exception e = null;
-		VirtuosoConnection connection = null;
-		VirtuosoResultSet rs = null;
-		try {
-			readLock.lock();
-			connection = provider.getConnection();
-			st = (VirtuosoStatement) connection.createStatement();
-			st.execute(sql);
-			rs = (VirtuosoResultSet) st.getResultSet();
-			list = new ArrayList<Triple>();
-			
-			while (rs.next()) {
-				list.add(new TripleBuilder(rs.getObject(1), rs.getObject(2), rs
-						.getObject(3)).build());
-			}
-		} catch (VirtuosoException ve) {
-			logger.error("ERROR while executing statement", ve);
-			logger.error(" executing SQL: {}", sql);
-			e = ve;
-		} catch (SQLException e1) {
-			logger.error("ERROR while executing statement", e1);
-			logger.error(" executing SQL: {}", sql);
-			e = e1;
-		} catch (ClassNotFoundException e1) {
-			logger.error("ERROR while executing statement", e1);
-			e = e1;
-		} finally {
-			readLock.unlock();
-			try {
-				if (rs != null)
-					rs.close();
-			} catch (Throwable ex) {
-				logger.error("Cannot close result set", ex);
-			}
-			;
-			try {
-				if (st != null)
-					st.close();
-			} catch (Throwable ex) {
-				logger.error("Cannot close statement", ex);
-			}
-			;
-			try {
-				if (connection != null) {
-					connection.close();
-				}
-			} catch (VirtuosoException e1) {
-				logger.error("Cannot close connection", e1);
-			}
-		}
-
-		if (list == null || e != null) {
-			throw new RuntimeException(e);
-		}
-		return list.iterator();
+		readLock.lock();
+		Iterator<Triple> tit = getDataAccess().filter(getName(), subject,
+				predicate, object);
+		readLock.unlock();
+		return tit;
 	}
 
 	/**
@@ -258,395 +119,44 @@ public class VirtuosoMGraph extends AbstractMGraph implements MGraph,
 	@Override
 	public int size() {
 		logger.debug("size()");
-		loadSize();
-		return this.size;
+		readLock.lock();
+		int size = getDataAccess().size(getName());
+		readLock.unlock();
+		return size;
 	}
 
 	@Override
 	public void clear() {
 		logger.debug("clear()");
-		String SQL = "SPARQL CLEAR GRAPH <" + this.getName() + ">";
-		this.writeLock.lock();
-		VirtuosoConnection connection = null;
-		Exception e = null;
-		Statement st = null;
-		try {
-			logger.debug("Executing SQL: {}", SQL);
-			connection = getConnection();
-			st = connection.createStatement();
-			boolean success = st.execute(SQL);
-			if (success) {
-				this.size = 0;
-			} else {
-				e = new RuntimeException(
-						"Problems on clear() method. Cannot clear the graph!");
-			}
-		} catch (VirtuosoException ve) {
-			logger.error("ERROR while executing statement", e);
-			e = ve;
-		} catch (SQLException se) {
-			logger.error("ERROR while executing statement", e);
-			e = se;
-		} catch (ClassNotFoundException e1) {
-			e = e1;
-		} finally {
-			try {
-				if (st != null)
-					st.close();
-			} catch (Exception ex) {
-				logger.error("Cannot close statement", ex);
-			}
-			;
-			if (connection != null) {
-				try {
-					connection.close();
-				} catch (VirtuosoException e1) {
-					logger.error("Cannot close connection", e1);
-				}
-			}
-			this.writeLock.unlock();
-		}
-		if (e != null) {
-			throw new RuntimeException(e);
-		}
-	}
-
-	private void loadSize() {
-		logger.debug("loadSize()");
-		String SQL = "SPARQL SELECT COUNT(*) FROM <" + this.getName()
-				+ "> WHERE { ?s ?p ?o } ";
-		int size = 0;
-		logger.debug("loadSize() pre lock");
-		this.readLock.lock();
-		logger.debug("loadSize() post lock");
-		VirtuosoConnection connection = null;
-		Exception e = null;
-		Statement st = null;
-		VirtuosoResultSet rs = null;
-		try {
-			logger.debug("Executing SQL: {}", SQL);
-			connection = getConnection();
-			st = connection.createStatement();
-			rs = (VirtuosoResultSet) st.executeQuery(SQL);
-			rs.next();
-			size = rs.getInt(1);
-		} catch (VirtuosoException ve) {
-			logger.error("ERROR while executing statement", e);
-			e = ve;
-		} catch (SQLException se) {
-			logger.error("ERROR while executing statement", e);
-			e = se;
-		} catch (ClassNotFoundException e1) {
-			e = e1;
-		} finally {
-			this.readLock.unlock();
-			logger.debug("loadSize() unlock");
-			try {
-				if (rs != null)
-					rs.close();
-			} catch (Exception ex) {
-				logger.error("Cannot close result set", ex);
-			}
-			;
-			try {
-				if (st != null)
-					st.close();
-			} catch (Exception ex) {
-				logger.error("Cannot close statement", ex);
-			}
-			;
-			if (connection != null) {
-				try {
-					connection.close();
-				} catch (VirtuosoException e1) {
-					logger.error("Cannot close connection", e1);
-				}
-			}
-		}
-		if (e != null) {
-			throw new RuntimeException(e);
-		}
-		this.size = size;
-	}
-
-	private int checkpoint = 0;
-	private void checkpoint(boolean force){
-		if(checkpoint <= CHECKPOINT && force == false){
-			checkpoint++;
-			return;
-		}else{
-			checkpoint = 0;
-		}
-		VirtuosoConnection connection = null;
-		Exception e = null;
-		Statement st = null;
-		try {
-			connection = provider.getConnection();
-			st = connection.createStatement();
-			st.execute("Checkpoint");
-			logger.info("Checkpoint.");
-		} catch (VirtuosoException ve) {
-			logger.error("ERROR while executing statement", ve);
-			e = ve;
-		} catch (SQLException se) {
-			logger.error("ERROR while executing statement", se);
-			e = se;
-		} catch (ClassNotFoundException e1) {
-			e = e1;
-		} finally {
-			try {
-				if (st != null)
-					st.close();
-			} catch (Exception ex) {
-				logger.error("Cannot close statement", ex);
-			}
-			;
-			if (connection != null) {
-				try {
-					connection.close();
-				} catch (VirtuosoException e1) {
-					logger.error("Cannot close connection", e1);
-				}
-			}
-		}
-		if (e != null) {
-			throw new RuntimeException(e);
-		}
-	}
-	
-	private boolean performAddPlanB(Triple triple){
-		StringBuilder b = new StringBuilder();
-		b.append(toVirtSubject(triple.getSubject()))
-		.append(" ")
-		.append(toVirtPredicate(triple.getPredicate()))
-		.append(" ")
-		.append(toVirtObject(triple.getObject()))
-		.append(" . ");
-		String sql = "db.dba.ttlp(?, '', '" + this.getName() + "', 0)";
-		logger.debug("Exec Plan B: {}", sql);
 		writeLock.lock();
-		VirtuosoConnection connection = null;
-		Exception e = null;
-		PreparedStatement st = null;
-		try {
-			connection = provider.getConnection();
-			st = connection.prepareStatement(sql);
-			String s = b.toString();
-			logger.trace(" TTL is \n{}\n", s);
-			st.setNString(1, b.toString());
-			st.execute();
-			connection.commit();
-		} catch (VirtuosoException ve) {
-			logger.error("ERROR while executing statement", ve);
-			e = ve;
-		} catch (SQLException se) {
-			logger.error("ERROR while executing statement", se);
-			e = se;
-		} catch (ClassNotFoundException e1) {
-			e = e1;
-		} finally {
-			writeLock.unlock();
-			try {
-				if (st != null)
-					st.close();
-			} catch (Exception ex) {
-				logger.error("Cannot close statement", ex);
-			}
-			;
-			if (connection != null) {
-				try {
-					connection.close();
-				} catch (VirtuosoException e1) {
-					logger.error("Cannot close connection", e1);
-				}
-			}
-			checkpoint(false);
-		}
-		if (e != null) {
-			logger.error("S {}", triple.getSubject());
-			logger.error("P {}", triple.getPredicate());
-			logger.error("O {}", triple.getObject());
-			logger.error(" O size: {}", triple.getObject().toString().length());
-			logger.error("Sql: {}", sql);
-			throw new RuntimeException(e);
-		}
-		return true;
+		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
-//		if (triple.getObject() instanceof Literal) {
-//			int litsize = ((Literal) triple.getObject()).getLexicalForm().getBytes().length;
-//			if(triple.getObject() instanceof TypedLiteral){
-//				litsize += ((TypedLiteral) triple.getObject()).getDataType().getUnicodeString().getBytes().length;
-//			}else{
-//				litsize += 10; // lang annotation should not be longer then 10 bytes...
-//			}
-//			if ( litsize > PLAN_B_LITERAL_SIZE) {
-//				return performAddPlanB(triple);
-//			}
-//		}
-
+		// SR449: Key is too long, index RDF_QUAD, ruling part is 1901 bytes
+		// that exceeds 1900 byte limit
 		// We use alternative method for literals
-		if (triple.getObject() instanceof Literal) {
-			return performAddPlanB(triple);
-		}
-		
-		// String sql = getAddSQLStatement(triple);
-		String sql = INSERT;
 		writeLock.lock();
-		VirtuosoConnection connection = null;
-		Exception e = null;
-		PreparedStatement st = null;
-		try {
-			connection = getConnection();
-			connection.setAutoCommit(false);
-			// st = connection.createStatement();
-			st = connection.prepareStatement(sql);
-			bindGraph(st, 1, new UriRef(getName()));
-			bindSubject(st, 2, triple.getSubject());
-			bindPredicate(st, 3, triple.getPredicate());
-			bindValue(st, 4, triple.getObject());
-			
-			try{
-				st.executeUpdate();
-				connection.commit();
-			}catch(VirtuosoException ve){
-				logger.error("FAILED ", ve);
-				connection.rollback();
-				throw ve;
-			}
-		} catch (VirtuosoException ve) {
-			logger.error("ERROR while executing statement", ve);
-			e = ve;
-		} catch (SQLException se) {
-			logger.error("ERROR while executing statement", se);
-			e = se;
-		} catch (ClassNotFoundException e1) {
-			e = e1;
-		} finally {
-			writeLock.unlock();
-			try {
-				if (st != null)
-					st.close();
-			} catch (Exception ex) {
-				logger.error("Cannot close statement", ex);
-			}
-			;
-			if (connection != null) {
-				try {
-					connection.close();
-				} catch (VirtuosoException e1) {
-					logger.error("Cannot close connection", e1);
-				}
-			}
-			checkpoint(false);
-		}
-		if (e != null) {
-			logger.error("S {}", triple.getSubject());
-			logger.error("P {}", triple.getPredicate());
-			logger.error("O {}", triple.getObject());
-			logger.error(" O size: {}", triple.getObject().toString().length());
-			logger.error("Sql: {}", sql);
-			throw new RuntimeException(e);
+		if (triple.getObject() instanceof Literal) {
+			getDataAccess().performAddPlanB(getName(), triple);
+		}else{
+			getDataAccess().insertQuad(getName(), triple);
 		}
+		writeLock.unlock();
 		return true;
 	}
 
-	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, toVirtBnode((BNode) object).getSkolemId());
-			st.setNull(i + 2, java.sql.Types.VARCHAR);
-		} else if (object instanceof TypedLiteral) {
-			TypedLiteral tl = ((TypedLiteral)object);
-			st.setInt(i, 4);
-			// if datatype is XMLLiteral
-			String lf = tl.getLexicalForm();
-			if(tl.getDataType().getUnicodeString().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral")){
-				lf = prepareString(lf, true).toString();
-			}
-			st.setString(i+1, lf);
-			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, toVirtBnode((BNode) subject).getSkolemId());
-		}
-	}
-
-	private void bindGraph(PreparedStatement st, int i, UriRef uriRef)
-			throws SQLException {
-		st.setString(i, uriRef.getUnicodeString());
-	}
-
 	protected boolean performRemove(Triple triple) {
 		logger.debug("performRemove(Triple triple)", triple);
-		String sql = getRemoveSQLStatement(triple);
-		logger.debug("Executing SQL: {}", sql);
 		writeLock.lock();
-		VirtuosoConnection connection = null;
-		Exception e = null;
-		Statement st = null;
-		try {
-			connection = getConnection();
-			st = connection.createStatement();
-			st.execute(sql);
-		} catch (SQLException se) {
-			logger.error("ERROR while executing statement", e);
-			e = se;
-		} catch (ClassNotFoundException e1) {
-			e = e1;
-		} finally {
-			writeLock.unlock();
-			try {
-				if (st != null)
-					st.close();
-			} catch (Exception ex) {
-				logger.error("Cannot close statement", ex);
-			}
-			;
-			if (connection != null) {
-				try {
-					connection.close();
-				} catch (VirtuosoException e1) {
-					logger.error("Cannot close connection", e1);
-				}
-			}
-			checkpoint(false);
-		}
-		if (e != null) {
-			throw new RuntimeException(e);
-		}
+		getDataAccess().deleteQuad(getName(), triple);
+		writeLock.unlock();
 		return true;
 	}
 
@@ -661,419 +171,6 @@ public class VirtuosoMGraph extends AbstractMGraph implements MGraph,
 	}
 
 	/**
-	 * Build a virtuoso bnode mapped to the intern
-	 * 
-	 * @param virtbnode
-	 * @return
-	 */
-	private VirtuosoBNode toBNode(String virtbnode) {
-		logger.debug("toBNode(String {})", virtbnode);
-		VirtuosoBNode bnode;
-		bnode = new VirtuosoBNode(virtbnode);
-		return bnode;
-	}
-
-	/**
-	 * 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.
-		 */
-		String temp_graph = "<urn:x-virtuoso:bnode-tmp>";
-		String bno = new StringBuilder().append('<').append(bn).append('>')
-				.toString();
-		String _bnodeObject = "<urn:x-virtuoso:bnode:object>";
-		String sql_insert = new StringBuilder()
-				.append("sparql INSERT IN GRAPH ").append(temp_graph)
-				.append(" { [] ").append(_bnodeObject).append(' ').append(bno)
-				.append(" } ").toString();
-		logger.trace(" insert: {}", sql_insert);
-		String sql_select = new StringBuilder()
-				.append("sparql SELECT ?S FROM ").append(temp_graph)
-				.append(" WHERE { ?S ").append(_bnodeObject).append(' ')
-				.append(bno).append(' ').append(" } LIMIT 1").toString();
-		logger.trace(" select new bnode: {}", sql_select);
-		String sql_delete = new StringBuilder().append("sparql DELETE FROM ")
-				.append(temp_graph).append(" { ?S ").append(_bnodeObject)
-				.append(' ').append(bno).append(" } ").toString();
-		logger.trace(" delete tmp triple: {}", sql_delete);
-
-		// logger.info("SQL {}", sql);
-		writeLock.lock();
-		VirtuosoConnection connection = null;
-		Exception e = null;
-		Statement st = null;
-		VirtuosoResultSet rs = null;
-		String bnodeId = null;
-		try {
-			connection = getConnection();
-			st = connection.createStatement();
-			st.executeUpdate(sql_insert);
-			rs = (VirtuosoResultSet) st.executeQuery(sql_select);
-			rs.next();
-			bnodeId = rs.getString(1);
-			st.executeUpdate(sql_delete);
-		} catch (VirtuosoException ve) {
-			logger.error("ERROR while executing statement", ve);
-			e = ve;
-		} catch (SQLException se) {
-			logger.error("ERROR while executing statement", se);
-			e = se;
-		} catch (ClassNotFoundException e1) {
-			logger.error("ERROR while executing statement", e1);
-			e = e1;
-		} finally {
-			writeLock.unlock();
-			try {
-				if (st != null)
-					st.close();
-			} catch (Exception ex) {
-			}
-			;
-			try {
-				if (rs != null)
-					rs.close();
-			} catch (Exception ex) {
-			}
-			;
-			if (connection != null) {
-				try {
-					connection.close();
-				} catch (VirtuosoException e1) {
-					logger.error("Cannot close connection", e1);
-				}
-			}
-			checkpoint(false);
-		}
-		if (e != null) {
-			throw new RuntimeException(e);
-		}
-		return new VirtuosoBNode(bnodeId);
-	}
-
-	/**
-	 * 
-	 * @param bnode
-	 * @return
-	 */
-	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;
-		}
-	}
-
-	private static String INSERT = "SPARQL INSERT INTO iri(??) {`iri(??)` `iri(??)` "
-			+ "`bif:__rdf_long_from_batch_params(??,??,??)`}";
-
-//	protected String getAddSQLStatement(Triple triple) {
-//		logger.debug("getAddSQLStatement(Triple {})", triple);
-//		StringBuilder sb = new StringBuilder();
-//		String subject = toVirtSubject(triple.getSubject());
-//		String predicate = toVirtPredicate(triple.getPredicate());
-//		String object = toVirtObject(triple.getObject());
-//		String sql = sb.append("SPARQL INSERT INTO <").append(this.getName())
-//				.append("> { ").append(subject).append(" ").append(predicate)
-//				.append(" ").append(object).append(" }").toString();
-//		return sql;
-//	}
-
-	protected String getRemoveSQLStatement(Triple triple) {
-		logger.debug("getRemoveSQLStatement(Triple {})", triple);
-		StringBuilder sb = new StringBuilder();
-		String subject = toVirtSubject(triple.getSubject());
-		String predicate = toVirtPredicate(triple.getPredicate());
-		String object = toVirtObject(triple.getObject());
-		String sql = sb.append("SPARQL DELETE FROM <").append(this.getName())
-				.append("> { ").append(subject).append(" ").append(predicate)
-				.append(" ").append(object).append(" } FROM <")
-				.append(this.getName()).append("> ").append(" WHERE { ")
-				.append(subject).append(" ").append(predicate).append(" ")
-				.append(object).append(" }").toString();
-		return sql;
-	}
-
-	/**
-	 * 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");
-		}
-	}
-
-	/**
-	 * 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 VirtuosoMGraph.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 VirtuosoMGraph.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 VirtuosoMGraph.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());
-		}
-	}
-
-	/**
 	 * Must be a VirtuosoMGraph with the same name. Subclasses are not assumed
 	 * to be equals (VirtuosoGraph is not the same as VirtuosoMGraph)
 	 */

http://git-wip-us.apache.org/repos/asf/clerezza/blob/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/DataAccess.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/DataAccess.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/DataAccess.java
new file mode 100644
index 0000000..d5abc36
--- /dev/null
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/DataAccess.java
@@ -0,0 +1,855 @@
+package rdf.virtuoso.storage.access;
+
+import java.io.PrintWriter;
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.wymiwyg.commons.util.collections.BidiMap;
+import org.wymiwyg.commons.util.collections.BidiMapImpl;
+
+import rdf.virtuoso.storage.VirtuosoBNode;
+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();
+		
+		// Init collections
+		this.preparedStatements = new HashMap<String,VirtuosoPreparedStatement>();
+		this.bnodesMap = new BidiMapImpl<VirtuosoBNode, BNode>();
+
+	}
+
+	private VirtuosoConnection createConnection() {
+		try {
+			Class.forName(VirtuosoWeightedProvider.DRIVER, true, this
+					.getClass().getClassLoader());
+			if (logger.isDebugEnabled()) {
+				logger.debug("Activating logging for DriverManager in stderr");
+				// FIXME! How to redirect logging to our logger???
+				DriverManager.setLogWriter(new PrintWriter(System.err));
+			}
+			VirtuosoConnection c = (VirtuosoConnection) DriverManager
+					.getConnection(connectionString, user, pwd);
+			c.setAutoCommit(true);
+			return c;
+		} catch (ClassNotFoundException e) {
+			throw new RuntimeException(e);
+		} catch (SQLException e) {
+			throw new RuntimeException(e);
+		}
+	}
+
+	protected PreparedStatement getStatement(String query)
+			throws VirtuosoException {
+		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();
+	}
+
+	public void close() {
+		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);
+			}
+		}
+		preparedStatements.clear();
+		try {
+			connection.close();
+		} catch (Exception e) {
+			logger.error("Cannot close connection", e);
+		}
+	}
+
+	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) {
+			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);
+		}
+		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 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 Set<UriRef> listGraphs() {
+		try {
+			PreparedStatement st = getStatement(LIST_GRAPHS);
+			ResultSet rs = st.executeQuery();
+			Set<UriRef> graphs = new HashSet<UriRef>();
+			while (rs.next()) {
+				UriRef graph = new UriRef(rs.getString(1));
+				logger.debug(" > Graph {}", graph);
+				graphs.add(graph);
+			}
+			return Collections.unmodifiableSet(graphs);
+		} catch (VirtuosoException e) {
+			logger.error("Cannot execute query", e);
+			throw new RuntimeException(e);
+		} catch (SQLException e) {
+			logger.error("Cannot execute query", e);
+			throw new RuntimeException(e);
+		}
+	}
+
+	public void clearGraph(String graph) {
+		try {
+			PreparedStatement st = getStatement(CLEAR_GRAPH);
+			bindGraph(st, 1, graph);
+			st.executeUpdate();
+			try {
+				connection.commit();
+			} catch (Exception e) {
+				logger.error("Rolling back");
+				connection.rollback();
+			}
+		} 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);
+		}
+	}
+
+	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) {
+		
+
+		// 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.isDebugEnabled()) {
+			logger.debug("performFilter(UriRef graph, NonLiteral s, UriRef p, Resource o)");
+			logger.debug(" > g: {}", graph);
+			logger.debug(" > s: {}", subject);
+			logger.debug(" > p: {}", predicate);
+			logger.debug(" > 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) {
+			throw new RuntimeException(e);
+		}
+		return list.iterator();
+	}
+
+	public int size(String graph){
+		Exception e = null;
+		PreparedStatement ps = null;
+		VirtuosoResultSet rs = null;
+		int size = -1;
+		try {
+			ps = getStatement(COUNT_TRIPLES_OF_GRAPH);
+			// In any case the first binding is the graph
+			bindGraph(ps, 1, graph);
+			ps.execute();
+			rs = (VirtuosoResultSet) ps.getResultSet();
+			rs.next();
+			size = rs.getInt(1);
+		} 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) {
+			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) {
+			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");
+		}
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/clerezza/blob/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
index 1b7fa62..ff033cb 100644
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/main/java/rdf/virtuoso/storage/access/VirtuosoWeightedProvider.java
@@ -100,6 +100,7 @@ public class VirtuosoWeightedProvider implements WeightedTcProvider {
 	 * MAP OF LOADED GRAPHS
 	 */
 	private Map<UriRef, VirtuosoMGraph> graphs = new HashMap<UriRef, VirtuosoMGraph>();
+	private Set<DataAccess> dataAccessSet = new HashSet<DataAccess>();
 	private String ACTIVE_GRAPHS_GRAPH = "urn:x-virtuoso:active-graphs";
 	
 	/**
@@ -241,9 +242,9 @@ public class VirtuosoWeightedProvider implements WeightedTcProvider {
 		for(UriRef name : remembered){
 			if (canModify(name)) {
 				graphs.put(name, new VirtuosoMGraph(name.getUnicodeString(),
-							this));
+						createDataAccess()));
 			} else {
-				graphs.put(name,  new VirtuosoGraph(name.getUnicodeString(), this));
+				graphs.put(name,  new VirtuosoGraph(name.getUnicodeString(), createDataAccess()));
 			}
 		}
 		logger.info("Activated VirtuosoWeightedProvider.");
@@ -420,6 +421,11 @@ public class VirtuosoWeightedProvider implements WeightedTcProvider {
 		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.");
 	}
 	
@@ -533,11 +539,11 @@ public class VirtuosoWeightedProvider implements WeightedTcProvider {
 					if (canModify(name)) {
 						logger.debug("Creating writable MGraph for graph {}", name);
 						graphs.put(name, new VirtuosoMGraph(
-								name.getUnicodeString(), this));
+								name.getUnicodeString(), createDataAccess()));
 					} else {
 						logger.debug("Creating read-only Graph for graph {}", name);
 						graphs.put(name, new VirtuosoMGraph(
-								name.getUnicodeString(), this)
+								name.getUnicodeString(), createDataAccess())
 								.asVirtuosoGraph());
 					}
 					graph = graphs.get(name);
@@ -570,6 +576,15 @@ public class VirtuosoWeightedProvider implements WeightedTcProvider {
 		}
 		
 	}
+	
+
+	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
@@ -740,7 +755,7 @@ public class VirtuosoWeightedProvider implements WeightedTcProvider {
 		} catch (NoSuchEntityException nsee) {
 			if (canModify(name)) {
 				graphs.put(name, new VirtuosoMGraph(name.getUnicodeString(),
-							this));
+							createDataAccess()));
 				rememberGraphs(name);
 				return graphs.get(name);
 			} else {

http://git-wip-us.apache.org/repos/asf/clerezza/blob/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/RdfIOTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/RdfIOTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/RdfIOTest.java
index 2633b29..1166c81 100644
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/RdfIOTest.java
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/RdfIOTest.java
@@ -44,7 +44,7 @@ import org.junit.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import rdf.virtuoso.storage.access.VirtuosoWeightedProvider;
+import rdf.virtuoso.storage.access.DataAccess;
 import virtuoso.jdbc4.VirtuosoException;
 
 public class RdfIOTest {
@@ -52,7 +52,7 @@ public class RdfIOTest {
 	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 VirtuosoWeightedProvider wp;
+	static DataAccess da;
 
 	/**
 	 * Clean before any test
@@ -66,8 +66,8 @@ public class RdfIOTest {
 			log.warn("SKIPPED");
 			return;
 		}
-		wp = TestUtils.getProvider();
-		mgraph = new VirtuosoMGraph(TEST_GRAPH_NAME, wp);
+		da = TestUtils.getProvider().createDataAccess();
+		mgraph = new VirtuosoMGraph(TEST_GRAPH_NAME, da);
 		mgraph.clear();
 		log.debug("Clearing graph <{}>", TEST_GRAPH_NAME);
 	}
@@ -88,9 +88,16 @@ public class RdfIOTest {
 		}
 		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
@@ -144,11 +151,9 @@ public class RdfIOTest {
 
 	private Triple writeAndRead(NonLiteral subject, UriRef predicate,
 			Resource object) throws ClassNotFoundException, SQLException {
-		VirtuosoMGraph graph = new VirtuosoMGraph(TEST_GRAPH_NAME,
-				TestUtils.getProvider());
 		Triple t = new TripleImpl(subject, predicate, object);
-		graph.add(t);
-		Triple read = graph.getGraph().iterator().next();
+		mgraph.add(t);
+		Triple read = mgraph.getGraph().iterator().next();
 		return read;
 	}
 
@@ -272,12 +277,9 @@ public class RdfIOTest {
 		UriRef p2 = new UriRef("p2");
 		UriRef p3 = new UriRef("p3");
 
-		VirtuosoMGraph graph = new VirtuosoMGraph(TEST_GRAPH_NAME,
-				TestUtils.getProvider());
-
-		graph.add(new TripleImpl(s1, p1, s2));
+		mgraph.add(new TripleImpl(s1, p1, s2));
 		// Get the bnode of s1
-		Triple first = graph.filter(null, p1, null).next();
+		Triple first = mgraph.filter(null, p1, null).next();
 
 		Assert.assertTrue(first.getSubject() instanceof VirtuosoBNode);
 		Assert.assertTrue(first.getObject() instanceof VirtuosoBNode);
@@ -285,29 +287,29 @@ public class RdfIOTest {
 		BNode s1intern = (BNode) first.getSubject();
 		BNode s2intern = (BNode) first.getObject();
 		
-		graph.add(new TripleImpl(s2intern, p1, s3));
-		Triple second = graph.filter(s2intern, p1, null).next();
+		mgraph.add(new TripleImpl(s2intern, p1, s3));
+		Triple second = mgraph.filter(s2intern, p1, null).next();
 		Assert.assertTrue(second.getObject() instanceof VirtuosoBNode);
 		
-		graph.add(new TripleImpl(s1intern, p2, s4));
-		Triple third = graph.filter(s1intern, p2, null).next();
+		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();
 		
-		graph.add(new TripleImpl(s1intern, p2, s4intern));
-		graph.add(new TripleImpl(s4intern, p3, s1intern));
+		mgraph.add(new TripleImpl(s1intern, p2, s4intern));
+		mgraph.add(new TripleImpl(s4intern, p3, s1intern));
 
-		Iterator<Triple> all = graph.iterator();
+		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 = graph.filter(null, p2, null);
+		Iterator<Triple> i = mgraph.filter(null, p2, null);
 		int n = 0;
 		while (i.hasNext()) {
 			n++;
 			Triple s1t = i.next();
-			Iterator<Triple> s1i = graph.filter(s1t.getSubject(), null, null);
+			Iterator<Triple> s1i = mgraph.filter(s1t.getSubject(), null, null);
 			boolean found = false;
 			while (s1i.hasNext()) {
 				Triple s1it = s1i.next();
@@ -321,7 +323,7 @@ public class RdfIOTest {
 			Assert.assertTrue(found);
 			Assert.assertTrue(s1t.getObject() instanceof VirtuosoBNode);
 			Assert.assertTrue(s1t.getSubject() instanceof VirtuosoBNode);
-			Iterator<Triple> s4i = graph.filter((NonLiteral) s1t.getObject(),
+			Iterator<Triple> s4i = mgraph.filter((NonLiteral) s1t.getObject(),
 					null, null);
 			log.info("s4 {} ",s1t.getObject());
 			while (s4i.hasNext()) {

http://git-wip-us.apache.org/repos/asf/clerezza/blob/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/ThreadSafetyTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/ThreadSafetyTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/ThreadSafetyTest.java
index 966da2c..17cb722 100644
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/ThreadSafetyTest.java
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/ThreadSafetyTest.java
@@ -39,6 +39,8 @@ import org.junit.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import rdf.virtuoso.storage.access.DataAccess;
+
 /**
  * 
  * Credit: This code is largely cloned by the thread safe test in
@@ -51,7 +53,7 @@ public class ThreadSafetyTest {
 
 	private ExecutorService executor;
 	private VirtuosoMGraph mgraph;
-
+	private DataAccess da = null;
 	static Logger log = LoggerFactory.getLogger(ThreadSafetyTest.class);
 
 	@Before
@@ -60,8 +62,11 @@ public class ThreadSafetyTest {
 			log.warn("SKIPPED");
 			return;
 		}
+		da = TestUtils.getProvider().createDataAccess();
+		da.clearGraph("ThreadSafetyTest");
 		mgraph = new VirtuosoMGraph("ThreadSafetyTest",
-				TestUtils.getProvider());
+				da);
+		mgraph.clear();
 		executor = Executors.newCachedThreadPool();
 	}
 
@@ -79,6 +84,8 @@ public class ThreadSafetyTest {
 		} finally {
 			mgraph.clear();
 			mgraph = null;
+			da.close();
+			da = null;
 		}
 	}
 

http://git-wip-us.apache.org/repos/asf/clerezza/blob/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/VirtuosoMGraphTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/VirtuosoMGraphTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/VirtuosoMGraphTest.java
index 6bdbbe3..26fff47 100644
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/VirtuosoMGraphTest.java
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/VirtuosoMGraphTest.java
@@ -34,18 +34,22 @@ 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.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import rdf.virtuoso.storage.access.DataAccess;
 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);
@@ -62,7 +66,8 @@ public class VirtuosoMGraphTest {
 			log.warn("SKIPPED");
 			return;
 		}
-		mgraph = new VirtuosoMGraph(TEST_GRAPH_NAME, TestUtils.getProvider());
+		da = TestUtils.getProvider().createDataAccess();
+		mgraph = new VirtuosoMGraph(TEST_GRAPH_NAME, da);
 		mgraph.clear();
 		log.debug("Clearing graph <{}>", TEST_GRAPH_NAME);
 	}
@@ -72,6 +77,9 @@ public class VirtuosoMGraphTest {
 	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
@@ -101,6 +109,75 @@ public class VirtuosoMGraphTest {
 		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()");
+		if (TestUtils.SKIP) {
+			log.warn("SKIPPED");
+			return;
+		}
+		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));
+	}
+	
+//	@Test
+	public void testAddSingleXMLLiteral() {
+		log.info("testAddSingleXMLLiteral()");
+		if (TestUtils.SKIP) {
+			log.warn("SKIPPED");
+			return;
+		}
+		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));
 	}
 
 
@@ -271,6 +348,52 @@ public class VirtuosoMGraphTest {
 	}
 
 	@Test
+	public void testFilterObjectTyped() {
+		log.info("testFilterObjectTyped(); Test filter(null,null,o)");
+		if (TestUtils.SKIP) {
+			log.warn("SKIPPED");
+			return;
+		}
+		// 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);
+	}
+
+//	@Test
+	public void testFilterObjectXml() {
+		log.info("testFilterObjectXml(); Test filter(null,null,o)");
+		if (TestUtils.SKIP) {
+			log.warn("SKIPPED");
+			return;
+		}
+		// 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()");
 		if (TestUtils.SKIP) {
@@ -451,7 +574,11 @@ public class VirtuosoMGraphTest {
 		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/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/DataAccessTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/DataAccessTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/DataAccessTest.java
new file mode 100644
index 0000000..5783911
--- /dev/null
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/DataAccessTest.java
@@ -0,0 +1,107 @@
+package rdf.virtuoso.storage.access;
+
+import java.sql.SQLException;
+
+import org.apache.clerezza.rdf.core.BNode;
+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.impl.PlainLiteralImpl;
+import org.apache.clerezza.rdf.core.impl.TripleImpl;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import rdf.virtuoso.storage.TestUtils;
+
+public class DataAccessTest {
+
+	private static DataAccess da = null;
+
+	static Logger log = LoggerFactory.getLogger(DataAccessTest.class);
+	
+	@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());
+		Resource o = da.filter(g, null, null, null).next().getObject();
+		log.info("object: {}", o);
+		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/67d8506f/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
----------------------------------------------------------------------
diff --git a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
index 8c823df..8d704ac 100644
--- a/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
+++ b/clerezza-virtuoso/rdf.virtuoso.storage/src/test/java/rdf/virtuoso/storage/access/VirtuosoWeightedProviderTest.java
@@ -32,13 +32,14 @@ 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.TripleCollection;
 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.junit.After;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.slf4j.Logger;
@@ -244,20 +245,31 @@ public class VirtuosoWeightedProviderTest {
 		assertFalse(g.equals(g.getGraph()));
 	}
 
+	@Before
 	@After
 	public void clear() throws VirtuosoException, ClassNotFoundException,
 			SQLException {
 		log.info("clear()");
-		log.debug("Removing graph <{}>", TEST_GRAPH_URI);
 		if (TestUtils.SKIP) {
 			log.warn("SKIPPED");
 			return;
 		}
+		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
@@ -283,4 +295,57 @@ public class VirtuosoWeightedProviderTest {
 //			// Nothing to do
 //		}
 	}
+	
+	@Test
+	public void testEmptyAndNonEmptyGraphs(){
+		log.info("testEmptyAndNonEmptyGraphs()");
+		if (TestUtils.SKIP) {
+			log.warn("SKIPPED");
+			return;
+		}
+		
+		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));
+
+	}
 }