Jena
From GetSemantic
Jena is a feature-rich Java RDF and Semantic Web framework.
Contents |
[edit] Documentation
[edit] Create a model and serialize
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.query.*;
public class JenaExample {
public static void main(String[] args) {
Model r = ModelFactory.createDefaultModel(ModelFactory.Standard);
r.read("http://tommorris.org/foaf");
r.write(System.out, "N3"); // outputs RDF/XML
}
}
Model.write() can take a string to specify output:
- 'RDF/XML'
- 'RDF/XML-ABBREV' - more readable RDF/XML
- 'N3' - Notation3. Selects one of:
- 'N3-PP' - pretty print
- 'N3-PLAIN' - "does not nest bNode strutures but does write record-like groups of all properties for a subject"
- 'N3-TRIPLE' - "one statement per line, like N-TRIPLES, but also does qname conversion of URIrefs"
- 'N-TRIPLE'
- 'TURTLE'
See Jena I/O Tutorial for more details.
[edit] 'SELECT' Query a model using SPARQL
We load in a model as before:
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.query.*;
public class JenaExample {
public static void main(String[] args) {
Model r = ModelFactory.createDefaultModel(ModelFactory.Standard);
r.read("http://tommorris.org/foaf");
Now we create a query:
String queryString = "SELECT ?name ?url " +
"WHERE {" +
"<http://tommorris.org/foaf#me> <http://xmlns.com/foaf/0.1/knows> ?person . " +
"?person <http://xmlns.com/foaf/0.1/name> ?name . " +
"?person <http://xmlns.com/foaf/0.1/weblog> ?url . " +
"}";
Query query = QueryFactory.create(queryString);
Now we run it against the model:
QueryExecution qe = QueryExecutionFactory.create(query, r);
ResultSet results = qe.execSelect();
There are a number of ways we can display the results. Firstly, we can just display them in the console:
ResultSetFormatter.out(System.out, results);
Alternatively, we could format them in the SPARQL XML results format or as JSON:
ResultSetFormatter.outputAsXML(System.out, results);
ResultSetFormatter.outputAsJSON(System.out, results);
Or we can iterate over them:
while(results.hasNext()) {
QuerySolution qs = results.nextSolution();
System.out.println(qs.get("?url"));
}
Obviously, replacing System.out with some other function or method makes this more useful, and you can substitute "?url" with another binding from the query.
Finally, we finish off by closing the query, closing our main method and closing the class:
qe.close();
}
}
[edit] Resources
- Homepage
- Jena supports RDFa by Elias Torrez - gives a code sample of how to load RDFa into a model
- IBM DeveloperWorks: Search RDF data with SPARQL (a tutorial by Philip McCarthy on using Jena for SPARQL)

