Henriette's Notes

Home » Semantic technologies » RDF Stores

Category Archives: RDF Stores

Using SHACL validation with Ontotext GraphDB

Today I have 1 of those moments where I am absolutely sure if I do not write this down, I will forget how to do this next time. For one of the projects I am working on, we need to do SHACL validation of RDF data that will be stored in Ontotext GraphDB. Here are the 10 things I needed to learn in doing this. Some of these are rather obvious, but some were less than obvious to me.

Number 1: To be able to do SHACL validation, your repository needs to be configured for SHACL when you create your repository. This cannot be done after the fact.

Number 2: It seems to be better to import your ontology (or ontologies) and data into different graphs. This is useful when you want to re-import your ontology (or ontologies) or your data, because then you can replace a specific named graph completely. This was very useful for me while prototyping. Screenshot below:

Number 3: SHACL shapes are imported into this named graph


by default. At configuration time you can provide a different named graph or graphs for your SHACL shapes.

Number 4: To find the named graphs in your repository, you can do the following SPARQL query:

select distinct ?g 
where {
  graph ?g {?s ?p ?o }

You can then query a specific named graph as follows:

select * 
from <myNamedGraph>
where { 
	?s ?p ?o .

Number 5: However, getting the named graphs does not return the SHACL named graph. On StackOverflow someone suggested SHACL shapes can be retrieved using:


However, this did not work for me. Instead, the following code worked reliably:

import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.impl.LinkedHashModel;
import org.eclipse.rdf4j.model.vocabulary.RDF4J;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.http.HTTPRepository;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.WriterConfig;
import org.eclipse.rdf4j.rio.helpers.BasicWriterSettings;

import java.util.stream.Collectors;

public class RetrieveShaclShapes {
public static void main(String[] args) {
String address = args[0]; /* i.e. http://localhost/ */
String repositoryName = args[1]; /* i.e. myRepo */

HTTPRepository repository = new HTTPRepository(address, repositoryName);
try (RepositoryConnection connection = repository.getConnection()) {
Model statementsCollector = new LinkedHashModel(
connection.getStatements(null, null,null, RDF4J.SHACL_SHAPE_GRAPH)
Rio.write(statementsCollector, System.out, RDFFormat.TURTLE, new WriterConfig().set(
BasicWriterSettings.INLINE_BLANK_NODES, true));
} catch (Throwable t) {

using the following dependencies in the pom.xml with

${rdf4j.version} = 4.2.3: 

Number 6: Getting the above code to run was not obvious since I opted to using a fat jar. I encountered an “org.eclipse.rdf4j.rio.UnsupportedRDFormatException: Did not recognise RDF format object” error. RFD4J uses the Java Service Provider Interface (SPI) which uses a file in the META-INF/services of the jar to register parser implementations. The maven-assembly-plugin I used, to generate the fat jar, causes different jars to overwrite META-INF/services thereby loosing registration information. The solution is to use the maven-shade-plugin which merge META-INF/services rather overwrite it. In your pom you need to add the following to your plugins configuration:

                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>

You can avoid this problem by using the separate jars rather than a single fat jar.

Number 7: Importing a new shape into the SHACL shape graph will cause new shape information to be appended. It will not replace the existing graph even when you have both the

  • “Enable replacement of existing data” and
  • “I understand that data in the replaced graphs will be cleared before importing new data.”

options enabled as seen in the next screenshot:

To replace the SHACL named graph you need to clear it explicitly by running the following SPARQL command:

clear graph <http://rdf4j.org/schema/rdf4j#SHACLShapeGraph>

For myself I found it easier to update the SHACL shapes programmatically. Note that I made use of the default SHACL named graph:

import org.eclipse.rdf4j.model.vocabulary.RDF4J;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.http.HTTPRepository;
import org.eclipse.rdf4j.rio.RDFFormat;

import java.io.File;

public class UpdateShacl {
    public static void main(String[] args)  {
        String address = args[0]; /* i.e. http://localhost/ */
        String repositoryName = args[1]; /* i.e. myRepo */
        String shacl = args[2];
        File shaclFile = new File(shacl);

        HTTPRepository repository = new HTTPRepository(address, repositoryName);
        try (RepositoryConnection connection = repository.getConnection()) {
            connection.add(shaclFile, RDFFormat.TURTLE, RDF4J.SHACL_SHAPE_GRAPH);
        } catch (Throwable t) {

Number 8: Programmatically you can delete a named graph using this code and the same maven dependency as we used above:

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.http.HTTPRepository;

public class ClearGraph {
    public static void main(String[] args)  {
        String address = args[0]; /* i.e. http://localhost/ */
        String repositoryName = args[1]; /* i.e. myRepo */
        String graph = args[2]; /* i.e. http://rdf4j.org/schema/rdf4j#SHACLShapeGraph */

        ValueFactory valueFactory = SimpleValueFactory.getInstance();
        IRI graphIRI = valueFactory.createIRI(graph);
        HTTPRepository repository = new HTTPRepository(address, repositoryName);
        try (RepositoryConnection connection = repository.getConnection()) {

Number 9: If you update the shape graph with constraints that are violated by your existing data, you will need to first fix your data before you can upload your new shape definition.

Number 10: When uploading SHACL shapes, unsupported features fails silently. I had this idea to add human readable information to the shape definition to make it easier for users to understand validation errors. Unfortunately “sh:name” and “sh:description” are not supported by GraphDB version 10.0.2. and 10.2.0. Moreover, it fails silently. In the Workbench it will show that it loaded successfully as seen in the next screenshot:

However, in the logs I have noticed the following warnings:

As these are logged as warnings, I was expecting my shape to have loaded fine, except that triples pertaining to “sh:name” and “sh:description” are skipped. However, my shape did not load at all.

You find the list of supported SHACL features here.


This post may come across as being critical of GraphDB. However, this is not the intention. I think it is rather a case of growing pains that are still experienced around SHACL (and Shex, I suspect) adoption. Resources that have been helpful for me in resolving issues are:

Setting up Virtuoso on Ubuntu 18.04

I recently needed to setup a local instance of Virtuoso on my Ubuntu 18.04 laptop. In particular I needed to be able to specify the directory that Virtuoso is installed. This meant that using a Linux package manager was not an option. I therefore opted to install Virtuoso from source.

  1. Here are the steps I followed to do this:
    We are using Virtuoso 7.2.2. in our production environment, hence I downloaded virtuoso-opensource-7.2.2.tar.gz from Virtuoso downloads.
  2. Then I followed the instructions to build Virtuoso from Building from Upstream Source.
    1. Check build environment by running the following commands:
      sudo apt-get install dpkg-dev build-essential 
      sudo apt-get install autoconf automake libtool flex bison gperf gawk m4 make odbcinst libxml2-dev libssl-dev libreadline-dev
    2. Extract the file:
      tar xvpfz virtuoso-opensource-7.2.2.tar.gz
    3. Now to configure Virtuoso to install to a directory of your choice, in the directory you extracted the .tar.gz, run the following:
      ./configure --prefix=directory_of_choice
    4. To build Virtuoso, run:
      make nice

      This step failed for me with an error message that looks something like the following

      make[3]: Entering directory '~/virtuoso-opensource/libsrc/Wi'
      /bin/bash ../../libtool  --tag=CC   --mode=compile gcc -DHAVE_CONFIG_H -I. -I../../libsrc/Dk    -fno-strict-aliasing -O2  -Wall  -DNDEBUG -DPOINTER_64   -I/home/klimek/virtuoso-opensource/libsrc/Xml.new  -DOPENSSL_NO_KRB5 -Dlinux -D_GNU_SOURCE -DFILE64 -D_LARGEFILE64_SOURCE   -I../../libsrc -I../../libsrc/Dk -I../../libsrc/zlib -I. -I../../libsrc/langfunc -I../../libsrc/plugin -I../../libsrc/Tidy -I../../libsrc/Xml.new -I../../libsrc/odbcsdk/include -DVAD -DDBP -DBIF_XPER -DOPSYS=\"Linux\" -DHOST=\"x86_64-unknown-linux-gnu\" -g -O2 -MT libwi_la-bif_crypto.lo -MD -MP -MF .deps/libwi_la-bif_crypto.Tpo -c -o libwi_la-bif_crypto.lo `test -f 'bif_crypto.c' || echo './'`bif_crypto.c
      libtool: compile:  gcc -DHAVE_CONFIG_H -I. -I../../libsrc/Dk -fno-strict-aliasing -O2 -Wall -DNDEBUG -DPOINTER_64 -I/home/klimek/virtuoso-opensource/libsrc/Xml.new -DOPENSSL_NO_KRB5 -Dlinux -D_GNU_SOURCE -DFILE64 -D_LARGEFILE64_SOURCE -I../../libsrc -I../../libsrc/Dk -I../../libsrc/zlib -I. -I../../libsrc/langfunc -I../../libsrc/plugin -I../../libsrc/Tidy -I../../libsrc/Xml.new -I../../libsrc/odbcsdk/include -DVAD -DDBP -DBIF_XPER -DOPSYS=\"Linux\" -DHOST=\"x86_64-unknown-linux-gnu\" -g -O2 -MT libwi_la-bif_crypto.lo -MD -MP -MF .deps/libwi_la-bif_crypto.Tpo -c bif_crypto.c  -fPIC -DPIC -o .libs/libwi_la-bif_crypto.o
      bif_crypto.c: In function ‘box_hmac’:
      bif_crypto.c:184:12: error: storage size of ‘ctx’ isn’t known
         HMAC_CTX ctx;
      bif_crypto.c:190:3: warning: ‘HMAC_Init’ is deprecated [-Wdeprecated-declarations]
         HMAC_Init (&ctx, key, box_length (key) - DV_STRINGP (key) ? 1 : 0, md);

      which I fixed by installing libssl1.0-dev with

      sudo apt-get install libssl1.0-dev

      You can read more on this error here.
      After this re-run make nice.

    5. Lastly, I ran
      make install

      because I installed Virtuoso in my home directory. If you are not installing it in you home directory, you will need to run

      sudo make install
  3. To test your installation, go to localhost:8890.


Getting started with Ontotext GraphDB and Jena

In my previous post I explained how you can create an GraphDB repository and how you can update and query your repository using RDF4J. In this post I provide an example of how you can update and query a GraphDB repository using Jena. However, even though the code works, there are some pitfalls.

A Quick Example

First you need to add Jena as a Maven dependency:


The Java code is straightforward:

package org.graphdb.jena.tutorial;

import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.update.UpdateExecutionFactory;
import org.apache.jena.update.UpdateFactory;
import org.apache.jena.update.UpdateProcessor;
import org.apache.jena.update.UpdateRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

public class SimpleInsertQueryExample {
  private static Logger logger = LoggerFactory.getLogger(SimpleInsertQueryExample.class);
  // Why This Failure marker
  private static final Marker WTF_MARKER = MarkerFactory.getMarker("WTF");
  // GraphDB 
  private static final String PERSONDATA_REPO_QUERY = 
  private static final String PERSONDATA_REPO_UPDATE = 

  private static String strInsert;
  private static String strQuery;
  static {
    strInsert = 
        "INSERT DATA {"
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://dbpedia.org/ontology/birthDate>"
         + " \"1906-12-09\"^^<http://www.w3.org/2001/XMLSchema#date> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://dbpedia.org/ontology/birthPlace> "
         + "<http://dbpedia.org/resource/New_York_City> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://dbpedia.org/ontology/deathDate>"
         + " \"1992-01-01\"^^<http://www.w3.org/2001/XMLSchema#date> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://dbpedia.org/ontology/deathPlace> "
         + "<http://dbpedia.org/resource/Arlington_County,_Virginia> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://purl.org/dc/terms/description>"
         + " \"American computer scientist and United States Navy officer.\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> "
         + "<http://dbpedia.org/ontology/Person> ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://xmlns.com/foaf/0.1/gender> \"female\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://xmlns.com/foaf/0.1/givenName> \"Grace\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper> "
         + "<http://xmlns.com/foaf/0.1/name> \"Grace Hopper\" ."
         + "<http://dbpedia.org/resource/Grace_Hopper>"
         + " <http://xmlns.com/foaf/0.1/surname> \"Hopper\" ."        
         + "}";
    strQuery = 
        "SELECT ?name WHERE {?s <http://xmlns.com/foaf/0.1/name> ?name .}";
  private static void insert() {
    UpdateRequest updateRequest = UpdateFactory.create(strInsert);
    UpdateProcessor updateProcessor = UpdateExecutionFactory
  private static void query() {
    QueryExecution queryExecution = QueryExecutionFactory
        .sparqlService(PERSONDATA_REPO_QUERY, strQuery);
    for (ResultSet results = queryExecution.execSelect(); results.hasNext();) {
      QuerySolution qs = results.next();
      String strName = qs.get("?name").toString();
      logger.trace("name = " + strName);

  public static void main(String[] args) {
    try {
    } catch (Throwable t) {
      logger.error(WTF_MARKER, t.getMessage(), t);

Some Pitfalls

The example I provided will insert RDF data into GraphDB and query it successfully. However, the data is inserted into the repository in the absence of a transaction. The transaction API of Jena is based on a Dataset. Historically Ontotext provided a Jena adapter with which a Jena Dataset could be created. However, based on my question on Stack Overflow in this regard, the Jena adapter is no longer supported by Ontotext. Hence, currently it is not clear to me how to enable transactions when using Jena to access GraphDB. So, if you know how to address this, please be so kind as to leave a comment with your insight!


In this post I provided a quick example of how you can access GraphDB using Jena. However, this example does not support transactions, and therefore you may want to look at rather using RDF4J with GraphDB. You can find this code at github.