SlideShare a Scribd company logo
Processing SPARQL Queries using Java
ARQ - A SPARQL Processor for Jena

Raji GHAWI
26/01/2009
Outline



Query Execution



Query Analysis

26/01/2009

2
1. Query Execution
Query Execution
Read a file into a model

String fileName = "../univ.owl";
// Model model = ModelFactory.createDefaultModel();
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
try {
File file = new File(fileName);
FileReader reader = new FileReader(file);
model.read(reader,null);
} catch (Exception e) {
e.printStackTrace();
}

26/01/2009

4
Query Execution
Put the query as a string

PREFIX my:<http://www.something.com/myontology#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?stud ?dip
WHERE {
?stud
my:enrolledIn
}

?dip.

String sparqlQuery =
"PREFIX my:<http://www.something.com/myontology#>n" +
"PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>n" +
"n" +
"SELECT ?stud ?dip n" +
"WHERE {n" +
"
?stud
my:enrolledIn
?dip.n" +
"} ";

26/01/2009

5
Query Execution
Execute the Query

encapsulates a parsed query

read a textual query from a String
Query query = QueryFactory.create(sparqlQuery);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();

a single execution of a query

26/01/2009

6
Query Execution
Print Query Results

result set

ResultSetFormatter.out(System.out, results, query);

textual format

standard output

----------------------------------| stud
| dip
|
===================================
| my:Simon_Thevenin | my:M2_BDIA |
| my:Raji_Ghawi
| my:Doctorat |
| my:Kamel_Boulil
| my:M2_BDIA |
-----------------------------------

26/01/2009

output

7
XML format
ResultSetFormatter.outputAsXML(System.out, results);

26/01/2009

<?xml version="1.0"?>
<sparql
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:xs="http://www.w3.org/2001/XMLSchema#"
xmlns="http://www.w3.org/2005/sparql-results#" >
<head>
<variable name="stud"/>
<variable name="dip"/>
</head>
<results ordered="false" distinct="false">
<result>
<binding name="stud">
<uri>http://www.something.com/myontology#Simon_Thevenin</uri>
</binding>
<binding name="dip">
<uri>http://www.something.com/myontology#M2_BDIA</uri>
</binding>
</result>
<result>
<binding name="stud">
<uri>http://www.something.com/myontology#Raji_Ghawi</uri>
</binding>
<binding name="dip">
<uri>http://www.something.com/myontology#Doctorat</uri>
</binding>
</result>
<result>
<binding name="stud">
<uri>http://www.something.com/myontology#Kamel_Boulil</uri>
</binding>
<binding name="dip">
<uri>http://www.something.com/myontology#M2_BDIA</uri>
</binding>
</result>
</results>
</sparql>

output

8
Query Execution
Save Query Results to String

MyOutputStream myOutput = new MyOutputStream();
ResultSetFormatter.out(myOutput, results, query);
String sparqlResults = myOutput.getString();

class MyOutputStream extends OutputStream {
StringBuffer buf;
public MyOutputStream(){
buf = new StringBuffer();
}
public void write(int character) throws IOException {
buf.append((char) character);
}
public String getString() {
return buf.toString();
}
}
26/01/2009

9
Query Execution
Retrieve Query Solutions
ResultSet results = qe.execSelect();
List vars = results.getResultVars();
while(results.hasNext()) {
QuerySolution qs = results.nextSolution();
System.out.println("--------- solution ---------");
for (int i = 0; i < vars.size(); i++) {
String var = vars.get(i).toString();
RDFNode node = qs.get(var);
System.out.println(var + "t" + node.toString());
}
}

--------stud
dip
--------stud
dip
--------stud
dip
26/01/2009

output

solution --------http://www.something.com/myontology#Guillermo_Gomez
http://www.something.com/myontology#These
solution --------http://www.something.com/myontology#Elie_Raad
http://www.something.com/myontology#M2-BDIA
solution --------http://www.something.com/myontology#Raji_Ghawi
http://www.something.com/myontology#M2-BDIA

10
ResultSet results = qe.execSelect();
List vars = results.getResultVars();
PrefixMapping pm = query.getPrefixMapping();
while (results.hasNext()) {
QuerySolution qs = results.nextSolution();
System.out.println("--------- solution ---------");
for (int i = 0; i < vars.size(); i++) {
String var = vars.get(i).toString();
RDFNode node = qs.get(var);
String text = "";
if(node.isURIResource()){
text = pm.shortForm(node.asNode().getURI());
} else {
text = node.toString();
}
System.out.println(var+"t"+text);
}
}
--------stud
dip
--------stud
dip
--------stud
dip
26/01/2009

