34
Jena Programming Dr. Myungjin Lee

Jena Programming

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: Jena Programming

Jena Programming

Dr. Myungjin Lee

Page 2: Jena Programming

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

Page 3: Jena Programming

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

Page 4: Jena Programming

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

Page 5: Jena Programming

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/

Page 6: Jena Programming

RDFResource Description Framework

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

Page 7: Jena Programming

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

Page 8: Jena Programming

Core ConceptsNodes and Triples

Resource Property

ResourceStatement

Literal

Model

Page 9: Jena Programming

Core ConceptsInterface Hierarchy

Page 10: Jena Programming

Reading RDFCore Classes

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

Model

Jena ProgrammingInterface

Ontology(RDF Graph)

Page 11: Jena Programming

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.

Page 12: Jena Programming

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"

Page 13: Jena Programming

Reading RDFHow to make Model

Model model = ModelFactory.createDefaultModel();

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

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

Page 14: Jena Programming

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)));

Page 15: Jena Programming

Creating NodesInterfaces related to nodes

Resource InterfaceAn RDF Resource

Property InterfaceAn RDF Property

RDFNode InterfaceInterface covering RDF resources and literals

Page 16: Jena Programming

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

Page 17: Jena Programming

Creating NodesResource and Property

MethodsResource createResource(String uri)

Property createProperty(String uriref)

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

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

Page 18: Jena Programming

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);

Page 19: Jena Programming

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

Page 20: Jena Programming

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

Page 21: Jena Programming

TriplesInterfaces related to triples

Statement Interfacerepresents a tripleconsists of Resource, Property, and RDFNode

StmtIterator Interfacea set of statements (triples)

Page 22: Jena Programming

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

Page 23: Jena Programming

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);

}

Page 24: Jena Programming

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);

Page 25: Jena Programming

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

Page 26: Jena Programming

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.

Page 27: Jena Programming

Reasoning of Sample Ontology

Person

FemaleMale

subClassOfsubClassOf

Myungjin Lee

Yejin Son

typetype

hasWife

hasWife

hasHusband

inverseOf

hasHusband

typetype

Page 28: Jena Programming

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);

}

Page 29: Jena Programming

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.

Page 30: Jena Programming

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)]

Page 31: Jena Programming

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);

Page 32: Jena Programming

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.

}

Page 33: Jena Programming

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.

}

Page 34: Jena Programming

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();}