Sections
You are here: Home » Data » Documents » Development » RDF files » Java developers only » Jena code snippets

Jena code snippets

— filed under: , , ,

Short examples how to use jena.sourceforge.net

JENA

http://jena.sourceforge.net

An introduction to RDF and the Jena RDF API

The Jena ontology API

Jena I/O Mini How To

Examples for using OWL reasoners and SPARQL

 

 

OpenTox classes and  properties

package org.opentox.owl;

import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;

public class OT {
	public enum OTClass {
		Compound,
		Conformer,
		Dataset,
		DataEntry,
		Feature,
		FeatureValue,
		Algorithm,
		Model,
		Validation,
		ValidationInfo;
		public String getNS() {
			return String.format(_NS, toString());
		}
		public OntClass getOntClass(OntModel model) {
			return model.getOntClass(getNS());
		}
		public OntClass createOntClass(OntModel model) {
			return model.createClass(getNS());
		}		
		public Property createProperty(OntModel model) {
			return model.createProperty(getNS());
		}			

	};
	/** <p>The RDF model that holds the vocabulary terms</p> */
	private static Model m_model = ModelFactory.createDefaultModel();
	/** <p>The namespace of the vocabalary as a string ({@value})</p> */
	protected static final String _NS = "http://www.opentox.org/api/1.1#%s";
	public static final String NS = String.format(_NS,"");
	
	public static String getURI() {return NS;}
	/** <p>The namespace of the vocabalary as a resource</p> */
        public static final Resource NAMESPACE = m_model.createResource( NS );

    /**
     * Object properties
     */
    public static final Property dataEntry = m_model.createProperty(String.format(_NS, "dataEntry"));
    public static final Property compound = m_model.createProperty(String.format(_NS, "compound"));
    public static final Property feature = m_model.createProperty(String.format(_NS, "feature"));
    public static final Property values = m_model.createProperty(String.format(_NS, "values"));
    public static final Property hasSource = m_model.createProperty(String.format(_NS, "hasSource"));
    public static final Property conformer = m_model.createProperty(String.format(_NS, "conformer"));
    public static final Property isA = m_model.createProperty(String.format(_NS, "isA"));
    public static final Property model = m_model.createProperty(String.format(_NS, "model"));
    public static final Property report = m_model.createProperty(String.format(_NS, "report"));
    public static final Property algorithm = m_model.createProperty(String.format(_NS, "algorithm"));
    public static final Property dependentVariables = m_model.createProperty(String.format(_NS, "dependentVariables"));
    public static final Property independentVariables = m_model.createProperty(String.format(_NS, "independentVariables"));
    public static final Property predictedVariables = m_model.createProperty(String.format(_NS, "predictedVariables"));
    public static final Property trainingDataset = m_model.createProperty(String.format(_NS, "trainingDataset"));
    public static final Property validationReport = m_model.createProperty(String.format(_NS, "validationReport"));
    public static final Property validation = m_model.createProperty(String.format(_NS, "validation"));
    public static final Property hasValidationInfo = m_model.createProperty(String.format(_NS, "hasValidationInfo"));
    public static final Property validationModel = m_model.createProperty(String.format(_NS, "validationModel"));
    public static final Property validationPredictionDataset = m_model.createProperty(String.format(_NS, "validationPredictionDataset"));
    public static final Property validationTestDataset = m_model.createProperty(String.format(_NS, "validationTestDataset"));
    /**
     * Data properties
     */
    public static final Property value = m_model.createProperty(String.format(_NS, "value"));
    public static final Property units = m_model.createProperty(String.format(_NS, "units"));
    public static final Property has3Dstructure = m_model.createProperty(String.format(_NS, "has3Dstructure"));
    public static final Property hasStatus = m_model.createProperty(String.format(_NS, "hasStatus"));
    public static final Property paramScope = m_model.createProperty(String.format(_NS, "paramScope"));
    public static final Property paramValue = m_model.createProperty(String.format(_NS, "paramValue"));
    public static final Property statisticsSupported = m_model.createProperty(String.format(_NS, "statisticsSupported"));

}

 

Create Jena Model with support for OWL

Create an empty model

OntModel jenaModel = createModel();
..	
public OntModel createModel() throws Exception {
		OntModel jenaModel = ModelFactory.createOntologyModel( OntModelSpec.OWL_DL_MEM,null);
		jenaModel.setNsPrefix( "ot", OT.NS );
		jenaModel.setNsPrefix( "owl", OWL.NS );
		jenaModel.setNsPrefix( "dc", DC.NS );
		return jenaModel;
}

Add an empy Dataset

		Individual dataset = jenaModel.createIndividual("Dataset URI",
					jenaModel.getOntClass(OT.OTClass.Dataset.getNS()));

		OT.OTClass.Dataset.createOntClass(jenaModel);
		OT.OTClass.DataEntry.createOntClass(jenaModel);
		OT.OTClass.Feature.createOntClass(jenaModel);
		OT.OTClass.FeatureValue.createOntClass(jenaModel);
		OT.OTClass.Compound.createOntClass(jenaModel);

Add an empty Data Entry to the dataset

Individual dataEntry = jenaModel.createIndividual(OT.OTClass.DataEntry.getOntClass(jenaModel));
dataset.addProperty(OT.dataEntry,dataEntry);

Set Compound to the data entry

Individual compound = jenaModel.createIndividual("compoundURI",OT.OTClass.Compound.getOntClass(jenaModel));
dataEntry.addProperty(OT.compound, compound);

Add feature values

//First value
Individual feature1 = jenaModel.createIndividual("featureURI1",OT.OTClass.Feature.getOntClass(jenaModel));
Individual featureValu1e = jenaModel.createIndividual(OT.OTClass.FeatureValue.getOntClass(jenaModel));
featureValue1.addProperty(OT.feature,feature1);
featureValue1.addLiteral(OT.value,jenaModel.createTypedLiteral("formaldehyde",XSDDatatype.XSDstring));

//Second value
Individual feature2 = jenaModel.createIndividual("featureURI2",OT.OTClass.Feature.getOntClass(jenaModel));
Individual featureValue2 = jenaModel.createIndividual(OT.OTClass.FeatureValue.getOntClass(jenaModel));
featureValue2.addProperty(OT.feature,feature2);
featureValue2.addLiteral(OT.value,jenaModel.createTypedLiteral(3.14, XSDDatatype.XSDdouble));
 
//and finally add values to the data entry
dataEntry.addProperty(OT.values,featureValue1);
dataEntry.addProperty(OT.values,featureValue2);

Write output

import org.restlet.data.MediaType;
    
public void write(OutputStream output) {
        if (mediaType.equals(MediaType.APPLICATION_RDF_XML))
            //jenaModel.write(output,"RDF/XML");  //this is faster
            jenaModel.write(output,"RDF/XML-ABBREV");   //this is more readable 
        else if (mediaType.equals(MediaType.APPLICATION_RDF_TURTLE))
            jenaModel.write(output,"TURTLE");
        else if (mediaType.equals(MediaType.TEXT_RDF_N3))
            jenaModel.write(output,"N3");
        else if (mediaType.equals(MediaType.TEXT_RDF_NTRIPLES))
            jenaModel.write(output,"N-TRIPLE");    
        else
            jenaModel.write(output,"RDF/XML-ABBREV");    
};

The result

RDF/XML-ABBREV

<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
    xmlns:ot="http://www.opentox.org/api/1.1#"
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    xmlns:owl="http://www.w3.org/2002/07/owl#"
    xmlns:dc="http://purl.org/dc/elements/1.1/">
  <owl:Class rdf:about="http://www.opentox.org/api/1.1#FeatureValue"/>
  <owl:Class rdf:about="http://www.opentox.org/api/1.1#Dataset"/>
  <owl:Class rdf:about="http://www.opentox.org/api/1.1#Compound"/>
  <owl:Class rdf:about="http://www.opentox.org/api/1.1#Feature"/>
  <owl:Class rdf:about="http://www.opentox.org/api/1.1#DataEntry"/>
  <rdf:Description rdf:about="Dataset URI">
    <ot:dataEntry>
      <ot:DataEntry>
        <ot:values>
          <ot:FeatureValue>
            <ot:value xml:lang="http://www.w3.org/2001/XMLSchema"
            >3.14</ot:value>
            <ot:feature>
              <ot:Feature rdf:about="featureURI2"/>
            </ot:feature>
          </ot:FeatureValue>
        </ot:values>
        <ot:values>
          <ot:FeatureValue>
            <ot:value xml:lang="http://www.w3.org/2001/XMLSchema"
            >formaldehyde</ot:value>
            <ot:feature>
              <ot:Feature rdf:about="featureURI1"/>
            </ot:feature>
          </ot:FeatureValue>
        </ot:values>
        <ot:compound>
          <ot:Compound rdf:about="compoundURI"/>
        </ot:compound>
      </ot:DataEntry>
    </ot:dataEntry>
  </rdf:Description>
</rdf:RDF>

 TURTLE

@prefix xsd:     <http://www.w3.org/2001/XMLSchema#> .
@prefix dc:      <http://purl.org/dc/elements/1.1/> .
@prefix ot:      <http://www.opentox.org/api/1.1#> .
@prefix rdfs:    <http://www.w3.org/2000/01/rdf-schema#> .
@prefix rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix owl:     <http://www.w3.org/2002/07/owl#> .

<http://localhost:8080/ambit2-www/feature_definition/1>
      a       ot:Feature .

ot:FeatureValue
      a       owl:Class .

ot:Dataset
      a       owl:Class .

<featureURI2>
      a       ot:Feature .

<Dataset URI>
      ot:dataEntry
              [ a       ot:DataEntry ;
                ot:compound <compoundURI> ;
                ot:values
                        [ a       ot:FeatureValue ;
                          ot:feature <featureURI2> ;
                          ot:value "3.14"^^xsd:float                      
                         ] ;
                ot:values
                        [ a       ot:FeatureValue ;
                          ot:feature <featureURI1> ;
                          ot:value "formaldehyde"^^xsd:string
                        ]
              ] .

ot:Compound
      a       owl:Class .

<compoundURI>
      a       ot:Compound .

ot:Feature
      a       owl:Class .

ot:DataEntry
      a       owl:Class .

More about Features

Create

An example how to create Feature with name, units and links to another ontology

		Individual feature = jenaModel.createIndividual("featureURI",
				OT.OTClass.Feature.getOntClass(jenaModel));
		feature.addProperty(DC.title, "featureName");
		feature.addProperty(DC.identifier,"featureURI");
		feature.addProperty(OT.units,"mmol");
		feature.addProperty(OWL.sameAs,"Reference to an individual from another ontology");
                feature.addProperty(OT.isA,"Reference to an individual from another ontology");
		feature.addProperty(OT.hasSource, "URI of dataste, algorithm or model");

Read

An example how to read Features from RDF input stream:

InputStream in;
...
OntModel jenaModel = OT.createModel();
jenaModel.read(in, null);

OntClass featureClass = OT.OTClass.Feature.getOntClass(jenaModel);
//get all instances of Feature class
ExtendedIterator<? extends OntResource> features = featureClass.listInstances();
while (features.hasNext()) {
  OntResource feature = features.next();
  System.out.println(feature);
  System.out.println(feature.getProperty(DC.title));
  System.out.println(feature.getProperty(DC.identifier));
  System.out.println(feature.getProperty(OT.units));
  System.out.println(feature.getProperty(OT.hasSource));
  System.out.println(feature.getProperty(OWL.sameAs));
}

Possible output:

http://localhost:8181/feature/1
[http://localhost:8181/feature/1, http://purl.org/dc/elements/1.1/title, "Property 1"]
[http://localhost:8181/feature/1, http://purl.org/dc/elements/1.1/identifier, "http://localhost:8181/feature/1"]
[http://localhost:8181/feature/1, http://www.opentox.org/api/1.1#units, ""]
[http://localhost:8181/feature/1, http://www.opentox.org/api/1.1#hasSource, "somereference"]
[http://localhost:8181/feature/1, http://www.w3.org/2002/07/owl#sameAs, "PropertyFromAnotherOntology"]

 

OpenTox Model

Create

An example how to create Model

Individual model = jenaModel.createIndividual("modelURI",OT.OTClass.Model.getOntClass(jenaModel));
model.addProperty(DC.title, "Model name");
model.addProperty(DC.identifier,"modelURI");
model.addProperty(DC.creator,"N/A");
model.addProperty(DC.date,"N/A");
model.addProperty(DC.format,"N/A");

//the algorithm
Individual algorithm = jenaModel.createIndividual("algorithm URI",OT.OTClass.Algorithm.getOntClass(jenaModel));
model.addProperty(OT.algorithm, algorithm);

//assign training dataset (same as above)
Individual dataset = jenaModel.createIndividual("dataset",OT.OTClass.Dataset.getOntClass(jenaModel));
model.addProperty(OT.trainingDataset,dataset);

//independent variables
Individual feature_independent1 = jenaModel.createIndividual("featureURI1",OT.OTClass.Feature.getOntClass(jenaModel));
model.addProperty(OT.independentVariables, feature_independent1);
Individual feature_independent2 = jenaModel.createIndividual("featureURI2",OT.OTClass.Feature.getOntClass(jenaModel));
model.addProperty(OT.independentVariables, feature_independent2);

//dependent variables
Individual feature_dependent1 = jenaModel.createIndividual("featureURI3",OT.OTClass.Feature.getOntClass(jenaModel));
model.addProperty(OT.dependentVariables, feature_dependent1);

//predicted (where the result will be written)
Individual feature_result = jenaModel.createIndividual("featureURI4",OT.OTClass.Feature.getOntClass(jenaModel));

Read

An example how to read a Model

InputStream in;
...
OntModel jenaModel = OT.createModel();
jenaModel.read(in, null);
 
OntClass modelClass = OT.OTClass.Model.getOntClass(jenaModel);
ExtendedIterator<? extends OntResource> models = modelClass.listInstances();
if (models!=null)
while (models.hasNext()) {
		OntResource model = models.next();
		System.out.println(model);
		System.out.println(model.getProperty(DC.title));
		System.out.println(model.getProperty(DC.identifier));
		System.out.println(model.getProperty(DC.creator));
		System.out.println(model.getProperty(DC.date));
		System.out.println(model.getProperty(OT.algorithm));
		System.out.println(model.getProperty(OT.independentVariables));
		System.out.println(model.getProperty(OT.dependentVariables));
		System.out.println(model.getProperty(OT.predictedVariables));
		System.out.println(model.getProperty(OT.trainingDataset));
}		

Possible output:

http://localhost:8181/model/1
[http://localhost:8181/model/1, http://purl.org/dc/elements/1.1/title, "Toxtree: Cramer rules"]
[http://localhost:8181/model/1, http://purl.org/dc/elements/1.1/identifier, "http://localhost:8181/model/1"]
[http://localhost:8181/model/1, http://purl.org/dc/elements/1.1/creator, "N/A"]
[http://localhost:8181/model/1, http://purl.org/dc/elements/1.1/date, "N/A"]
[http://localhost:8181/model/1, http://www.opentox.org/api/1.1#algorithm, http://localhost:8181/alg

OpenTox Algorithm

Create

An example how to create Algorithm

OntModel jenaModel = OT.createModel();

// defines Algorithm and Parameter classes 
OT.OTClass.Algorithm.createOntClass(jenaModel);
OT.OTClass.Parameter.createOntClass(jenaModel);

Individual algorithm = jenaModel.createIndividual("alg_uri",OT.OTClass.Algorithm.getOntClass(jenaModel));
algorithm.addLiteral(DC.title,jenaModel.createTypedLiteral("title",XSDDatatype.XSDstring));
algorithm.addLiteral(DC.identifier,jenaModel.createTypedLiteral("http://myservice/algorithm/1",XSDDatatype.XSDanyURI));
...
 
algorithm.addProperty(OT.isA, "http://www.opentox.org/algorithmTypes.owl#RegressionEagerSingleTarget");
		
algorithm.addLiteral(OT.statisticsSupported,jenaModel.createTypedLiteral("statistics-1",XSDDatatype.XSDstring));

Individual iparam = jenaModel.createIndividual(OT.OTClass.Parameter.getOntClass(jenaModel));
iparam.addLiteral(OT.paramValue,jenaModel.createTypedLiteral(10,XSDDatatype.XSDinteger));
iparam.addLiteral(OT.paramScope,jenaModel.createTypedLiteral("mandatory",XSDDatatype.XSDstring));	
algorithm.addProperty(OT.parameters, iparam);


Individual iparam1 = jenaModel.createIndividual(OT.OTClass.Parameter.getOntClass(jenaModel));
iparam1.addLiteral(OT.paramValue,jenaModel.createTypedLiteral("newparam",XSDDatatype.XSDString));
iparam1.addLiteral(OT.paramScope,jenaModel.createTypedLiteral("optional",XSDDatatype.XSDstring));	
algorithm.addProperty(OT.parameters, iparam1);

Read

An example how to read an Algorithm

InputStream in;
...
OntModel jenaModel = createModel();
jenaModel.read(in, null);
 
OntClass algClass = OT.OTClass.Algorithm.getOntClass(jenaModel);
ExtendedIterator<? extends OntResource> algorithms = algClass.listInstances();
if (algorithms!=null)
while (algorithms.hasNext()) {
		OntResource algorithm= algorithms.next();
		System.out.println(algorithm);
		System.out.println(algorithm.getProperty(DC.title));
		System.out.println(algorithm.getProperty(DC.identifier));
		System.out.println(algorithm.getProperty(OT.parameters));
		System.out.println(algorithm.getProperty(OT.statisticsSupported));
		System.out.println(algorithm.getProperty(OT.isA));
...
}		

 

OpenTox Dataset

Retrieve all datasets:

		OntClass aClass = OT.OTClass.Dataset.getOntClass(jenaModel);
		if (aClass != null) {
			ExtendedIterator<? extends OntResource>  a = aClass.listInstances();	
			if (a!=null)
				while (a.hasNext()) {
					parseDataset(jenaModel, out,a.next());
				}
			
		}

 

Parse RDF representation of a Dataset:

	protected void parseDataset(OntModel jenaModel, OutputStreamWriter out, OntResource dataset) throws IOException {
		out.write(String.format("<h3>%s&nbsp;%s</h3>","Dataset", dataset==null?"":dataset));
		StmtIterator iter =  jenaModel.listStatements(new SimpleSelector(dataset,OT.dataEntry,(RDFNode)null));
		while (iter.hasNext()) {
			Statement st = iter.next();
			if (!st.getObject().isResource()) continue;
			Resource dataEntry = (Resource) st.getObject();
			out.write(String.format("<h4>DataEntry&nbsp;%s</h4>",dataEntry));

			parseDataEntry(jenaModel, out, dataEntry);
		}		
	}

Parse RDF representation of a DataEntry

	protected void parseDataEntry(OntModel jenaModel, OutputStreamWriter out, Resource dataEntry) throws IOException {
		//get the compound
		StmtIterator compound =  jenaModel.listStatements(new SimpleSelector(dataEntry,OT.compound,(RDFNode)null));
		while (compound.hasNext()) {
			Statement st = compound.next();
			out.write(String.format("<h5>%s&nbsp;%s</h5>","Compound", st.getObject()));
		}	
		//get feature values
		parseFeatureValues(jenaModel, out, dataEntry);
	}

Parse RDF representation of FeatureValues

	protected void parseFeatureValues(OntModel jenaModel, OutputStreamWriter out, Resource dataEntry) throws IOException {
		StmtIterator values =  jenaModel.listStatements(new SimpleSelector(dataEntry,OT.values,(RDFNode)null));
		out.write(String.format("<h5>%s</h5>","Values"));
		while (values.hasNext()) {
			Statement st = values.next();
			if (st.getObject().isResource()) {
				Resource fv = (Resource)st.getObject();
				RDFNode value = fv.getProperty(OT.value).getObject();
				out.write(String.format("%s&nbsp;=&nbsp;%s<br>",
						//Feature
						fv.getProperty(OT.feature).getObject().toString(),
						//Value
						value
						));
			}
		}
	}

 

Possible output:

-555a6061:12575437b71:-7ffa

Compound http://ambit.uni-plovdiv.bg:8080/ambit2/compound/1

http://ambit.uni-plovdiv.bg:8080/ambit2/feature/2 = formaldehyde
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/11 = C=O
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/13 = InChI=1/CH2O/c1-2/h1H2
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/7 = formaldehyde
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/8 = 30.026
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/9 = formaldehyde
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/3 = VeryHigh
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/5 = 200-001-8
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/4 = CH2O
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/1 = CH2O
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/10 = DSL,TSCA
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/6 = 50-00-0
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/12 = 1.0

-555a6061:12575437b71:-7ffb

Compound http://ambit.uni-plovdiv.bg:8080/ambit2/compound/2

http://ambit.uni-plovdiv.bg:8080/ambit2/feature/6 = 50-01-1
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/5 = 200-002-3
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/3 = Low
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/13 = InChI=1/CH5N3.ClH/c2-1(3)4;/h(H5,2,3,4);1H
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/7 = guanidinium chloride
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/11 = [Cl-].NC(=N)[NH3+]
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/2 = guanidinium chloride
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/9 = amino(imino)methanaminium chloride
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/10 = DSL,TSCA
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/12 = 2.0
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/1 = CH5N3.ClH
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/8 = 95.5314 (35.4535+60.0779)
http://ambit.uni-plovdiv.bg:8080/ambit2/feature/4 = CH6ClN3


      
Document Actions