I've made an Ontology in Protege and i want to create new individuals using eclipse i' using this code
public class testOwl2 {
public static final String SOURCE_URL = "http://www.semanticweb.org/nira/ontologies/2022/3/untitled-ontology-9";
// where we've stashed it on disk for the time being
protected static final String SOURCE_FILE = "C:\\Users\\benni\\Ontologies\\L'ontologie classique.owl";
// the namespace of the ontology
public static final String NS = SOURCE_URL + "#";
/***********************************/
/* External signature methods */
/***********************************/
public void run() {
OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM );
loadModel( m );
// get an OntClass reference to one of the classes in the model
// note: ideally, we would delegate this step to Jena's schemagen tool
OntClass Patient = m.getOntClass( NS + "Patient" );
//OntProperty Patient_relation = m.getObjectProperty( NS + "Has_sign" );
// similarly a reference to the attack duration property,
// and again, using schemagen would be better
OntProperty Patient_Crea = m.getDatatypeProperty( NS + "Creatinine_value" );
// create an instance of the attack class to represent the current attack
Individual Patient1 = m.createIndividual( NS + "P4", Patient );
// add a duration to the attack
Patient1.addProperty( Patient_Crea, m.createTypedLiteral( 10 ) );
m.prepare();
// finally, print out the model to show that we have some data
m.write( System.out, "Turtle" );
}
/***********************************/
/* Internal implementation methods */
/***********************************/
/** read the ontology and add it as a sub-model of the given ontmodel */
protected void loadModel( OntModel m ) {
FileManager.get().getLocationMapper().addAltEntry( SOURCE_URL, SOURCE_FILE );
Model baseOntology = FileManager.get().loadModel( SOURCE_URL );
m.addSubModel( baseOntology );
// for compactness, add a prefix declaration st: (for Sam Thomas)
m.setNsPrefix( "st", NS );
}
public static void main( String[] args ) {
new testOwl2().run();}}
Output
#prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
#prefix st: <http://www.semanticweb.org/nira/ontologies/2022/3/untitled-ontology-9#> .
#prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
#prefix owl: <http://www.w3.org/2002/07/owl#> .
#prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
st:P4
a st:Patient ;
st:Creatinine_value "10"^^xsd:int .
But in the owl file (protege) i dont have any individuals that i creat in my ontology could u guys tell what wrong with this code and where can i find this individuals ...thank you
Related
I am novice to java however, I cannot seem to figure this one out. I have a CSV file in the following format:
String1,String2
String1,String2
String1,String2
String1,String2
Each line are pairs. The 2nd line is a new record, same with the 3rd. In the real word the CSV file will change in size, sometimes it will be 3 records, or 4, or even 10.
My issues is how do I read the values into an array and dynamically adjust the size? I would imagine, first we would have to parse though the csv file, get the number of records/elements, then create the array based on that size, then go though the CSV again and store it in the array.
I'm just not sure how to accomplish this.
Any help would be appreciated.
You can use ArrayList instead of Array. An ArrayList is a dynamic array. ex.
Scanner scan = new Scanner(new File("yourfile"));
ArrayList<String[]> records = new ArrayList<String[]>();
String[] record = new String[2];
while(scan.hasNext())
{
record = scan.nextLine().split(",");
records.add(record);
}
//now records has your records.
//here is a way to loop through the records (process)
for(String[] temp : records)
{
for(String temp1 : temp)
{
System.out.print(temp1 + " ");
}
System.out.print("\n");
}
Just replace "yourfile" with the absolute path to your file.
You could do something like this.
More traditional for loop for processing the data if you don't like the first example:
for(int i = 0; i < records.size(); i++)
{
for(int j = 0; j < records.get(i).length; j++)
{
System.out.print(records.get(i)[j] + " ");
}
System.out.print("\n");
}
Both for loops are doing the same thing though.
You can simply read the CSV into a 2-dimensional array just in 2 lines with the open source library uniVocity-parsers.
Refer to the following code as an example:
public static void main(String[] args) throws FileNotFoundException {
/**
* ---------------------------------------
* Read CSV rows into 2-dimensional array
* ---------------------------------------
*/
// 1st, creates a CSV parser with the configs
CsvParser parser = new CsvParser(new CsvParserSettings());
// 2nd, parses all rows from the CSV file into a 2-dimensional array
List<String[]> resolvedData = parser.parseAll(new FileReader("/examples/example.csv"));
// 3rd, process the 2-dimensional array with business logic
// ......
}
tl;dr
Use the Java Collections rather than arrays, specifically a List or Set, to auto-expand as you add items.
Define a class to hold your data read from CSV, instantiating an object for each row read.
Use the Apache Commons CSV library to help with the chore of reading/writing CSV files.
Class to hold data
Define a class to hold the data of each row being read from your CSV. Let's use Person class with a given name and surname, to be more concrete than the example in your Question.
In Java 16 and later, more briefly define the class as a record.
record Person ( String givenName , String surname ) {}
In older Java, define a conventional class.
package work.basil.example;
public class Person {
public String givenName, surname;
public Person ( String givenName , String surname ) {
this.givenName = givenName;
this.surname = surname;
}
#Override
public String toString ( ) {
return "Person{ " +
"givenName='" + givenName + '\'' +
" | surname='" + surname + '\'' +
" }";
}
}
Collections, not arrays
Using the Java Collections is generally better than using mere arrays. The collections are more flexible and more powerful. See Oracle Tutorial.
Here we will use the List interface to collect each Person object instantiated from data read in from the CSV file. We use the concrete ArrayList implementation of List which uses arrays in the background. The important part here, related to your Question, is that you can add objects to a List without worrying about resizing. The List implementation is responsible for any needed resizing.
If you happen to know the approximate size of your list to be populated, you can supply an optional initial capacity as a hint when creating the List.
Apache Commons CSV
The Apache Commons CSV library does a nice job of reading and writing several variants of CSV and Tab-delimited formats.
Example app
Here is an example app, in a single PersoIo.java file. The Io is short for input-output.
Example data.
GivenName,Surname
Alice,Albert
Bob,Babin
Charlie,Comtois
Darlene,Deschamps
Source code.
package work.basil.example;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class PersonIo {
public static void main ( String[] args ) {
PersonIo app = new PersonIo();
app.doIt();
}
private void doIt ( ) {
Path path = Paths.get( "/Users/basilbourque/people.csv" );
List < Person > people = this.read( path );
System.out.println( "People: \n" + people );
}
private List < Person > read ( final Path path ) {
Objects.requireNonNull( path );
if ( Files.notExists( path ) ) {
System.out.println( "ERROR - no file found for path: " + path + ". Message # de1f0be7-901f-4b57-85ae-3eecac66c8f6." );
}
List < Person > people = List.of(); // Default to empty list.
try {
// Hold data read from file.
int initialCapacity = ( int ) Files.lines( path ).count();
people = new ArrayList <>( initialCapacity );
// Read CSV file.
BufferedReader reader = Files.newBufferedReader( path );
Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
for ( CSVRecord record : records ) {
// GivenName,Surname
// Alice,Albert
// Bob,Babin
// Charlie,Comtois
// Darlene,Deschamps
String givenName = record.get( "GivenName" );
String surname = record.get( "Surname" );
// Use read data to instantiate.
Person p = new Person( givenName , surname );
// Collect
people.add( p ); // For real work, you would define a class to hold these values.
}
} catch ( IOException e ) {
e.printStackTrace();
}
return people;
}
}
When run.
People:
[Person{ givenName='Alice' | surname='Albert' }, Person{ givenName='Bob' | surname='Babin' }, Person{ givenName='Charlie' | surname='Comtois' }, Person{ givenName='Darlene' | surname='Deschamps' }]
I'm trying to use the Jena OntModel to get the direct relations of an ontology.
Problems come from the listClasses() method.
I searched a while for tips on the net but don't find relevant answer to my problem.
So here comes a complete example with minimal data and code showing what's wrong.
I have a for example this basic ontology (N-Triple formated):
<http://weblab.ow2.org/wookie#Anti-social_behaviour> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#CriminalEvent>.
<http://weblab.ow2.org/wookie#Robbery> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#CriminalEvent>.
<http://weblab.ow2.org/wookie#Vehicle_crime> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#CriminalEvent>.
<http://weblab.ow2.org/wookie#Bicycle_theft> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#CriminalEvent>.
<http://weblab.ow2.org/wookie#CriminalEvent> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#Event>.
<http://weblab.ow2.org/wookie#Event> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#WookieThing>.
<http://weblab.ow2.org/wookie#Event> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Class>.
I basically would like to be able to get the all the classes, and for each class, get subClasses.
I use the following JAVA code :
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.util.FileManager;
public class Main {
public static void main(final String [] argv) throws FileNotFoundException, IOException {
final OntModel model = ModelFactory.createOntologyModel();
model.read(FileManager.get().open("./src/test/resources/eventOnto.n3"), "", "N-TRIPLE");
// This part allows to check that the ontology model is really loaded and that inference is
// correctly done. WORKING
final List<Statement> statements = model.listStatements().toList();
Collections.sort(statements, new Comparator<Statement>() {
#Override
public int compare(final Statement o1, final Statement o2) {
return o1.toString().compareTo(o2.toString());
}
});
for (final Statement statement : statements) {
System.out.println(statement);
}
System.out.println("-------------------------------------------------");
// Listing all the classes.
final List<OntClass> classes = model.listClasses().toList();
for (final OntClass ontclass : classes) {
System.out.println(ontclass);
}
System.out.println("-------------------------------------------------");
// Bug got nothing. So try with a SPARQL query...
final Query query = QueryFactory.create("PREFIX rdf:<http://www.w3.org/2000/01/rdf-schema#> SELECT distinct ?class WHERE {?class a rdf:Class.}");
final ResultSet queryResult = QueryExecutionFactory.create(query, model).execSelect();
while (queryResult.hasNext()) {
System.out.println(queryResult.next());
}
// and got many results...
}
Prints show that the ontology model is correctly loaded and basic inference is done. It also show that the getClasses() don't return anything while the SPARQL query that ask for classes got every single class.
[http://weblab.ow2.org/wookie#Anti-social_behaviour, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2000/01/rdf-schema#Class]
[http://weblab.ow2.org/wookie#Anti-social_behaviour, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2000/01/rdf-schema#Resource]
[http://weblab.ow2.org/wookie#Anti-social_behaviour, http://www.w3.org/2000/01/rdf-schema#subClassOf, http://weblab.ow2.org/wookie#Anti-social_behaviour]
[http://weblab.ow2.org/wookie#Anti-social_behaviour, http://www.w3.org/2000/01/rdf-schema#subClassOf, http://weblab.ow2.org/wookie#CriminalEvent]
[http://weblab.ow2.org/wookie#Anti-social_behaviour, http://www.w3.org/2000/01/rdf-schema#subClassOf, http://weblab.ow2.org/wookie#Event]
[http://weblab.ow2.org/wookie#Anti-social_behaviour, http://www.w3.org/2000/01/rdf-schema#subClassOf, http://weblab.ow2.org/wookie#WookieThing]
[http://weblab.ow2.org/wookie#Anti-social_behaviour, http://www.w3.org/2000/01/rdf-schema#subClassOf, http://www.w3.org/2000/01/rdf-schema#Resource]
[http://weblab.ow2.org/wookie#Anti-social_behaviour, http://www.w3.org/2000/01/rdf-schema#subClassOf, http://www.w3.org/2002/07/owl#Thing]
...(many other lines)...
-------------------------------------------------
-------------------------------------------------
( ?class = rdf:Property )
( ?class = rdf:List )
( ?class = rdfs:Resource )
( ?class = rdfs:Class )
( ?class = rdf:Statement )
( ?class = rdfs:Literal )
( ?class = <http://weblab.ow2.org/wookie#Event> )
( ?class = rdf:XMLLiteral )
( ?class = owl:Thing )
( ?class = <http://weblab.ow2.org/wookie#WookieThing> )
( ?class = <http://weblab.ow2.org/wookie#CriminalEvent> )
( ?class = rdfs:Container )
( ?class = <http://weblab.ow2.org/wookie#Robbery> )
( ?class = <http://weblab.ow2.org/wookie#Bicycle_theft> )
( ?class = rdf:Seq )
( ?class = rdf:Alt )
( ?class = <http://weblab.ow2.org/wookie#Anti-social_behaviour> )
( ?class = <http://weblab.ow2.org/wookie#Vehicle_crime> )
( ?class = rdfs:ContainerMembershipProperty )
( ?class = rdf:Bag )
( ?class = rdfs:Datatype )
Do anyone know why the OntModel.getClasses() don't return anything ?
You get no results for two reasons.
The default ontology profile is an OWL profile, so you're getting an OWL model use getOntologyModel without a particular OntModelSpec. Instead, you should probably be using an RDFS ontology model. That will make listClasses look for instances of rdfs:Class rather than owl:Class. That will still only get you one result, though, because you've only declared one thing to be an rdfs:Class.
You've only declared one thing as an rdfs:Class, and the rest are supposed to be inferred to be rdfs:Classes based on the fact that they're subclasses of something else. That means that you need to use an inference model. In this case, you probably want an RDFS inference model, but because (some of) Jena's OWL reasoners include the RDFS rules, you might be able to use an OWL model too.
Here's code that loads your data into a few different types of models and shows the results of listClasses:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
public class ListClassesExample {
public static void main(String[] args) throws IOException {
String content =
"<http://weblab.ow2.org/wookie#Anti-social_behaviour> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#CriminalEvent>.\n" +
"<http://weblab.ow2.org/wookie#Robbery> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#CriminalEvent>.\n" +
"<http://weblab.ow2.org/wookie#Vehicle_crime> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#CriminalEvent>.\n" +
"<http://weblab.ow2.org/wookie#Bicycle_theft> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#CriminalEvent>.\n" +
"<http://weblab.ow2.org/wookie#CriminalEvent> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#Event>.\n" +
"<http://weblab.ow2.org/wookie#Event> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://weblab.ow2.org/wookie#WookieThing>.\n" +
"<http://weblab.ow2.org/wookie#Event> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Class>.";
final Model base = ModelFactory.createDefaultModel();
try ( InputStream in = new ByteArrayInputStream( content.getBytes() )) {
RDFDataMgr.read( base, in, Lang.NTRIPLES );
}
System.out.println( "== OWL Classes (no inference) ==" );
OntModel owlOntology = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM, base );
for ( OntClass klass : owlOntology.listClasses().toList() ) {
System.out.println( klass );
}
System.out.println( "== RDFS Classes (no inference) ==" );
OntModel rdfsOntology = ModelFactory.createOntologyModel( OntModelSpec.RDFS_MEM, base );
for ( OntClass klass : rdfsOntology.listClasses().toList() ) {
System.out.println( klass );
}
System.out.println( "== RDFS Classes (with inference) ==" );
OntModel rdfsOntologyInf = ModelFactory.createOntologyModel( OntModelSpec.RDFS_MEM_RDFS_INF, base );
for ( OntClass klass : rdfsOntologyInf.listClasses().toList() ) {
System.out.println( klass );
}
System.out.println( "== End ==");
}
}
== OWL Classes (no inference) ==
== RDFS Classes (no inference) ==
http://weblab.ow2.org/wookie#Event
== RDFS Classes (with inference) ==
http://www.w3.org/1999/02/22-rdf-syntax-ns#Property
http://www.w3.org/1999/02/22-rdf-syntax-ns#List
http://www.w3.org/2000/01/rdf-schema#Resource
http://www.w3.org/2000/01/rdf-schema#Class
http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement
http://www.w3.org/2000/01/rdf-schema#Literal
http://weblab.ow2.org/wookie#Event
http://weblab.ow2.org/wookie#WookieThing
http://weblab.ow2.org/wookie#CriminalEvent
http://www.w3.org/2000/01/rdf-schema#Container
http://weblab.ow2.org/wookie#Robbery
http://weblab.ow2.org/wookie#Bicycle_theft
http://www.w3.org/1999/02/22-rdf-syntax-ns#Seq
http://www.w3.org/1999/02/22-rdf-syntax-ns#Alt
http://weblab.ow2.org/wookie#Anti-social_behaviour
http://weblab.ow2.org/wookie#Vehicle_crime
http://www.w3.org/2000/01/rdf-schema#ContainerMembershipProperty
http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag
http://www.w3.org/2000/01/rdf-schema#Datatype
http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral
== End ==
This has some classes that you didn't mention, because the RDFS axioms entail them. If you just want the things that are declared as rdfs:Classes in your data, and the subclasses of them, you could use a SPARQL query:
String query = "\n" +
"prefix rdfs: <"+RDFS.getURI()+">\n" +
"\n" +
"select distinct ?class where {\n" +
" { ?class a rdfs:Class } union\n" +
" { ?class rdfs:subClassOf|^rdfs:subClassOf [] }\n" +
"}";
ResultSet results = QueryExecutionFactory.create( query, base ).execSelect();
System.out.println( query );
ResultSetFormatter.out( results );
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
select distinct ?class where {
{ ?class a rdfs:Class } union
{ ?class rdfs:subClassOf|^rdfs:subClassOf [] }
}
--------------------------------------------------------
| class |
========================================================
| <http://weblab.ow2.org/wookie#Event> |
| <http://weblab.ow2.org/wookie#Bicycle_theft> |
| <http://weblab.ow2.org/wookie#Anti-social_behaviour> |
| <http://weblab.ow2.org/wookie#WookieThing> |
| <http://weblab.ow2.org/wookie#Vehicle_crime> |
| <http://weblab.ow2.org/wookie#CriminalEvent> |
| <http://weblab.ow2.org/wookie#Robbery> |
--------------------------------------------------------
I have my class Alert which contain as individual
Alert_1
Alert_2
Alert_3
and each individual has properties witch contains values
for example
Alert_1 :
hasanalyser : analyser546
hastime: 10
hasdatainfo: difficult
I can now get all individuals but I can not get those (hasanalyser, hastime and hasdatainfo) values
Here is my code and it works. How I can get what I want please?
owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");
OntModel model = owlModel.getOntModel();
OWLNamedClass theAlert = owlModel.getOWLNamedClass("Alert");
Collection CAlerte = theAlert.getInstances();
int nombreAlerte =CAlerte.size();
String[ ] list_alerte=new String[ nombreAlerte ];
OWLIndividual[ ] idorg=(OWLIndividual[ ]) CAlerte.toArray(new OWLIndividual[ 0 ]);
for(int j=0;j< nombreAlerte;j++){
list_alerte[ j ]=idorg[ j ].getName();
}
System.out.println(" le nombres des alerte est:"+nombreAlerte);
OntModel inf1 = ModelFactory.createOntologyModel();
for(int k=0;k< nombreAlerte;k++){
System.out.println(" \n"+list_alerte[k]);
}
Here it display my
Alert_1
Alert_2
Alert_3
How to get their properties?
UPDATE:
Thanks for your answer, it doesn't work yet. I tried now to do like you said
JenaOWLModel owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");
OntModel model = owlModel.getOntModel();
ArrayList<Resource> results = new ArrayList<Resource>();
ExtendedIterator individuals = model.listIndividuals();
while (individuals.hasNext()) {
Resource individual = (Resource) individuals.next();
results.add(individual);
}
for(int i = 0; i < results.size(); i++)
{
System.out.println("individual number " + i + " = " + results.get(i));//here it display my individual
Individual ind = model.getIndividual(results.get(i).toString());
Property hasTime = model.createProperty( "file:///D:/base_connaissance.owl#hasanalyser" );
RDFNode time = ind.getPropertyValue( hasTime );
System.out.println("property value of hasanalyser "+time);
At the end it displays all names of my individuals, and after each individual it display property value of hasanalyser NULL.
where is the problème please
IT WORK NOW , i can get now all properties of all individuals thanks lot , now what it doesnt work is HOW to add an individual and add properties to this individual and insert it into my "base_connaissance.owl" if you can help me i realy appreciate it here is the full code witch work perfectly .
static JenaOWLModel owlModel ;
public static void main(String[] args) {
OntModel model;
javax.swing.JDialog jDialog1 = new javax.swing.JDialog();
try{
String ns="file:///D:/base_connaissance.owl#";
owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");// crée un modele owl a partir du ficher owl charger
model = owlModel.getOntModel();
JOptionPane.showMessageDialog(jDialog1,"chargement du fichier effectuer avec succé","Information",JOptionPane.INFORMATION_MESSAGE);
ArrayList<Resource> results = new ArrayList<Resource>();
ExtendedIterator individuals = model.listIndividuals();
while (individuals.hasNext()) {
Resource individual = (Resource) individuals.next();
results.add(individual);
}
System.out.println("\n");
for(int i = 0; i < results.size(); i++)
{
Individual ind = model.getIndividual(results.get(i).toString());
System.out.println(""+ind);
StmtIterator it = ind.listProperties();
while ( it.hasNext()) {
Statement s = (Statement) it.next();
if (s.getObject().isLiteral()) {
System.out.println(""+s.getLiteral().getLexicalForm().toString()+" type = "+s.getPredicate().getLocalName());
}
else System.out.println(""+s.getObject().toString().substring(53)+" type = "+s.getPredicate().getLocalName());
}
System.out.println("\n");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(jDialog1,
"error",
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
I'm not clear from your code how you are using Jena models. The OntModel called model does not appear to be used, nor does the InfModel called inf1. OWLIndividual is not a Jena class, but a Protégé one. The question asks about using the Jena API, however, so the rest of this answer assumes that you can get the Individuals that you are interested in, not the OWLIndividuals.
Jena's Individuals have a method getPropertyValue that returns the value of a property for the individual. You should be able to do something like this:
Individual alert1 = ...;
String hasTimeURI = "...";
Property hasTime = model.createProperty( hasTimeURI );
RDFNode time = alert1.getPropertyValue( hasTime );
The additional code you posted is printing null probably because the IRI for the property is incorrect. File-based IRIs are not very good identifiers; URIs are supposed to be universal identifiers, and something that includes a file path almost certainly isn't going to be universal. Without seeing your data, we cannot know what the proper IRI for the property should be. However, if you do something like this, you should be able to get enough information to determine what the property IRI should be.
Individual ind = model.getIndividual(results.get(i).toString());
// Check whether ind is null.
System.out.println( "ind: "+ind );
// Iterate over all the statements that have ind as subject.
StmtIterator it = ind.ListProperties();
while ( it.hasNext() ) {
System.out.println( it.next() );
}
I'm currently following the Jena API inferencing tutorial:
https://jena.apache.org/documentation/inference/
and as an exercise to test my understanding, I'd like to rewrite the first example, which demonstrates a trivial RDFS reasoning from a programmatically built model:
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.vocabulary.*;
public class Test1 {
static public void main(String...argv) {
String NS = "foo:";
Model m = ModelFactory.createDefaultModel();
Property p = m.createProperty(NS, "p");
Property q = m.createProperty(NS, "q");
m.add(p, RDFS.subPropertyOf, q);
m.createResource(NS + "x").addProperty(p, "bar");
InfModel im = ModelFactory.createRDFSModel(m);
Resource x = im.getResource(NS + "x");
// verify that property q of x is "bar" (which follows
// from x having property p, and p being a subproperty of q)
System.out.println("Statement: " + x.getProperty(q));
}
}
to something which does the same, but with the model read from this Turtle file instead (which is my own translation of the above, and thus might be buggy):
#prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>.
#prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.
#prefix foo: <http://example.org/foo#>.
foo:p a rdf:Property.
foo:q a rdf:Property.
foo:p rdfs:subPropertyOf foo:q.
foo:x foo:p "bar".
with this code:
public class Test2 {
static public void main(String...argv) {
String NS = "foo:";
Model m = ModelFactory.createDefaultModel();
m.read("foo.ttl");
InfModel im = ModelFactory.createRDFSModel(m);
Property q = im.getProperty(NS + "q");
Resource x = im.getResource(NS + "x");
System.out.println("Statement: " + x.getProperty(q));
}
}
which doesn't seem to be the right approach (I suspect in particular that my extraction of the q property is somehow not right). What am I doing wrong?
String NS = "foo:";
m.createResource(NS + "x")
creates a URI but the Turtle version has foo:x = http://example.org/foo#x
See the differences by printing the model im.write(System.out, "TTL");
Change NS = "foo:" to NS = "http://example.org/foo#"
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.
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
}