Using JENA to query a SPARQL Endpoint or a file

Submitted by admin on Tue, 08/11/2015 - 14:06

<strong>Endpoint</strong>
<code>
package test_java;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.shared.PrefixMapping;

public class Sparql {
public static void main(String[] args) {
String endpoint = "http://localhost:8080/openrdf-workbench/repositories/dbpedia/query&quot;;
String q = "SELECT DISTINCT (str(?label) as ?classlabel) ?classuri {\n" +
"?subclass rdfs:subClassOf* ?classuri.\n" +
"?classuri rdfs:label ?label.\n" +
"FILTER(?subclass = <http://dbpedia.org/ontology/Engineer&gt; && lang(?label) = \"en\")\n" +
" }";

Query query = QueryFactory.create();
query.setPrefixMapping(PrefixMapping.Standard);
QueryFactory.parse(query, q, "", Syntax.syntaxSPARQL_11);

QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query);

ResultSet r = qexec.execSelect();

ResultSetFormatter.outputAsCSV(r);
}
}

</code>
<strong>File</strong.
<code>
public static void main(String[] args) {
// TODO Auto-generated method stub

Model onto = ModelFactory.createDefaultModel();
Model ontodata = onto.read("changeset/dbpedia_2014.owl", "RDF/XML");

Model removed = ModelFactory.createDefaultModel();
Model data = removed.read("changeset/removed.nt", "N-TRIPLES");

Model total = ontodata.add(data);
String q = "SELECT ?class (count(?instance) as ?count) { ?instance rdf:type ?class. } GROUP BY ?class LIMIT 10";
Query query = QueryFactory.create();
query.setPrefixMapping(PrefixMapping.Standard);
QueryFactory.parse(query, q, "", Syntax.syntaxSPARQL_11);
QueryExecution qexec = QueryExecutionFactory.create(query, total);
ResultSet r = qexec.execSelect();

ResultSetFormatter.outputAsCSV(r);

}
</code>

Etiquetas