use of org.openrdf.query.parser.ParsedTupleQuery in project QueryAnalysis by Wikidata.
the class StandardizingSPARQLParser method parseQuery.
/**
* @param qc The query container to be parsed
* @param baseURI The base URI to resolve any possible relative URIs against
* @return The parsed query
* @throws MalformedQueryException If the query was in any way malformed
*/
@SuppressWarnings("WeakerAccess")
public final ParsedQuery parseQuery(ASTQueryContainer qc, String baseURI) throws MalformedQueryException {
StringEscapesProcessor.process(qc);
BaseDeclProcessor.process(qc, baseURI);
Map<String, String> prefixes = StandardizingPrefixDeclProcessor.process(qc);
WildcardProjectionProcessor.process(qc);
BlankNodeVarProcessor.process(qc);
if (qc.containsQuery()) {
// handle query operation
TupleExpr tupleExpr = buildQueryModel(qc);
ParsedQuery query;
ASTQuery queryNode = qc.getQuery();
if (queryNode instanceof ASTSelectQuery) {
query = new ParsedTupleQuery(qc.getSourceString(), tupleExpr);
} else if (queryNode instanceof ASTConstructQuery) {
query = new ParsedGraphQuery(qc.getSourceString(), tupleExpr, prefixes);
} else if (queryNode instanceof ASTAskQuery) {
query = new ParsedBooleanQuery(qc.getSourceString(), tupleExpr);
} else if (queryNode instanceof ASTDescribeQuery) {
query = new ParsedGraphQuery(qc.getSourceString(), tupleExpr, prefixes);
} else {
throw new RuntimeException("Unexpected query type: " + queryNode.getClass());
}
// Handle dataset declaration
Dataset dataset = DatasetDeclProcessor.process(qc);
if (dataset != null) {
query.setDataset(dataset);
}
return query;
} else {
throw new IncompatibleOperationException("supplied string is not a query operation");
}
}
use of org.openrdf.query.parser.ParsedTupleQuery in project incubator-rya by apache.
the class RdfController method queryRdf.
@RequestMapping(value = "/queryrdf", method = { RequestMethod.GET, RequestMethod.POST })
public void queryRdf(@RequestParam("query") final String query, @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, required = false) String auth, @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_CV, required = false) final String vis, @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_INFER, required = false) final String infer, @RequestParam(value = "nullout", required = false) final String nullout, @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_RESULT_FORMAT, required = false) final String emit, @RequestParam(value = "padding", required = false) final String padding, @RequestParam(value = "callback", required = false) final String callback, final HttpServletRequest request, final HttpServletResponse response) {
// WARNING: if you add to the above request variables,
// Be sure to validate and encode since they come from the outside and could contain odd damaging character sequences.
SailRepositoryConnection conn = null;
final Thread queryThread = Thread.currentThread();
auth = StringUtils.arrayToCommaDelimitedString(provider.getUserAuths(request));
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
log.debug("interrupting");
queryThread.interrupt();
}
}, QUERY_TIME_OUT_SECONDS * 1000);
try {
final ServletOutputStream os = response.getOutputStream();
conn = repository.getConnection();
final Boolean isBlankQuery = StringUtils.isEmpty(query);
final ParsedOperation operation = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, query, null);
final Boolean requestedCallback = !StringUtils.isEmpty(callback);
final Boolean requestedFormat = !StringUtils.isEmpty(emit);
if (!isBlankQuery) {
if (operation instanceof ParsedGraphQuery) {
// Perform Graph Query
final RDFHandler handler = new RDFXMLWriter(os);
response.setContentType("text/xml");
performGraphQuery(query, conn, auth, infer, nullout, handler);
} else if (operation instanceof ParsedTupleQuery) {
// Perform Tuple Query
TupleQueryResultHandler handler;
if (requestedFormat && emit.equalsIgnoreCase("json")) {
handler = new SPARQLResultsJSONWriter(os);
response.setContentType("application/json");
} else {
handler = new SPARQLResultsXMLWriter(os);
response.setContentType("text/xml");
}
performQuery(query, conn, auth, infer, nullout, handler);
} else if (operation instanceof ParsedUpdate) {
// Perform Update Query
performUpdate(query, conn, os, infer, vis);
} else {
throw new MalformedQueryException("Cannot process query. Query type not supported.");
}
}
if (requestedCallback) {
os.print(")");
}
} catch (final Exception e) {
log.error("Error running query", e);
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (final RepositoryException e) {
log.error("Error closing connection", e);
}
}
}
timer.cancel();
}
use of org.openrdf.query.parser.ParsedTupleQuery in project incubator-rya by apache.
the class QueryRuleset method setRules.
/**
* Extract the rules from the query string, applying inference rules if configured to.
* @throws QueryRulesetException if the parsed query can't be parsed and translated into valid rules.
*/
private void setRules() throws QueryRulesetException {
final ParsedTupleQuery ptq;
final TupleExpr te;
try {
ptq = QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, query, null);
} catch (UnsupportedQueryLanguageException | MalformedQueryException e) {
throw new QueryRulesetException("Error parsing query:\n" + query, e);
}
te = ptq.getTupleExpr();
// Before converting to rules (and renaming variables), validate that no statement patterns
// consist of only variables (this would result in a rule that matches every triple).
// Needs to be done before inference, since inference rules may create such statement patterns
// that are OK because they won'd be converted to rules directly.
te.visit(new QueryModelVisitorBase<QueryRulesetException>() {
@Override
public void meet(final StatementPattern node) throws QueryRulesetException {
if (!(node.getSubjectVar().hasValue() || node.getPredicateVar().hasValue() || node.getObjectVar().hasValue())) {
throw new QueryRulesetException("Statement pattern with no constants would match every statement:\n" + node + "\nFrom parsed query:\n" + te);
}
}
});
// Apply inference, if applicable
if (conf != null && conf.isInfer()) {
RdfCloudTripleStore store = null;
try {
log.info("Applying inference rules");
store = (RdfCloudTripleStore) RyaSailFactory.getInstance(conf);
final InferenceEngine inferenceEngine = store.getInferenceEngine();
// Apply in same order as query evaluation:
te.visit(new TransitivePropertyVisitor(conf, inferenceEngine));
te.visit(new SymmetricPropertyVisitor(conf, inferenceEngine));
te.visit(new InverseOfVisitor(conf, inferenceEngine));
te.visit(new SubPropertyOfVisitor(conf, inferenceEngine));
te.visit(new SubClassOfVisitor(conf, inferenceEngine));
te.visit(new SameAsVisitor(conf, inferenceEngine));
log.info("Query after inference:\n");
for (final String line : te.toString().split("\n")) {
log.info("\t" + line);
}
} catch (final Exception e) {
throw new QueryRulesetException("Error applying inference to parsed query:\n" + te, e);
} finally {
if (store != null) {
try {
store.shutDown();
} catch (final SailException e) {
log.error("Error shutting down Sail after applying inference", e);
}
}
}
}
// Extract the StatementPatterns and Filters and turn them into rules:
final RulesetVisitor rv = new RulesetVisitor();
try {
te.visit(rv);
rv.addSchema();
} catch (final QueryRulesetException e) {
throw new QueryRulesetException("Error extracting rules from parsed query:\n" + te, e);
}
for (final CopyRule candidateRule : rv.rules) {
boolean unique = true;
for (final CopyRule otherRule : rv.rules) {
if (!candidateRule.equals(otherRule) && otherRule.isGeneralizationOf(candidateRule)) {
unique = false;
break;
}
}
if (unique) {
rules.add(candidateRule);
}
}
}
use of org.openrdf.query.parser.ParsedTupleQuery in project incubator-rya by apache.
the class FilterSerializer method serialize.
/**
* Converts a {@link Filter} to a SPARQL query containing only the SPARQL representation
* of the Filter along with a Select clause that return all variables. The argument of the
* Filter is replaced by a {@link SingletonSet} so that the body of the SPARQL query consists of only a
* single Filter clause.
* @param filter - Filter to be serialized
* @return - SPARQL String containing a single Filter clause that represents the serialized Filter
* @throws FilterParseException
*/
public static String serialize(Filter filter) throws FilterParseException {
Filter clone = filter.clone();
clone.setArg(new SingletonSet());
try {
return removeAngularBracketsFromNonUriFunctions(renderer.render(new ParsedTupleQuery(clone)));
} catch (Exception e) {
throw new FilterParseException("Unable to parse Filter.", e);
}
}
use of org.openrdf.query.parser.ParsedTupleQuery in project backstage by zepheira.
the class Expression method computeOutputOnValue.
public ExpressionQueryResult computeOutputOnValue(Value value, Database database, SailRepositoryConnection connection) throws ExpressionException {
TupleQueryBuilder builder = new TupleQueryBuilder();
Var valueVar = builder.makeVar("value", value);
ExpressionResult expressionResult = computeOutputOnItem(database, builder, valueVar);
if (expressionResult.valueExpr instanceof Var) {
Var resultVar = (Var) expressionResult.valueExpr;
ProjectionElemList projectionElements = new ProjectionElemList();
projectionElements.addElement(new ProjectionElem(resultVar.getName()));
TupleExpr t = builder.makeFilterTupleExpr();
if (t == null) {
// TODO[dfhuynh]: This happens if the expression is just "value". I'm not sure what to do here.
return null;
}
Projection projection = new Projection(t, projectionElements);
TupleQuery query = new MyTupleQuery(new ParsedTupleQuery(projection), connection);
return new ExpressionQueryResult(query, expressionResult.valueType, resultVar);
}
return null;
}
Aggregations