I would like to get all resource/object pairs from DBPedia related to Jupiter and construct query that output results in RDF format in java by means of Apache Jena. My construct query works in http://dbpedia.org/sparql service which is as follows:
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
construct {<http://dbpedia.org/resource/Jupiter> ?o ?r. }
{{ <http://dbpedia.org/resource/Jupiter> ?o ?r }
UNION
{?o ?r <http://dbpedia.org/resource/Jupiter>}}
I wrote a java program to write the CONSTRUCT query results in Jupiter.rdf file in RDF format, but it showed exception. My java code is as follows:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.jena.query.ParameterizedSparqlString;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSetFactory;
import org.apache.jena.query.ResultSetRewindable;
public class Jupiter {
public static void main(String[] args) throws IOException {
ParameterizedSparqlString querystring = new ParameterizedSparqlString(""
+ "construct {<http://dbpedia.org/resource/Jupiter> ?o ?r } where {{ <http://dbpedia.org/resource/Jupiter> ?o ?r } UNION"
+ " {?r ?o <http://dbpedia.org/resource/Jupiter>}}");
QueryExecution exec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", querystring.asQuery());
ResultSetRewindable result = ResultSetFactory.makeRewindable(exec.execSelect());
try (BufferedWriter bw = new BufferedWriter(new FileWriter("Jupiter.rdf")))
{
while (result.hasNext()) {
QuerySolution querysolution = result.next();
bw.write(querysolution.get("o").toString());
bw.write(querysolution.get("r").toString());
}
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the exception is thus:
Exception in thread "main" org.apache.jena.sparql.resultset.ResultSetException: Not a string: key: value
at org.apache.jena.sparql.resultset.JSONInput.stringOrNull(JSONInput.java:230)
at org.apache.jena.sparql.resultset.JSONInput.parseOneTerm(JSONInput.java:201)
at org.apache.jena.sparql.resultset.JSONInput.parse(JSONInput.java:172)
at org.apache.jena.sparql.resultset.JSONInput.process(JSONInput.java:100)
at org.apache.jena.sparql.resultset.JSONInput.fromJSON(JSONInput.java:63)
at org.apache.jena.query.ResultSetFactory.fromJSON(ResultSetFactory.java:331)
at org.apache.jena.sparql.engine.http.QueryEngineHTTP.execResultSetInner(QueryEngineHTTP.java:385)
at org.apache.jena.sparql.engine.http.QueryEngineHTTP.execSelect(QueryEngineHTTP.java:351)
Could you tell me why this happens,please? Your help is greatly appreciated
You have a SPARQL CONSTRUCT query, not a SELECT query. Thus, you have to call exec.execConstruct()
and you'll get a Model
object back, which contains triples instead of a ResultSet
.