Jena
A Semantic Web Framework for Java Amna Basharat Spring 2009
Outline What is Jena Packages Jena Example SPARQL SPARQL Example My project DEMO
What is Jena Jena is a Java framework for building Semantic Web
applications includes
a RDF API reading and writing RDF in
RDF/XML, N3 and N-Triples an OWL API in-memory and persistent storage SPARQL query engine http://jena.sourceforge.net/
Packages Jena includes Jena and ARQ a package providing API about RDF and SPARQL Jena CVS a tool used to manage changes within source code Joseki a RDF publishing server Eyeball an "RDF lint" for checking RDF/OWL models
ARQ - Application API
8
Introduction – ARQ Application API The application API is in the
package com.hp.hpl.jena.query.
Other packages contain various parts of the
system (execution engine, parsers, testing etc).
Most applications will only need to use the
9
main package. Only applications wishing to programmatically build queries or modify the behaviour of the query engine need to use the others packages directly.
Key Classes of ARQ Application API The package com.hp.hpl.jena.query is the main application package. Query a class that represents the application query. It is a container for all the details of the query. Objects of class Query are normally created by calling one of the
10
methods of QueryFactory methods which provide access to the various parsers. QueryExecution represents one execution of a query. QueryExecutionFactory a place to get QueryExecution instances DatasetFactory a place to make datasets, including making a DataSource (an updatable Dataset) For SELECT queries: QuerySolution - A single solution to the query ResultSet - All the QuerySolutions. An iterator. ResultSetFormatter - turn a ResultSet into various forms; into text,
Creating Queries
11
SELECT queries The basic steps in making a SELECT
12
query are outlined in the example below. A query is created from a string using the QueryFactory. The query and model or RDF dataset to be queried are then passed to QueryExecutionFactory to produce an instance of a query execution. Result are handled in a loop and finally the query execution is closed.
Example Code Structure
t com.hp.hpl.jena.query.* ;
model = ... ; g queryString = " .... " ; query = QueryFactory.create(queryString) ; Execution qexec = QueryExecutionFactory.create(query, model) ;
tSet results = qexec.execSelect() ; ; results.hasNext() ; )
Solution soln = results.nextSolution() ; de x = soln.get("varName") ; // Get a result variable by name. rce r = soln.getResource("VarR") ; // Get a result variable - must be a res al l = soln.getLiteral("VarL") ; // Get a result variable - must be a liter
ally { qexec.close() ; }
13
Simplifying the Query Formulation and Execution It is important to cleanly close the query execution
when finished.
System resources connected to persistent storage
may need to be released.
The step of creating a query and then a query import com.hp.hpl .jenabe .query .* ; execution can reduced to one step in some
common cases:
14
Model model = ... ; String queryString = " .... " ; QueryExecution qexec = QueryExecutionFactory.create(queryString, model) ; try { ResultSet results = qexec.execSelect() ; . . . } finally { qexec.close() ; }
Example: Formatting a ResultSet Instead of a loop to deal with each row in
the result set, the application can call an operation of the ResultSetFormatter. This is what the command line applications do. Example: processing results to produce a simple text presentation:
15
ResultSetFormatter fmt = new ResultSetFormatter(results, query) ; fmt.printAll(System.out) ; OR ResultSetFormatter.out(System.out, results, query) ;
Example: Processing results The results are objects from the Jena
RDF API and API calls, which do not modify the model, can be mixed with for ( ; results.hasNext() ; ) query results processing: { // Access variables: soln.get("x") ; RDFNode n = soln.get("x") ; // "x" is a variable in the query // If you need to test the thing returned if ( n.isLiteral() ) ((Literal)n).getLexicalForm() ; if ( n.isResource() ) { Resource r = (Resource)n ; if ( ! r.isAnon() ) { ... r.getURI() ... }}}
16
CONSTRUCT Queries CONSTRUCT queries return a single
RDF graph. As usual, the query execution should be closed after use. Query query = QueryFactory.create(queryString) ; QueryExecution qexec = QueryExecutionFactory.create(query, model) ; Model resultModel = qexec.execConstruct() ; qexec.close() ;
17
DESCRIBE Queries DESCRIBE queries return a single RDF
graph. Different handlers for the DESCRIBE operation can be loaded by added by the application. Query query = QueryFactory.create(queryString) ; QueryExecution qexec = QueryExecutionFactory.create(query, model) ; Model resultModel = qexec.execDescribe() ; qexec.close() ;
18
ASK Queries The operation Query.execAsk() returns
a boolean value indicating whether the query pattern matched the graph or dataset or not. Query query = QueryFactory.create(queryString) ; QueryExecution qexec = QueryExecutionFactory.create(query, model) ; boolean result = qexec.execAsk() ; qexec.close()
19
Formatting XML results The ResultSetFormatter class has
methods to write out the SPARQL Query Results XML Format. See ResultSetFormatter.outputAsXML method.
20
Datasets The examples above are all queries on a single
model. A SPARQL query is made on a dataset, which is a default graph and zero or more named graphs. String dftGraphURI = "file :default-graph.ttlusing " ; Datasets can be constructed List namedGraphURIs = new ArrayList() ; the DatasetFactory: namedGraphURIs .add("file:named-1.ttl") ; namedGraphURIs.add("file:named-2.ttl") ;
Query query = QueryFactory.create(queryString) ; Dataset dataset = DatsetFactory.create(dftGraphURI, namedGraphURIs) ; QueryExecution qExec = QueryExecutionFactory.create(query, dataset) ; try { ... } finally { qExec.close() ; }
21
Using Existing Models Already existing models can also be
used: A DataSource is an updatable dataset: DataSource dataSource = DatsetFactory.create() ; dataSource.setDefaultModel(model) ; dataSource.addNamedModel("http://example/named-1", modelX) ; dataSource.addNamedModel("http://example/named-2", modelY) ; QueryExecution qExec = QueryExecutionFactory.create(query, dataSource) ;
22
Examples
23
Example 1
http://example.org/book# 1 DC.title
DC.description DC.description Advanced techniques for SPARQL
SPARQL - the book
A book about SPARQL
Example 1 public class Ex1 { public static void main( String[] args ) { Model m = ModelFactory.createDefaultModel() ;
Resource r1 = m.createResource( "http://example.org/book#1" ) ;
r1.addProperty(DC.title, "SPARQL - the book" ) .addProperty(DC.description, "A book about SPARQL" ) .addProperty(DC.description, "Advanced techniques for SPARQL" );
m.write( System.out, "RDF/XML-ABBREV" );
}
}
Example 1 Advanced techniques for SPARQL dc:description> A book about SPARQL SPARQL - the book
Example 2 http://example.org/book# 1 DC.title
DC.description DC.description http://example.org/book# 2
SPARQL - the book A book about SPARQL
DC.description
http://example.org/book# 3 DC.title
Jena - an RDF framework for Java
DC.description
A book about Jena
DC.title Advanced techniques for SPARQL
public class Ex2 { public static void main( String[] args ) { Model m = ModelFactory.createDefaultModel() ;
Resource r1 = m.createResource( "http://example.org/book#1" ) ; Resource r2 = m.createResource( "http://example.org/book#2" ) ; Resource r3 = m.createResource( "http://example.org/book#3" ) ;
SPARQL" )
r1.addProperty(DC.title, "SPARQL - the book" ) .addProperty(DC.description, "A book about .addProperty(DC.description, r2) ;
SPARQL" )
r2.addProperty(DC.title, "Advanced techniques for .addProperty(DC.description, r3) ;
for Java" )
Jena") ;
r3.addProperty(DC.title, "Jena - an RDF framework .addProperty(DC.description, "A book about
m.write( System.out, "RDF/XML-ABBREV" );
A book about Jena Jena - an RDF framework for Java Advanced techniques for SPARQL A book about SPARQL SPARQL - the book
SPARQL An RDF query language allows for a query to consist of
triple patterns, conjunctions, disjunctions, and optional patterns ?x queries across diverse data dc:description sources
?y
PREFIX dc: dc:description SELECT ?title WHERE { ?x dc:description ?y . dc:title ?y dc:description ?z . ?title ?z dc:title ?title . }
?z
SPARQL in Example 2 http://example.org/book# 1 DC.title
DC.description DC.description http://example.org/book# 2
SPARQL - the book A book about SPARQL
DC.description
http://example.org/book# 3 DC.title
Jena - an RDF framework for Java
DC.description
A book about Jena
DC.title Advanced techniques for SPARQL
public class Ex3 { public static void main( String[] args) { Model model = createModel() ;
String prolog = "PREFIX dc:< " + DC.getURI() + ">"; String queryString = prolog + "\n" + "SELECT ?title WHERE { ?x dc:description ?y . ?y dc:description ?z . ?z dc:title ?title }";
Query query = QueryFactory.create( queryString ); QueryExecution qexec = QueryExecutionFactory.create( query, model );
System.out.println( "Titles: " ) ; try { ResultSet rs = qexec.execSelect();
for ( ; rs.hasNext() ; ) { QuerySolution rb = rs.nextSolution() ; RDFNode x = rb.get( "title" ) ;
if ( x.isLiteral() ) { Literal titleStr= ( Literal )x ; System.out.println( "
}
}
}
“ + titleStr ) ;
}
} finally qexec.close() ;
Titles: Jena - an RDF framework for Java
Q u e ry in g R e m o te S P A R Q L S e rv ice s
33
ARQ - Querying Remote SPARQL Services SPARQL is a query language and a
remote access protocol. The remote access protocol can be used with plain HTTP or over SOAP. See Joseki for an implementation of an RDF publishing server, using the SPARQL protocol (HTTP and SOAP). Joseki uses ARQ to provide SPARQL query access to Jena models, including Jena persistent models. ARQ includes a query engine capable of using the HTTP version. A version using SOAP is include in Joseki. 34
Firewalls and Proxies Don't forget to set the proxy for Java if you are
accessing a public server from behind a blocking firewall. Most home firewalls do not block outgoing requests; many corporate firewalls do block outgoing requests. If, to use your web browser, you need to set a proxy, you need to do so for a Java program. Simple examples include: -DsocksProxyHost=YourSocksServerDsocksProxyHost=YourSocksServer -DsocksProxyPort=portDhttp.proxyHost=WebProxy -Dhttp.proxyPort=Port This can be done in the application if it is done before any network connection are made: 35 System.setProperty("socksProxyHost", "socks.corp.com"); Consult the Java
From your application The QueryExecutionFactory has methods for
creating a QueryExecution object for remote use. QueryExecutionFactory.sparqlService
These methods build a query execution object that
uses the query engine in com.hp.hpl.jena.sparql.engine.http.
The remote request is made when
the execSelect, execConstruct, execDescribe or e xecAsk method is called.
The results are held locally after remote execution
and can be processed as usual.
36
Protégé OWL API
37
OWL API Comparisons http://wiki.yoshtec.com/java-owl-api
38
A Comparison API-Name
Type
Generates Java Classes Yes
Tested
Jastor
Type 2
Sommer Type 2 Protege OWL-API 1 & 2
? Yes
Not Yet Yes
3.4 beta
BSD MPL
RDFReactor
Yes
Yes
4.5.2
BSD / LGPL ?
Kazuki ? Sesame and Elmo ?
? ?
Not Yet Not Yet
OWL API
Type 1
No
Yes
2.1.1
LGPL
Since it is a plain low level OWL API code looks horrible for this purpose
Jena
Type 1
No
Indirect
2.4
BSD-Style
Is used in a lot of different higher level APIs
Topaz JAOB
Type 2 Type 2
? Yes
No Yes
0.1
Apache 2.0 LGPL
39
Type 2
Version
Tried
License
Problems / Issues / Remarks
CPL
Unable to run with Jena 2.4 or Jena 2.5
none More research needed to correct OWL output
BSD
My own implementation
From the above Comparison,
ProtegeOWL API seems to be an OK Choice.
40
How to use protege OWL API in Eclipse 1-Create Java Project
2-Goto Project->Properties-> Java Build Paths
41
Libraries tab, click add external JARS and go inside Protege directory ->select all jar files. inside Protege directory ->Plugins inside (edu.stanford.smi.protegex.owl) select all jar files. Also Select protege.api from /protege/
ProtegeOWL API Tutorial By Amna Basharat Haider Fast - NU , Fall 2008
42
Tasks Creating Ontology Factory Publishing: Publishing new
Knowledge into Your OWL Ontology using Ontology Factory Querying/Knowledge Retrieval: Reasoning: Invoking a Reasoner throught the Code 43
Creating Ontology Factory
44
Publishing : Publishing new Knowledge into Your OWL Ontology using Ontology Factory
45
Querying / Knowledge Retrieval
JENA – ARQ Tutorial http :// jena . sourceforge . net / ARQ / documenta
46
An Introduction to RDF and the
Jena RDF API
http://jena.sourceforge.net/tutorial/R
47
Jena Tutorial
http://jena.hpl.hp.com/juc2006/proce
48
R e a so n in g : In v o k in g a R e a so n e r th ro u g h t th e Code
49