On 08/06/11 22:10, Danai Symeonidou wrote:
Dear jena-list, I have tried a lot to solve the following issue, and
read a lot of stuff on the internet but i didnt make it in the end. Iam
really desperate..:-(

Here I have a set of OntClasses and what I try to do is to find and
print for each class the properties that appear in the domain and in the
range of this class.
With listDeclaredProperties() I can have an iteration of the properties
that are associated with this class by their domain.
MY PROBLEM is that I cannot find the iteration associated with this
class by their range.
One simple way to solve this would be with a SPARQL query:

select distinct ?p where {
 {?p rdfs:range ?cls}
 union
 {?p rdfs:range ?d.
  ?cls rdfs:subClassOf ?d}
}

That is: select distinct properties whose range is either the class you are interested in, or one of its super-classes. I've attached an example of how to run that query, with ?cls bound to the class you're trying to investigate.

Ian
package example;

import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.vocabulary.RDFS;


public class DanaiExample
{
    public static void main( String[] args ) {
        // set up a test model
        OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
        String ns = "http://example.com/test#";;
        OntClass a = m.createClass( ns + "A" );
        OntClass b = m.createClass( ns + "B" );
        OntClass c = m.createClass( ns + "C" );

        OntProperty p = m.createOntProperty( ns + "p" );
        OntProperty q = m.createOntProperty( ns + "q" );
        OntProperty r = m.createOntProperty( ns + "r" );

        a.addSubClass( b );
        b.addSubClass( c );

        p.addRange( b );
        q.addRange( a );
        q.addRange( c );

        // the query we want to test
        String qStr = "prefix rdfs: <" + RDFS.getURI() + ">"  +
                "select distinct ?p where {\n" +
                " {?p rdfs:range ?cls}\n" +
                " union\n" +
                " {?p rdfs:range ?d.\n" +
                "  ?cls rdfs:subClassOf ?d}\n" +
                "}";

        // bind ?cls to example:B
        QuerySolutionMap preBindings = new QuerySolutionMap();
        preBindings.add( "cls", b );

        // run the query
        Query query = QueryFactory.create( qStr );
        QueryExecution exec = QueryExecutionFactory.create(query, m, preBindings );
        ResultSet results = exec.execSelect();

        while (results.hasNext()) {
            System.out.println( "Solution: " + results.next() );
        }
    }
}

Reply via email to