I’m writing an Application where a user can upload .rdf-Files and then execute SPARQL-Queries on it. Right now I am stuck on how to format the query’s result. For example: an ASK-Query outputs a boolean and a SELECT-Query returns a ResultSet. CONSTRUCT and DESCRIBE return a new RDF-Graph.
How do I get the result of the given query in a form to pass it to my view? In there I hope to print out a HTML-Table.
For a better understanding of my Problem I created this minimalistic code example:
import java.io.InputStream;
import com.hp.hpl.jena.*;
public class playground {
public static void main(String[] args) {
InputStream in = FileManager.get().open("vc-db-1.rdf");
Model model = ModelFactory.createDefaultModel();
model.read(in, null);
String queryStringSelect = "SELECT ?subject ?predicate ?object WHERE { ?subject ?predicate ?object }";
String queryStringAsk = "ASK WHERE { ?subject ?predicate ?object }";
String queryStringDescribe = "DESCRIBE * WHERE { ?subject ?predicate ?object }";
String queryStringConstruct = "CONSTRUCT { ?subject ?predicate ?object } WHERE { ?subject ?predicate ?object }";
QueryExecution qe = QueryExecutionFactory.create(queryStringDescribe,
model);
Query q = QueryFactory.create(queryStringDescribe);
int queryType = q.getQueryType();
switch (queryType) {
case Query.QueryTypeAsk:
boolean b = qe.execAsk(); // Result that has to be formatted
ResultSetFormatter.outputAsTSV(System.out, b);
break;
case Query.QueryTypeConstruct:
model = qe.execConstruct(); // Result that has to be formatted
model.write(System.out);
break;
case Query.QueryTypeDescribe:
model = qe.execDescribe(); // Result that has to be formatted
model.write(System.out);
break;
case Query.QueryTypeSelect:
ResultSet results = qe.execSelect(); // Result that has to be
// formatted
ResultSetFormatter.outputAsTSV(System.out, results);
break;
}
model.close();
qe.close();
}
}
The mentionend .rdf file can be downloaded here: http://jena.apache.org/tutorials/sparql_data/vc-db-1.rdf
I finally found an answer:
I take a ByteArrayOutputStream and use the various
model.write()functions do the rest. For theSELECT-Query I use a textual representation because the providedResultSetFormatter.outputAsRDF()gives me way to much nonsense back. Anyways, here’s the relevant code