I need to parse SPARQL and SPARQL Update queries in a Java application. I tried to do this by the use of the rdf4j library. This library provides possibilities to parse Queries (e.g. QueryParserUtil.parseQuery(...) or SyntaxTreeBuilder.parseQuery(...)) and possibilities to parse Updates (e.g. QueryParserUtil.parseUpdate(...) or SyntaxTreeBuilder.parseUpdateSequence(...)). But there is no method that allows to parse both of them. Therefore I need to figure out if the query string represents a query or an update.
When an update string is applied to a parseQuery() method an ParseException is thrown. This is also the case for the other way round. Of course it would be possible to always try the other method if an exception is thrown. But that would be a bad programming style.
Is there a method in the rdf4j library that can be used to check whether the queryString represents an update or a simple query?
And if not, are there other solutions for parsing both updates and queries?
You can use QueryParserUtil.parseOperation() for this purpose. It parses the String, and provides you back with a ParsedOperation
object, which has two subtypes: ParsedUpdate
and ParsedQuery
. Then you can do a simple instanceof
check:
String str = "....";
ParsedOperation operation = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, str, null);
if (operation instanceof ParsedQuery) {
// it's a query
} else {
// it's an update
}