Fopa Léon Constantin
Fopa Léon Constantin

Reputation: 12363

How to count individuals of an owl class in Jena?

I'm working on automatic instanciation of an OWL model with Jena. Since every individual need an unique identifier.

How could I know the number of individual of a given OWL class in order to generate a new id for the next individual to instanciate in this Class ?

I've try with the following Jena Java code by using the method listIndividuals, Here It is, but It's not working.

import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.model.*;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;

public static int individualSize(Resource res){

        int size = 0;

        ExtendedIterator<Individual> individuals = domainModel.listIndividuals(res);

        while (individuals.next() != null){ size++; }

        return size;
}

static String xmlbase = "http://www.semantic.org/ontologies/exemple.owl#";
OntModel domainModel = ModelFactory.createOntologyModel(ProfileRegistry.OWL_DL_LANG);
domainModel.read((new FileInputStream(ontoInPath)), null);

int nextId = individualSize(domainModel.getOntClass(xmlbase+"Event"));

System.out.print(nextId);

The Error is :

Exception in thread "main" java.util.NoSuchElementException
    at com.hp.hpl.jena.util.iterator.NiceIterator.ensureHasNext(NiceIterator.java:37)
    at com.hp.hpl.jena.util.iterator.UniqueExtendedIterator.next(UniqueExtendedIterator.java:77)
    at soctrace.Intology.individualSize(Intology.java:225)
    at soctrace.Intology.manageOntologies(Intology.java:124)
    at soctrace.Intology.main(Intology.java:65)

Is there any method from the Jena API that can help me to do this more easily ?

if no ! How could I correct my code.

Thanks you for any reply !

Upvotes: 1

Views: 2496

Answers (2)

Michael
Michael

Reputation: 4886

Your code:

while (individuals.next() != null){ size++; }

Is not the correct way to use an iterator, what you want is this:

while (individuals.hasNext()) {
  size++;
  individuals.next();
}

You might also want to close that FileInputStream if Model.read does not do so already.

Furthermore, if you're planning on working with OWL, you will want to look at using OWLAPI which is an OWL-centric Java API. Jena is great, but it's more RDF/triples centric which makes it cumbersome (in my experience at least) to use for real OWL-based applications. You probably also want to look into using a dedicated OWL reasoner such as HermiT or Pellet if you're going to be doing a lot of reasoning in your application.

Upvotes: 4

tsm
tsm

Reputation: 3658

If I'm doing the math right you have an off-by-one error anyway. Try:

public static int individualSize(Resource res){

    int size = 0;
    ExtendedIterator<Individual> individuals = domainModel.listIndividuals(res);

    while(individuals.hasNext()) {
        individuals.next();
        size++;
    }
    return size;
}

Upvotes: 2

Related Questions