Tanguy PERRETTE
Tanguy PERRETTE

Reputation: 23

SHACL with Jena, how to get the Model after SPARQL CONSTRUCT from the shape?

I have this data file:

@prefix ex: <http://example.com/ns#> .

ex:John
   a ex:Person ;
   a ex:parent ;
   a ex:male .

And this shape file:

@prefix rdf:    <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:   <http://www.w3.org/2000/01/rdf-schema#> .
@prefix sh: <http://www.w3.org/ns/shacl#> .
@prefix xsd:    <http://www.w3.org/2001/XMLSchema#> .
@prefix ex: <http://example.com/ns#> .

ex:RuleOrderExampleShape
    a sh:NodeShape ;
    sh:targetClass ex:Person ;
    sh:rule [
        a sh:SPARQLRule;
        rdfs:label "Construct a father if someone is a parent and a male";
        sh:prefixes ex: ;
        sh:construct """
            CONSTRUCT {
                $this a ex:uncle .
            }
            WHERE {
                $this a ex:parent .
                $this a ex:male .
            }
            """
    ] .

My code is currently:

Model dataModel = ModelFactory.createDefaultModel();
dataModel.read(data);
Model shapeModel = ModelFactory.createDefaultModel();
shapeModel.read(shape);

Resource reportResource = ValidationUtil.validateModel(dataModel, shapeModel, true);

How can I get the model which will contain the new triple (ex:John a ex:father) ?

Upvotes: 2

Views: 577

Answers (1)

Henriette Harmse
Henriette Harmse

Reputation: 4787

Assuming you have included the dependencies in your pom.xml for SHACL

<dependency>
  <groupId>org.topbraid</groupId>
  <artifactId>shacl</artifactId>
  <version>1.0.1</version>
</dependency>

you can use the following code:

Model shapeModel = JenaUtil.createDefaultModel();
shapeModel.read(strShapeFile);
Model inferenceModel = JenaUtil.createDefaultModel(); 
inferenceModel = RuleUtil.executeRules(infModel, shapeModel, inferenceModel, null);        

inferenceModel will contain the new triples.

I have written about this on my blog as well. See for example SHACL rule execution where you can find complete code examples.

Upvotes: 4

Related Questions