Click here to load reader

JENA-ARQ Tutorial

Embed Size (px)

Citation preview

A Semantic Web Framework for JavaAmna Basharat Spring 2009

Jena

OutlineWhat is Jena Packages Jena Example SPARQL SPARQL Example My project DEMO

What is JenaJena 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 enginehttp://jena.sourceforge.net/

PackagesJena 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 APIThe application API is in the

packagecom.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 packagecom.hp.hpl.jena.queryis the main application package. Query a class that represents the application query. It is a container for all the details of the query.

10

methods ofQueryFactorymethods which provide access to the various parsers. QueryExecution represents one execution of a query. QueryExecutionFactory a place to getQueryExecutioninstances DatasetFactory a place to make datasets, including making aDataSource(an updatableDataset) 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,

Objects of class Query are normally created by calling one of the

Creating Queries

11

SELECT queriesThe basic steps in making a SELECT

12

query are outlined in the example below. A query is created from a string using theQueryFactory. The query and model or RDF dataset to be queried are then passed toQueryExecutionFactoryto 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 reduced to one step in some execution can .query.* ;Model model = ... ; String queryString = " .... " ; QueryExecution qexec = QueryExecutionFactory.create(queryString, model) ; try { ResultSet results = qexec.execSelect() ; . . . } finally { qexec.close() ; }

common cases:

14

Example: Formatting a ResultSetInstead 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 resultsThe 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 QueriesCONSTRUCTqueries 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 QueriesDESCRIBEqueries return a single RDF

graph.Different handlersfor theDESCRIBEoperation 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 QueriesThe 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 resultsTheResultSetFormatterclass has

methods to write out the SPARQL Query Results XML Format. See ResultSetFormatter.outputAsXML method.

20

DatasetsThe 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 = " constructed using Datasets can befile:default-graph.ttl" ; List namedGraphURIs = new ArrayList() ; theDatasetFactory: 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 ModelsAlready existing models can also be

used: ADataSourceis 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 SPARQL - the book Advanced techniques for SPARQL A book about SPARQL DC.description

Example 1public 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 A book about SPARQL SPARQL - the book

Example 2http://example.org/book# 1 DC.title DC.description SPARQL - the book A book about SPARQL DC.description http://example.org/book# 2 DC.title Advanced techniques for SPARQL DC.description

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

Jena - an RDF framework for Java

A book about Jena

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 .addProperty(DC.description, r2) ; r2.addProperty(DC.title, "Advanced techniques for .addProperty(DC.description, r3) ; r3.addProperty(DC.title, "Jena - an RDF framework .addProperty(DC.description, "A book about

SPARQL" )

SPARQL" )

for Java" )

Jena") ;

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

SPARQLAn 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 2http://example.org/book# 1 DC.title DC.description SPARQL - the book A book about SPARQL DC.description http://example.org/book# 2 DC.title Advanced techniques for SPARQL DC.description

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

Jena - an RDF framework for Java

A book about Jena

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

remote access protocol. The remote access protocol can be used with plain HTTP or over SOAP. SeeJosekifor 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

ARQ - Querying Remote SPARQL Services SPARQL is aquery languageand a

Firewalls and Proxiesaccessing 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 applicationif it is done before any network connection are made: 35 System.setProperty("socksProxyHost", "socks.corp.com"); Consult the JavaDon't forget to set the proxy for Java if you are

From your applicationTheQueryExecutionFactoryhas methods for

creating aQueryExecutionobject for remote use.QueryExecutionFactory.sparqlService uses the query engine incom.hp.hpl.jena.sparql.engine.http.

These methods build a query execution object that

The remote request is made when

theexecSelect,execConstruct,execDescribeore xecAskmethod is called. and can be processed as usual.

The results are held locally after remote execution36

Protg OWL API

37

OWL API Comparisonshttp://wiki.yoshtec.com/java-owl-api

38

A ComparisonAPI-Name Jastor Type Type 2 Generates Java Classes Yes Tested Tried Version License CPL Problems / Issues / Remarks Unable to run with Jena 2.4 or Jena 2.5

Sommer Type 2 Protege OWL-API 1 & 2 RDFReactor Type 2

? Yes Yes

Not Yet Yes Yes

3.4 beta 4.5.2

BSD MPL BSD / LGPL ?

none More research needed to correct OWL output

Kazuki ? Sesame and Elmo ? OWL API Type 1

? ? No

Not Yet Not Yet Yes 2.1.1

BSD 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

My own implementation

39

From the above Comparison,

ProtegeOWL API seems to be an OK Choice.

40

How to use protege OWL API in Eclipse1-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 Select protege.api from /protege/

41

ProtegeOWL API TutorialBy Amna Basharat Haider Fast - NU , Fall 2008

42

TasksCreating 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