Sei sulla pagina 1di 49

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


main package.

Only applications wishing to
programmatically build queries or modify
9
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
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.
10
 ResultSetFormatter - turn a ResultSet into various forms; into text,
Creating Queries

11
SELECT queries
The basic steps in making a SELECT
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
12
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
execution
import can
com.hp.hpl .jenabe reduced
.query .* ; to one step in some
common cases:
Model model = ... ;
 String queryString = " .... " ;
QueryExecution qexec = QueryExecutionFactory.create(queryString, model) ;
 try {
ResultSet results = qexec.execSelect() ;
. . .
} finally { qexec.close() ; }

14
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:
ResultSetFormatter fmt = new ResultSetFormatter(results, query) ;
 fmt.printAll(System.out) ;
OR
ResultSetFormatter.out(System.out, results, query) ;

15
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
query results processing: 
for ( ; results.hasNext() ; )
{
// 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.
Datasets can
String dftGraphURI be constructed
= "file :default-graph.ttlusing
" ;
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 - the book
SPARQL

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
 <rdf:RDF
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-
ns#"
 xmlns:dc="http://purl.org/dc/elements/1.1/">
 <rdf:Description
rdf:about="http://example.org/book#1">
 <dc:description>Advanced techniques for
SPARQL</ dc:description>
 <dc:description>A book about
SPARQL</dc:description>
 <dc:title>SPARQL - the book</dc:title>
 </rdf:Description>
</rdf:RDF>
Example 2

http://example.org/book#
1
DC.title DC.description

DC.description
SPARQL - the book http://example.org/book#
2
A book about DC.description
DC.title
SPARQL

Advanced techniques for


http://example.org/book# SPARQL
3

DC.title DC.description

Jena - an RDF framework for


A book about Jena
Java
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" ) ;

 r1.addProperty(DC.title, "SPARQL - the book" )


 .addProperty(DC.description, "A book about
SPARQL" )
 .addProperty(DC.description, r2) ;

 r2.addProperty(DC.title, "Advanced techniques for


SPARQL" )
 .addProperty(DC.description, r3) ;

 r3.addProperty(DC.title, "Jena - an RDF framework


for Java" )
 .addProperty(DC.description, "A book about
Jena") ;

 m.write( System.out, "RDF/XML-ABBREV" );


 <rdf:RDF
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-
syntax-ns#"
 xmlns:dc="http://purl.org/dc/elements/1.1/">
 <rdf:Description
rdf:about="http://example.org/book#2">
 <dc:description>
 <rdf:Description
rdf:about="http://example.org/book#3">
 <dc:description>A book about
Jena</dc:description>
 <dc:title>Jena - an RDF framework for
Java</dc:title>
 </rdf:Description>
 </dc:description>
 <dc:title>Advanced techniques for
SPARQL</dc:title>
 </rdf:Description>
 <rdf:Description
rdf:about="http://example.org/book#1">
 <dc:description
rdf:resource="http://example.org/book#2"/>
 <dc:description>A book about
SPARQL</dc:description>
 <dc:title>SPARQL - the book</dc:title>
SPARQL
An RDF query language
allows for a query to consist of
triple patterns, conjunctions,
disjunctions, and optional
patterns
queries across diverse data ?x

sources dc:description
?y

 PREFIX dc: <http://purl.org/dc/elements/1.1/>


dc:description
 SELECT ?title ?z
 WHERE { ?x dc:description ?y .
dc:title
 ?y dc:description ?z .
?title
 ?z dc:title ?title . }
SPARQL in Example 2

http://example.org/book#
1
DC.title DC.description

DC.description
SPARQL - the book http://example.org/book#
2
A book about DC.description
DC.title
SPARQL

Advanced techniques for


http://example.org/book# SPARQL
3

DC.title DC.description

Jena - an RDF framework for


A book about Jena
Java
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 Titles:
 qexec.close() ; 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=YourSocksServer-
DsocksProxyHost=YourSocksServer
-DsocksProxyPort=port-
Dhttp.proxyHost=WebProxy
-Dhttp.proxyPort=Port
This can be done in the application if it is done
before any network connection are made:
System.setProperty("socksProxyHost",
35

"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 Tested Version License Problems / Issues / Remarks
Java
Classes
Jastor Type 2 Yes Tried CPL Unable to run with Jena 2.4 or Jena
2.5

Sommer Type 2 ? Not Yet BSD


Protege OWL-API 1 & 2 Yes Yes 3.4 beta MPL none
RDFReactor Type 2 Yes Yes 4.5.2 BSD / LGPL ? More research needed to correct
OWL output

Kazuki ? ? Not Yet


Sesame and Elmo ? ? Not Yet BSD
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 Type 2 ? No Apache 2.0


JAOB Type 2 Yes Yes 0.1 LGPL My own implementation

39
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

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 
41
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

Potrebbero piacerti anche