简体   繁体   中英

Java Apache Jena SparQL query returns Lexical error when query is valid

I have the following SparQL query:

SELECT ?b ?c WHERE {
ont:http\:\/\/test.com\/test\#com.test.test.test.2.3.4 ?b ?c}

which returns the successfully returns the correct results in OpenRDF Workbench 2.6.5 . However in my Java which is using Jena 2.6.4 when I run the query using the following code

private static ResultSet getQueryResults(String stringQuery, String service) {
    Query query = QueryFactory.create(stringQuery);
    QueryExecution qexec = QueryExecutionFactory.sparqlService(
            service, query);
    ResultSet results = qexec.execSelect(); 
    //ResultSetFormatter.out(System.out, results, query);
    return results;
}

public static ResultSet getDetails(String ID) {
    //we define our sparql query
    String sanatizedID = "ont:" +  sanitizeString(ID);
    String stringQuery = " SELECT ?b ?c WHERE" +
            " { " + sanatizedID + 
            //"{?a"+
            " ?b" +
            " ?c}";
    System.out.println(stringQuery);
    //we define our service
    String service = "http://test.test.com:8181/test-sesame/repositories/test";

    //We write the results of our query into a results set
    ResultSet results = getQueryResults(stringQuery, service);
    return results;
}

private static String sanitizeString(String s) {
    s = s.replace("/", "\\/");
    s = s.replace("#", "\\#");
    s = s.replace(":", "\\:");
    s = s.replace("\"", "\\\"");

    return s;
}

I get the following error

Exception in thread "main" com.hp.hpl.jena.query.QueryParseException: Lexical error at line 1, column 871.  Encountered: ":" (58), after : "\\" 

on line Query query = QueryFactory.create(stringQuery);

I've tried changing Jena version and no luck, can't understand why the query is valid in OpenRDF Workbench 2.6.5 and not in my Java query (I think it may do it's own sanatization) :/

Help would be really appreciated!

"ont:" + sanitizeString(ID);

您需要在查询中为ont:声明前缀,或使用完整格式和<...>

You are using a version of Sesame that supports a slightly older version of the SPARQL 1.1 specification, your prefixed name is not actually valid:

ont:http\:\/\/test.com\/test\#com.test.test.test.2.3.4

With the latest versions of the SPARQL specification it now permitted to use additional : characters directly in a prefixed name and there is no need to escape this with a \\ . So to make this query work with Jena you simply need to remove the \\ before your second :

I'm not sure where Sesame is with its alignment with the latest SPARQL 1.1 specifications but if you try this query on a more recent version of Sesame you will likely see behaviour that aligns with Jena.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM