Jena Programming

Preview:

DESCRIPTION

This slide describes how to make Semantic Web applications using Jena framework.

Citation preview

Jena Programming

Dr. Myungjin Lee

Apache JenaWhat is the Jena?

a Java framework for building Semantic Web applica-tions

A Java API for RDF

Developed by Brian McBride of HP

Derived from SiRPAC API

Can parse, create, and search RDF models

Easy to use

Apache Jenathe Jena Framework includes:

an API for reading, processing and writing RDF data in XML, N-triples and Turtle formats;

an ontology API for handling OWL and RDFS ontologies;

a rule-based inference engine for reasoning with RDF and OWL data sources;

stores to allow large numbers of RDF triples to be efficiently stored on disk;

a query engine compliant with the latest SPARQL specification

servers to allow RDF data to be published to other applications using a variety of protocols, including SPARQL

Apache JenaWhat can we do?

Identifiers: URICharacter set: UNICODE

Syntax: XML

Data interchange: RDF

Querying: SPARQL

Ontologies:OWL

Rules:RIF/SWRL

Taxonomies: RDFS

Unifying logic

Cryptography

User interface and applications

Trust

Proof

Jena(ARP)SDB + TDB

ARQ

Apache JenaInstall and Run Jena

Get package from

http://www.apache.org/dist/jena/

Unzip it

Setup environments (CLASSPATH)

Online documentation

Tutorial

http://jena.apache.org/documentation/index.html

API Doc

http://jena.apache.org/documentation/javadoc/

RDFResource Description Framework

a general method for conceptual description or modeling of information, especially web resources

Core ConceptsGraph and Model

Grapha simpler Java API intended for extending Jena's functionality

Modela rich Java API with many convenience methods for Java ap-plication developers

Core ConceptsNodes and Triples

Resource Property

ResourceStatement

Literal

Model

Core ConceptsInterface Hierarchy

Reading RDFCore Classes

What is a Model?one RDF graph which is represented by the Model interface

Model

Jena ProgrammingInterface

Ontology(RDF Graph)

Reading RDFCore Classes

ModelFactory Classmethods for creating standard kinds of Model

Model Interfacecreating resources, properties and literals and the Statements

adding statements

removing statements from a model

querying a model and set operations for combining models.

Reading RDFHow to make Model

read MethodsModel read(String url, String base, String lang)

Model read(InputStream in, String base, String lang)

Model read(Reader reader, String base, String lang)

Parametersbase - the base uri to be used when converting relative URI's to absolute URI's

lang - "RDF/XML", "N-TRIPLE", "TURTLE" (or "TTL") and "N3"

Reading RDFHow to make Model

Model model = ModelFactory.createDefaultModel();

InputStream in = FileManager.get().open(“BadBoy.owl");

model.read(in, null, “RDF/XML”);

Writing RDFHow to write Model

write MethodsModel write(OutputStream out, String lang, String base)

Model write(Writer writer, String lang, String base)

model.write(System.out);

model.write(System.out, "N-TRIPLE");

String fn = “temp/test.xml”;

model.write(new PrintWriter(new FileOutputStream(fn)));

Creating NodesInterfaces related to nodes

Resource InterfaceAn RDF Resource

Property InterfaceAn RDF Property

RDFNode InterfaceInterface covering RDF resources and literals

Creating NodesHow to create nodes

from Model Interfaceto create new nodes whose model is this model

from ResourceFactory Classto create resources and properties are not associ-ated with a user-modifiable model

Creating NodesResource and Property

MethodsResource createResource(String uri)

Property createProperty(String uriref)

Resource s = model.createResource(“…”);

Property p = ResourceFactory.createProperty(“…”);

Creating NodesLiteral

Un-typed LiteralLiteral createLiteral(String v, String language)

Literal createLiteral(String v, boolean wellFormed)

Literal l1 = model.createLiteral("chat", "en")

Literal l2 = model.createLiteral("<em>chat</em>", true);

Creating NodesLiteral

Typed LiteralLiteral createTypedLiteral(Object value)

Literal l = model.createTypedLiteral(new Integer(25));

Java class xsd typeFloat float

Double doubleInteger int

Long longShort short

Java class xsd typeByte byte

BigInteger integerBigDecimal decimal

Boolean BooleanString string

TriplesRDF Triple and Statement Interface

RDF Triple (Statement)arc in an RDF Modelasserts a fact about a resourceconsists of subject, predicate, and object

Triple

Subject Predicate Object

Jena ProgrammingInterface

Statement

Resource Property RDFNode

TriplesInterfaces related to triples

Statement Interfacerepresents a tripleconsists of Resource, Property, and RDFNode

StmtIterator Interfacea set of statements (triples)

TriplesGetting TriplesStmtIterator iter = model.listStatements();while (iter.hasNext()) { Statement stmt = iter.nextStatement(); Resource subject = stmt.getSubject(); Property predicate = stmt.getPredicate(); RDFNode object = stmt.getObject();}

Querying a Model

To list the ‘selected’ statements in the Model// making nodes for query

Resource husband =

model.createResource("http://iwec.yonsei.ac.kr/family#MyungjinLee");

Property type =

model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-

ns#type");

// querying a model

StmtIterator iter = model.listStatements(husband, type, (RDFNode)

null);

while (iter.hasNext()) {

Statement stmt = iter.nextStatement();

Resource subject = stmt.getSubject();

Property predicate = stmt.getPredicate();

RDFNode object = stmt.getObject();

System.out.println(subject + " " + predicate + " " + object);

}

Adding a triple

Add a relation of resourceResource husband = model.createResource("http://iwec.yon-sei.ac.kr/family#MyungjinLee");Property marry = model.createProperty("http://iwec.yonsei.ac.kr/family#hasWife");Resource wife = model.createResource("http://iwec.yonsei.ac.kr/family#YejinSon");husband.addProperty(marry, wife);

Ontology Reasoning

Ontologies and reasoningto derive additional truths about the concepts

Jena2 inference subsystemto allow a range of inference engines or reasoners to be plugged into Jenahttp://jena.sourceforge.net/inference/index.html

Available Reasoners on Jena

Transitive reasoner Provides support for storing and traversing class and property lattices. This imple-ments just the transitive and reflexive properties of rdfs:subPropertyOf and rdfs:subClassOf.

RDFS rule reasoner Implements a configurable subset of the RDFS entailments.

OWL, OWL Mini, OWL Micro Reasoners A set of useful but incomplete implementation of the OWL/Lite subset of the OWL/Full language.

DAML micro reasoner Used internally to enable the legacy DAML API to provide minimal (RDFS scale) infer-encing.

Generic rule reasoner A rule based reasoner that supports user defined rules. Forward chaining, tabled backward chaining and hybrid execution strategies are supported.

Reasoning of Sample Ontology

Person

FemaleMale

subClassOfsubClassOf

Myungjin Lee

Yejin Son

typetype

hasWife

hasWife

hasHusband

inverseOf

hasHusband

typetype

The OWL reasonerJena OWL reasonersReasoner reasoner = ReasonerRegistry.getOWLReasoner();

InfModel infmodel = ModelFactory.createInfModel(reasoner,

model);

Property husband = model.createProperty("http://www.semantic-

s.kr/family#hasHusband");

StmtIterator iterHusband = infmodel.listStatements(null, hus-

band, myungjin);

while (iterHusband.hasNext()) {

Statement stmt = iterHusband.nextStatement();

Resource subject = stmt.getSubject();

Property predicate = stmt.getPredicate();

RDFNode object = stmt.getObject();

System.out.println(subject + " " + predicate + " " + ob-

ject);

}

Making Domain Rules

Person

FemaleMale

subClassOfsubClassOf

Myungjin Lee

Yejin Son

typetype

hasWife

HappyWoman

subClassOf

type

If someone's husband is Myungjin Lee, she is a happy woman.

Making Domain Rules

family.rules

1. @prefix base: <http://www.semantics.kr/family#>.

2. [HappyWoman:(?x rdf:type base:Female),(base:MyungjinLee base:hasWife ?x)

-> (?x rdf:type base:HappyWoman)]

The Generic Rule ReasonerResource configuration = model.createResource();configuration.addProperty

(ReasonerVocabulary.PROPruleMode, "forward");configuration.addProperty

(ReasonerVocabulary.PROPruleSet, "family.rules");Reasoner domainReasoner = GenericRuleReasonerFactory.theInstance().create(configuration);InfModel domaininfmodel = ModelFactory.createInfModel(domainReasoner, infmodel);StmtIterator happyIter =domaininfmodel.listStatements(wife, type, (RDFNode) null);

SPARQL

SPARQL(SPARQL Protocol and RDF Query Language)an RDF query language, that is, a query language for databasesto retrieve and manipulate data stored in Resource Description Framework format

Simple ExamplePREFIX foaf: <http://xmlns.com/foaf/0.1/>SELECT ?name ?emailWHERE {

?person rdf:type foaf:Person.?person foaf:name ?name.?person foaf:mbox ?email.

}

SPARQL Example of Family Ontologyfamily.sparql

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .PREFIX base: <http://www.semantics.kr/family#>

SELECT ?xWHERE {

?x rdf:type base:Female.base:MyungjinLee base:hasWife ?x.

}

How to get the results from SPARQLtry { // make a query string from SPARQL file FileReader fr = new FileReader("family.sparql"); BufferedReader br = new BufferedReader(fr); StringBuffer queryString = new StringBuffer(); String temp; while ((temp = br.readLine()) != null) { queryString.append(temp); } Query query = QueryFactory.create(queryString.toString()); // create a object for query QueryExecution qexec = QueryExecutionFactory.create(query, domain-infmodel); ResultSet results = qexec.execSelect(); // execute SPARQL query while(results.hasNext()) { QuerySolution soln = results.nextSolution(); RDFNode r = soln.get("x"); // get a result System.out.println(r.toString()); }} catch (Exception e) { e.printStackTrace();}