private Repository parseSparqlResponse(final URI resource, InputStream in, String contentType) throws RepositoryException, IOException, QueryResultParseException, TupleQueryResultHandlerException {
TupleQueryResultFormat format = QueryResultIO.getParserFormatForMIMEType(contentType, TupleQueryResultFormat.SPARQL);
final Repository triples = new SailRepository(new MemoryStore());
triples.initialize();
QueryResultIO.parse(in,format,
new TupleQueryResultHandler() {
RepositoryConnection con;
URI subject;
@Override
public void startQueryResult(List<String> bindingNames) throws TupleQueryResultHandlerException {
subject = triples.getValueFactory().createURI(resource.stringValue());
try {
con = triples.getConnection();
} catch (RepositoryException e) {
throw new TupleQueryResultHandlerException("error while creating repository connection",e);
}
}
@Override
public void endQueryResult() throws TupleQueryResultHandlerException {
try {
con.commit();
con.close();
} catch (RepositoryException e) {
throw new TupleQueryResultHandlerException("error while closing repository connection",e);
}
}
@Override
public void handleSolution(BindingSet bindingSet) throws TupleQueryResultHandlerException {
try {
Value predicate = bindingSet.getValue("p");
Value object = bindingSet.getValue("o");
if(predicate instanceof URI) {
con.add(triples.getValueFactory().createStatement(subject,(URI)predicate,object));
} else {
log.error("ignoring binding as predicate {} is not a URI",predicate);
}
} catch (RepositoryException e) {
throw new TupleQueryResultHandlerException("error while adding triple to repository connection",e);
}
}
},
triples.getValueFactory());
return triples;
}