solution --------my:Guillermo_Gomez
my:These
solution --------my:Elie_Raad
my:M2-BDIA
solution --------my:Raji_Ghawi
my:M2-BDIA

output

11
2. Query Analysis
Query Analysis

PREFIX my:<http://www.something.com/myontology#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?stud ?modName
WHERE {
?stud
rdf:type
my:Student .
?stud
my:enrolledIn
?dip .
?dip
my:hasModule
?mod .
?mod
my:moduleName
?modName.
FILTER
(?modName='Databases').
}

26/01/2009

13
Query Analysis
Put the Query in a String

String sparqlQuery =
"PREFIX my:<http://www.something.com/myontology#>n" +
"PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>n" +
"n" +
"SELECT ?stud ?modName n" +
"WHERE {n" +
"
?stud
rdf:type
my:Student .n" +
"
?stud
my:enrolledIn
?dip .n" +
"
?dip
my:hasModule
?mod .n" +
"
?mod
my:moduleName
?modName.n" +
"
FILTER(?modName='Databases').n" +
"} ";

26/01/2009

14
Query Analysis
Create the Query

Query query = QueryFactory.create(sparqlQuery);
System.out.println("---------- Query
System.out.println(query);

----------");

output

---------- Query ---------PREFIX rdf:
<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX my:
<http://www.something.com/myontology#>
SELECT ?stud ?modName
WHERE
{ ?stud my:enrolledIn ?dip ;
rdf:type
my:Student ;
my:enrolledIn ?dip .
?dip
my:hasModule
?mod .
?mod
my:moduleName ?modName .
FILTER ( ?modName = "Databases" )
}
26/01/2009

15
Query Analysis
Prefix Mapping

System.out.println("------ Prefix Mapping ------");
Map map = query.getPrefixMapping().getNsPrefixMap();
Iterator pmIter= map.entrySet().iterator();
while (pmIter.hasNext()) {
Entry ent = (Entry) pmIter.next();
String prefix = ent.getKey().toString();
String namespace = ent.getValue().toString();
System.out.println(prefix+"t"+namespace);
}

------ Prefix Mapping -----rdf
http://www.w3.org/1999/02/22-rdf-syntax-ns#
my
http://www.something.com/myontology#

26/01/2009

output

16
Query Analysis
Retrieve Result Variables

System.out.println("------ Result Variables ------");
List varList = query.getResultVars();
for (int i = 0; i < varList.size(); i++) {
String var = varList.get(i).toString();
System.out.println(var);
}

------ Result Variables -----stud
modName

output

query.isQueryResultStar()
query.isDistinct()
26/01/2009

17
Query Analysis
Retrieve All Variables

System.out.println("------- All Variables --------");
Iterator varIter = query.getQueryBlock().varsMentioned().iterator();
while(varIter.hasNext()){
String var = varIter.next().toString();
System.out.println(var);
}

------- All Variables -------stud
dip
mod
modName

26/01/2009

output

18
Query Analysis
Fetch Query Elements
ElementGroup eg = (ElementGroup) query.getQueryBlock().getPatternElement();
List elemList = eg.getElements();
for(int i=0; i<elemList.size(); i++){
Element elem = (Element) elemList.get(i);
try{
if (elem instanceof ElementOptional) {
ElementOptional elOp = (ElementOptional) elem;
// ....
} else if (elem instanceof ElementFilter) {
ElementFilter elf = (ElementFilter) elem;
// ....
} else if (elem instanceof ElementTriplePattern) {
ElementTriplePattern etp = (ElementTriplePattern) elem;
// ....
}
} catch(ClassCastException e){
e.printStackTrace();
}
}

26/01/2009

19
Query Analysis
ElementOptional
ElementOptional elOp = (ElementOptional) elem;
Iterator iter = elOp.varsMentioned().iterator();
// ....
ElementGroup newElemGrp = (ElementGroup) elOp.getElement();
List elemList = eg.getElements();
for(int i=0; i<elemList.size(); i++){
// ....
}

26/01/2009

20
Query Analysis
ElementFilter
ElementFilter elf = (ElementFilter) elem;
Iterator iter = elf.varsMentioned().iterator();
// ....
Expr expr = elf.getConstraint().getExpr();
// ....

26/01/2009

21
Query Analysis
Expr

E_LogicalAnd
E_LogicalOr
E_Equals
E_NotEquals
E_LessThan
E_LessThanOrEqual
E_GreaterThan
E_GreaterThanOrEqual
E_LogicalNot

getLeft()
getRight()

getSubExpr()

E_Regex
NodeVar
if (expr instanceof E_LogicalAnd) {
getVarName()
E_LogicalAnd and = (E_LogicalAnd) expr;
NodeValueInteger
Expr left = and.getLeft();
NodeValueFloat
Expr right = and.getRight();
asString()
NodeValueDecimal
//
NodeValueString
} else if (expr instanceof E_LogicalOr) {
...
// .. ..
}
// .. ..
else if (expr instanceof E_Regex) {
E_Regex re = (E_Regex) expr;
String pattern = ((NodeValueString) re.getPattern()).asString();
String varName = re.getRegexExpr().getVarName().toString();
// .. ..
}
26/01/2009

22
Query Analysis
ElementTriplePattern
ElementTriplePattern etp = (ElementTriplePattern) elem;
Triple triple = etp.getTriple();
Node subject = triple.getSubject();
Node predicate = triple.getPredicate();
Node object = triple.getObject();






SELECT ?stud ?dip
WHERE {
?stud
my:enrolledIn
?dip
my:diplomaName
}

boolean isURI()
boolean isLiteral()
boolean isVariable()

Subject
Variable
26/01/2009

URI

Predicate

?dip.
"BDIA".

Object
Literal
23
Subject

Predicate

Object

URI

Literal
Variable

26/01/2009

24
Query Analysis
OrderBy

if(query.getOrderBy() != null){
Iterator orderBy = query.getOrderBy().iterator();
while (orderBy.hasNext()) {
SortCondition sc = (SortCondition) orderBy.next();
Expr exp = sc.getExpression();
if(exp.isVariable()){
String obv = exp.getVarName();
// ....
}
}
}

26/01/2009

25
References


ARQ - A SPARQL Processor for Jena




http://jena.sourceforge.net/ARQ/

Search RDF data with SPARQL


http://www.ibm.com/developerworks/xml/library/j-sparql

26/01/2009

26

More Related Content

What's hot

Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
CODE WHITE GmbH
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python Meetup
Areski Belaid
 
Log4 J
Log4 JLog4 J
Log4 J
Sunil OS
 
Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019
Michel Schudel
 
Build JSON and XML using RABL gem
Build JSON and XML using RABL gemBuild JSON and XML using RABL gem
Build JSON and XML using RABL gem
Nascenia IT
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
安齊 劉
 
XXE: How to become a Jedi
XXE: How to become a JediXXE: How to become a Jedi
XXE: How to become a Jedi
Yaroslav Babin
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
mengukagan
 
Flask Basics
Flask BasicsFlask Basics
Flask Basics
Eueung Mulyana
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
Ian Barber
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
Idiomatic kotlin
Idiomatic kotlinIdiomatic kotlin
Idiomatic kotlin
Anton Arhipov
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
Vitaly Polonetsky
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
Sherihan Anver
 
C++ oop
C++ oopC++ oop
C++ oop
Sunil OS
 
JDBC
JDBCJDBC
JDBC
Sunil OS
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
Hector Canto
 
Hibernate
Hibernate Hibernate
Hibernate
Sunil OS
 

What's hot (20)

Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
Java Deserialization Vulnerabilities - The Forgotten Bug Class (RuhrSec Edition)
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python Meetup
 
Log4 J
Log4 JLog4 J
Log4 J
 
Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019
 
Build JSON and XML using RABL gem
Build JSON and XML using RABL gemBuild JSON and XML using RABL gem
Build JSON and XML using RABL gem
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
 
XXE: How to become a Jedi
XXE: How to become a JediXXE: How to become a Jedi
XXE: How to become a Jedi
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
 
Flask Basics
Flask BasicsFlask Basics
Flask Basics
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Idiomatic kotlin
Idiomatic kotlinIdiomatic kotlin
Idiomatic kotlin
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
C++ oop
C++ oopC++ oop
C++ oop
 
JDBC
JDBCJDBC
JDBC
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Hibernate
Hibernate Hibernate
Hibernate
 

Viewers also liked

Java and OWL
Java and OWLJava and OWL
Java and OWL
Raji Ghawi
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaAleksander Pohl
 
An Introduction to the Jena API
An Introduction to the Jena APIAn Introduction to the Jena API
An Introduction to the Jena API
Craig Trim
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
Myungjin Lee
 
Database-to-Ontology Mapping Generation for Semantic Interoperability
Database-to-Ontology Mapping Generation for Semantic InteroperabilityDatabase-to-Ontology Mapping Generation for Semantic Interoperability
Database-to-Ontology Mapping Generation for Semantic Interoperability
Raji Ghawi
 
Twinkle: A SPARQL Query Tool
Twinkle: A SPARQL Query ToolTwinkle: A SPARQL Query Tool
Twinkle: A SPARQL Query Tool
Leigh Dodds
 
Understanding Mobile Phone Requirements
Understanding Mobile Phone RequirementsUnderstanding Mobile Phone Requirements
Understanding Mobile Phone Requirementschenjennan
 
Rdf And Rdf Schema For Ontology Specification
Rdf And Rdf Schema For Ontology SpecificationRdf And Rdf Schema For Ontology Specification
Rdf And Rdf Schema For Ontology Specificationchenjennan
 
Selecting with SPARQL
Selecting with SPARQLSelecting with SPARQL
Selecting with SPARQL
ostephens
 
Rest web services com Java
Rest web services com JavaRest web services com Java
Rest web services com JavajesuinoPower
 
Semantic Technologies and Triplestores for Business Intelligence
Semantic Technologies and Triplestores for Business IntelligenceSemantic Technologies and Triplestores for Business Intelligence
Semantic Technologies and Triplestores for Business IntelligenceMarin Dimitrov
 
Linked Data on the BBC
Linked Data on the BBCLinked Data on the BBC
Linked Data on the BBC
Patrick Sinclair
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQLLino Valdivia
 
OWL-XML-Summer-School-09
OWL-XML-Summer-School-09OWL-XML-Summer-School-09
OWL-XML-Summer-School-09
Duncan Hull
 
Diseño de Ontologías: Protégé - OWL: SPARQL
Diseño de Ontologías: Protégé - OWL: SPARQLDiseño de Ontologías: Protégé - OWL: SPARQL
Diseño de Ontologías: Protégé - OWL: SPARQL
Carlos Casamayor
 
RuleML 2015: Ontology Reasoning using Rules in an eHealth Context
RuleML 2015: Ontology Reasoning using Rules in an eHealth ContextRuleML 2015: Ontology Reasoning using Rules in an eHealth Context
RuleML 2015: Ontology Reasoning using Rules in an eHealth Context
RuleML
 
Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...
Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...
Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...
RuleML
 
정부3.0과직접민주주의
정부3.0과직접민주주의정부3.0과직접민주주의
정부3.0과직접민주주의
Min Hwa Lee
 
Learning sparql 2012 12
Learning sparql 2012 12Learning sparql 2012 12
Learning sparql 2012 12
Jerven Bolleman
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaKatrien Verbert
 

Viewers also liked (20)

Java and OWL
Java and OWLJava and OWL
Java and OWL
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for Java
 
An Introduction to the Jena API
An Introduction to the Jena APIAn Introduction to the Jena API
An Introduction to the Jena API
 
Jena Programming
Jena ProgrammingJena Programming
Jena Programming
 
Database-to-Ontology Mapping Generation for Semantic Interoperability
Database-to-Ontology Mapping Generation for Semantic InteroperabilityDatabase-to-Ontology Mapping Generation for Semantic Interoperability
Database-to-Ontology Mapping Generation for Semantic Interoperability
 
Twinkle: A SPARQL Query Tool
Twinkle: A SPARQL Query ToolTwinkle: A SPARQL Query Tool
Twinkle: A SPARQL Query Tool
 
Understanding Mobile Phone Requirements
Understanding Mobile Phone RequirementsUnderstanding Mobile Phone Requirements
Understanding Mobile Phone Requirements
 
Rdf And Rdf Schema For Ontology Specification
Rdf And Rdf Schema For Ontology SpecificationRdf And Rdf Schema For Ontology Specification
Rdf And Rdf Schema For Ontology Specification
 
Selecting with SPARQL
Selecting with SPARQLSelecting with SPARQL
Selecting with SPARQL
 
Rest web services com Java
Rest web services com JavaRest web services com Java
Rest web services com Java
 
Semantic Technologies and Triplestores for Business Intelligence
Semantic Technologies and Triplestores for Business IntelligenceSemantic Technologies and Triplestores for Business Intelligence
Semantic Technologies and Triplestores for Business Intelligence
 
Linked Data on the BBC
Linked Data on the BBCLinked Data on the BBC
Linked Data on the BBC
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQL
 
OWL-XML-Summer-School-09
OWL-XML-Summer-School-09OWL-XML-Summer-School-09
OWL-XML-Summer-School-09
 
Diseño de Ontologías: Protégé - OWL: SPARQL
Diseño de Ontologías: Protégé - OWL: SPARQLDiseño de Ontologías: Protégé - OWL: SPARQL
Diseño de Ontologías: Protégé - OWL: SPARQL
 
RuleML 2015: Ontology Reasoning using Rules in an eHealth Context
RuleML 2015: Ontology Reasoning using Rules in an eHealth ContextRuleML 2015: Ontology Reasoning using Rules in an eHealth Context
RuleML 2015: Ontology Reasoning using Rules in an eHealth Context
 
Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...
Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...
Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...
 
정부3.0과직접민주주의
정부3.0과직접민주주의정부3.0과직접민주주의
정부3.0과직접민주주의
 
Learning sparql 2012 12
Learning sparql 2012 12Learning sparql 2012 12
Learning sparql 2012 12
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPedia
 

Similar to Java and SPARQL

Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
David Rajah Selvaraj
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
DoHyun Jung
 
Data shapes-test-suite
Data shapes-test-suiteData shapes-test-suite
Data shapes-test-suite
Jose Emilio Labra Gayo
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
Andrea Francia
 
Good Practices On Test Automation
Good Practices On Test AutomationGood Practices On Test Automation
Good Practices On Test Automation
Gustavo Labbate Godoy
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitsmueller_sandsmedia
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder
 
Soundreader.classpathSoundreader.project Soundre.docx
Soundreader.classpathSoundreader.project  Soundre.docxSoundreader.classpathSoundreader.project  Soundre.docx
Soundreader.classpathSoundreader.project Soundre.docx
whitneyleman54422
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
Suman Sourav
 
Android Automated Testing
Android Automated TestingAndroid Automated Testing
Android Automated Testing
roisagiv
 
Generating characterization tests for legacy code
Generating characterization tests for legacy codeGenerating characterization tests for legacy code
Generating characterization tests for legacy code
Jonas Follesø
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
Sébastien Prunier
 
Java 104
Java 104Java 104
Java 104
Manuela Grindei
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
Manuela Grindei
 
SPARQLing cocktails
SPARQLing cocktailsSPARQLing cocktails
SPARQLing cocktails
Timea Turdean
 
Unsafe JAX-RS: Breaking REST API
Unsafe JAX-RS: Breaking REST APIUnsafe JAX-RS: Breaking REST API
Unsafe JAX-RS: Breaking REST API
Mikhail Egorov
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
 
Core Php Component Presentation
Core Php Component PresentationCore Php Component Presentation
Core Php Component Presentation
John Coonen
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder
 

Similar to Java and SPARQL (20)

Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Data shapes-test-suite
Data shapes-test-suiteData shapes-test-suite
Data shapes-test-suite
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
Good Practices On Test Automation
Good Practices On Test AutomationGood Practices On Test Automation
Good Practices On Test Automation
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Soundreader.classpathSoundreader.project Soundre.docx
Soundreader.classpathSoundreader.project  Soundre.docxSoundreader.classpathSoundreader.project  Soundre.docx
Soundreader.classpathSoundreader.project Soundre.docx
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Android Automated Testing
Android Automated TestingAndroid Automated Testing
Android Automated Testing
 
Generating characterization tests for legacy code
Generating characterization tests for legacy codeGenerating characterization tests for legacy code
Generating characterization tests for legacy code
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
Java 104
Java 104Java 104
Java 104
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
SPARQLing cocktails
SPARQLing cocktailsSPARQLing cocktails
SPARQLing cocktails
 
Unsafe JAX-RS: Breaking REST API
Unsafe JAX-RS: Breaking REST APIUnsafe JAX-RS: Breaking REST API
Unsafe JAX-RS: Breaking REST API
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
Core Php Component Presentation
Core Php Component PresentationCore Php Component Presentation
Core Php Component Presentation
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 

More from Raji Ghawi

Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
Raji Ghawi
 
Java and XML
Java and XMLJava and XML
Java and XML
Raji Ghawi
 
SPARQL
SPARQLSPARQL
SPARQL
Raji Ghawi
 
XQuery
XQueryXQuery
XQuery
Raji Ghawi
 
XPath
XPathXPath
XPath
Raji Ghawi
 
Ontology-based Cooperation of Information Systems
Ontology-based Cooperation of Information SystemsOntology-based Cooperation of Information Systems
Ontology-based Cooperation of Information Systems
Raji Ghawi
 
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information SourcesOWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
Raji Ghawi
 
Coopération des Systèmes d'Informations basée sur les Ontologies
Coopération des Systèmes d'Informations basée sur les OntologiesCoopération des Systèmes d'Informations basée sur les Ontologies
Coopération des Systèmes d'Informations basée sur les Ontologies
Raji Ghawi
 
Building Ontologies from Multiple Information Sources
Building Ontologies from Multiple Information SourcesBuilding Ontologies from Multiple Information Sources
Building Ontologies from Multiple Information Sources
Raji Ghawi
 

More from Raji Ghawi (10)

Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
Java and XML
Java and XMLJava and XML
Java and XML
 
SPARQL
SPARQLSPARQL
SPARQL
 
XQuery
XQueryXQuery
XQuery
 
XPath
XPathXPath
XPath
 
Ontology-based Cooperation of Information Systems
Ontology-based Cooperation of Information SystemsOntology-based Cooperation of Information Systems
Ontology-based Cooperation of Information Systems
 
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information SourcesOWSCIS: Ontology and Web Service based Cooperation of Information Sources
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
 
Coopération des Systèmes d'Informations basée sur les Ontologies
Coopération des Systèmes d'Informations basée sur les OntologiesCoopération des Systèmes d'Informations basée sur les Ontologies
Coopération des Systèmes d'Informations basée sur les Ontologies
 
Building Ontologies from Multiple Information Sources
Building Ontologies from Multiple Information SourcesBuilding Ontologies from Multiple Information Sources
Building Ontologies from Multiple Information Sources
 

Recently uploaded

Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 

Recently uploaded (20)

Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 

Java and SPARQL

  • 1. Processing SPARQL Queries using Java ARQ - A SPARQL Processor for Jena Raji GHAWI 26/01/2009
  • 4. Query Execution Read a file into a model String fileName = "../univ.owl"; // Model model = ModelFactory.createDefaultModel(); OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM); try { File file = new File(fileName); FileReader reader = new FileReader(file); model.read(reader,null); } catch (Exception e) { e.printStackTrace(); } 26/01/2009 4
  • 5. Query Execution Put the query as a string PREFIX my:<http://www.something.com/myontology#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT ?stud ?dip WHERE { ?stud my:enrolledIn } ?dip. String sparqlQuery = "PREFIX my:<http://www.something.com/myontology#>n" + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>n" + "n" + "SELECT ?stud ?dip n" + "WHERE {n" + " ?stud my:enrolledIn ?dip.n" + "} "; 26/01/2009 5
  • 6. Query Execution Execute the Query encapsulates a parsed query read a textual query from a String Query query = QueryFactory.create(sparqlQuery); QueryExecution qe = QueryExecutionFactory.create(query, model); ResultSet results = qe.execSelect(); a single execution of a query 26/01/2009 6
  • 7. Query Execution Print Query Results result set ResultSetFormatter.out(System.out, results, query); textual format standard output ----------------------------------| stud | dip | =================================== | my:Simon_Thevenin | my:M2_BDIA | | my:Raji_Ghawi | my:Doctorat | | my:Kamel_Boulil | my:M2_BDIA | ----------------------------------- 26/01/2009 output 7
  • 8. XML format ResultSetFormatter.outputAsXML(System.out, results); 26/01/2009 <?xml version="1.0"?> <sparql xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xs="http://www.w3.org/2001/XMLSchema#" xmlns="http://www.w3.org/2005/sparql-results#" > <head> <variable name="stud"/> <variable name="dip"/> </head> <results ordered="false" distinct="false"> <result> <binding name="stud"> <uri>http://www.something.com/myontology#Simon_Thevenin</uri> </binding> <binding name="dip"> <uri>http://www.something.com/myontology#M2_BDIA</uri> </binding> </result> <result> <binding name="stud"> <uri>http://www.something.com/myontology#Raji_Ghawi</uri> </binding> <binding name="dip"> <uri>http://www.something.com/myontology#Doctorat</uri> </binding> </result> <result> <binding name="stud"> <uri>http://www.something.com/myontology#Kamel_Boulil</uri> </binding> <binding name="dip"> <uri>http://www.something.com/myontology#M2_BDIA</uri> </binding> </result> </results> </sparql> output 8
  • 9. Query Execution Save Query Results to String MyOutputStream myOutput = new MyOutputStream(); ResultSetFormatter.out(myOutput, results, query); String sparqlResults = myOutput.getString(); class MyOutputStream extends OutputStream { StringBuffer buf; public MyOutputStream(){ buf = new StringBuffer(); } public void write(int character) throws IOException { buf.append((char) character); } public String getString() { return buf.toString(); } } 26/01/2009 9
  • 10. Query Execution Retrieve Query Solutions ResultSet results = qe.execSelect(); List vars = results.getResultVars(); while(results.hasNext()) { QuerySolution qs = results.nextSolution(); System.out.println("--------- solution ---------"); for (int i = 0; i < vars.size(); i++) { String var = vars.get(i).toString(); RDFNode node = qs.get(var); System.out.println(var + "t" + node.toString()); } } --------stud dip --------stud dip --------stud dip 26/01/2009 output solution --------http://www.something.com/myontology#Guillermo_Gomez http://www.something.com/myontology#These solution --------http://www.something.com/myontology#Elie_Raad http://www.something.com/myontology#M2-BDIA solution --------http://www.something.com/myontology#Raji_Ghawi http://www.something.com/myontology#M2-BDIA 10
  • 11. ResultSet results = qe.execSelect(); List vars = results.getResultVars(); PrefixMapping pm = query.getPrefixMapping(); while (results.hasNext()) { QuerySolution qs = results.nextSolution(); System.out.println("--------- solution ---------"); for (int i = 0; i < vars.size(); i++) { String var = vars.get(i).toString(); RDFNode node = qs.get(var); String text = ""; if(node.isURIResource()){ text = pm.shortForm(node.asNode().getURI()); } else { text = node.toString(); } System.out.println(var+"t"+text); } } --------stud dip --------stud dip --------stud dip 26/01/2009 solution --------my:Guillermo_Gomez my:These solution --------my:Elie_Raad my:M2-BDIA solution --------my:Raji_Ghawi my:M2-BDIA output 11
  • 13. Query Analysis PREFIX my:<http://www.something.com/myontology#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT ?stud ?modName WHERE { ?stud rdf:type my:Student . ?stud my:enrolledIn ?dip . ?dip my:hasModule ?mod . ?mod my:moduleName ?modName. FILTER (?modName='Databases'). } 26/01/2009 13
  • 14. Query Analysis Put the Query in a String String sparqlQuery = "PREFIX my:<http://www.something.com/myontology#>n" + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>n" + "n" + "SELECT ?stud ?modName n" + "WHERE {n" + " ?stud rdf:type my:Student .n" + " ?stud my:enrolledIn ?dip .n" + " ?dip my:hasModule ?mod .n" + " ?mod my:moduleName ?modName.n" + " FILTER(?modName='Databases').n" + "} "; 26/01/2009 14
  • 15. Query Analysis Create the Query Query query = QueryFactory.create(sparqlQuery); System.out.println("---------- Query System.out.println(query); ----------"); output ---------- Query ---------PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX my: <http://www.something.com/myontology#> SELECT ?stud ?modName WHERE { ?stud my:enrolledIn ?dip ; rdf:type my:Student ; my:enrolledIn ?dip . ?dip my:hasModule ?mod . ?mod my:moduleName ?modName . FILTER ( ?modName = "Databases" ) } 26/01/2009 15
  • 16. Query Analysis Prefix Mapping System.out.println("------ Prefix Mapping ------"); Map map = query.getPrefixMapping().getNsPrefixMap(); Iterator pmIter= map.entrySet().iterator(); while (pmIter.hasNext()) { Entry ent = (Entry) pmIter.next(); String prefix = ent.getKey().toString(); String namespace = ent.getValue().toString(); System.out.println(prefix+"t"+namespace); } ------ Prefix Mapping -----rdf http://www.w3.org/1999/02/22-rdf-syntax-ns# my http://www.something.com/myontology# 26/01/2009 output 16
  • 17. Query Analysis Retrieve Result Variables System.out.println("------ Result Variables ------"); List varList = query.getResultVars(); for (int i = 0; i < varList.size(); i++) { String var = varList.get(i).toString(); System.out.println(var); } ------ Result Variables -----stud modName output query.isQueryResultStar() query.isDistinct() 26/01/2009 17
  • 18. Query Analysis Retrieve All Variables System.out.println("------- All Variables --------"); Iterator varIter = query.getQueryBlock().varsMentioned().iterator(); while(varIter.hasNext()){ String var = varIter.next().toString(); System.out.println(var); } ------- All Variables -------stud dip mod modName 26/01/2009 output 18
  • 19. Query Analysis Fetch Query Elements ElementGroup eg = (ElementGroup) query.getQueryBlock().getPatternElement(); List elemList = eg.getElements(); for(int i=0; i<elemList.size(); i++){ Element elem = (Element) elemList.get(i); try{ if (elem instanceof ElementOptional) { ElementOptional elOp = (ElementOptional) elem; // .... } else if (elem instanceof ElementFilter) { ElementFilter elf = (ElementFilter) elem; // .... } else if (elem instanceof ElementTriplePattern) { ElementTriplePattern etp = (ElementTriplePattern) elem; // .... } } catch(ClassCastException e){ e.printStackTrace(); } } 26/01/2009 19
  • 20. Query Analysis ElementOptional ElementOptional elOp = (ElementOptional) elem; Iterator iter = elOp.varsMentioned().iterator(); // .... ElementGroup newElemGrp = (ElementGroup) elOp.getElement(); List elemList = eg.getElements(); for(int i=0; i<elemList.size(); i++){ // .... } 26/01/2009 20
  • 21. Query Analysis ElementFilter ElementFilter elf = (ElementFilter) elem; Iterator iter = elf.varsMentioned().iterator(); // .... Expr expr = elf.getConstraint().getExpr(); // .... 26/01/2009 21
  • 22. Query Analysis Expr E_LogicalAnd E_LogicalOr E_Equals E_NotEquals E_LessThan E_LessThanOrEqual E_GreaterThan E_GreaterThanOrEqual E_LogicalNot getLeft() getRight() getSubExpr() E_Regex NodeVar if (expr instanceof E_LogicalAnd) { getVarName() E_LogicalAnd and = (E_LogicalAnd) expr; NodeValueInteger Expr left = and.getLeft(); NodeValueFloat Expr right = and.getRight(); asString() NodeValueDecimal // NodeValueString } else if (expr instanceof E_LogicalOr) { ... // .. .. } // .. .. else if (expr instanceof E_Regex) { E_Regex re = (E_Regex) expr; String pattern = ((NodeValueString) re.getPattern()).asString(); String varName = re.getRegexExpr().getVarName().toString(); // .. .. } 26/01/2009 22
  • 23. Query Analysis ElementTriplePattern ElementTriplePattern etp = (ElementTriplePattern) elem; Triple triple = etp.getTriple(); Node subject = triple.getSubject(); Node predicate = triple.getPredicate(); Node object = triple.getObject();    SELECT ?stud ?dip WHERE { ?stud my:enrolledIn ?dip my:diplomaName } boolean isURI() boolean isLiteral() boolean isVariable() Subject Variable 26/01/2009 URI Predicate ?dip. "BDIA". Object Literal 23
  • 25. Query Analysis OrderBy if(query.getOrderBy() != null){ Iterator orderBy = query.getOrderBy().iterator(); while (orderBy.hasNext()) { SortCondition sc = (SortCondition) orderBy.next(); Expr exp = sc.getExpression(); if(exp.isVariable()){ String obv = exp.getVarName(); // .... } } } 26/01/2009 25
  • 26. References  ARQ - A SPARQL Processor for Jena   http://jena.sourceforge.net/ARQ/ Search RDF data with SPARQL  http://www.ibm.com/developerworks/xml/library/j-sparql 26/01/2009 26