Vijith
Vijith

Reputation: 77

Read restriction values using Jena

I have an object restriction defined as follows

hasYear some integer[minLength 2, maxLength 4, >=1995, <=2012]

How can i read the individual values defined in the restriction using Jena.

Upvotes: 4

Views: 1461

Answers (1)

Lev Khomich
Lev Khomich

Reputation: 2247

You can use different approaches. First of all you can traverse Jena Model by the following code:

model.read(...);
StmtIterator si = model.listStatements(
        model.getResource("required property uri"), RDFS.range, (RDFNode) null);
while (si.hasNext()) {
    Statement stmt = si.next();
    Resource range = stmt.getObject().asResource();
    // get restrictions collection
    Resource nextNode = range.getPropertyResourceValue(OWL2.withRestrictions);
    for (;;) {
        Resource restr = nextNode.getPropertyResourceValue(RDF.first);
        if (restr == null)
            break;

        StmtIterator pi = restr.listProperties();
        while (pi.hasNext()) {
            Statement restrStmt = pi.next();
            Property restrType = restrStmt.getPredicate();
            Literal value = restrStmt.getObject().asLiteral();
            // print type and value for each restriction
            System.out.println(restrType + " = " + value);
        }
        // go to the next element of collection
        nextNode = nextNode.getPropertyResourceValue(RDF.rest);
    }
}

If you use OntModel representation of RDF graph code can be simplified by using of

model.listRestrictions()
ontClass.asRestriction()
etc.

Good example of such approach (thanks to Ian Dickinson)

Another way is to use SPARQL 1.1 query with the same meaning

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?datatype ?restr_type ?restr_value {
    ?prop rdfs:range ?range.
    ?range owl:onDatatype ?datatype;
        owl:withRestrictions ?restr_list.
    ?restr_list rdf:rest*/rdf:first ?restr.
    ?restr ?restr_type ?restr_value
}

Upvotes: 4

Related Questions