Search in sources :

Example 1 with ParsedTupleQuery

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");
    }
}
Also used : IncompatibleOperationException(org.openrdf.query.IncompatibleOperationException) ParsedQuery(org.openrdf.query.parser.ParsedQuery) Dataset(org.openrdf.query.Dataset) ParsedGraphQuery(org.openrdf.query.parser.ParsedGraphQuery) TupleExpr(org.openrdf.query.algebra.TupleExpr) ParsedBooleanQuery(org.openrdf.query.parser.ParsedBooleanQuery) ParsedTupleQuery(org.openrdf.query.parser.ParsedTupleQuery)

Example 2 with ParsedTupleQuery

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();
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ParsedGraphQuery(org.openrdf.query.parser.ParsedGraphQuery) RepositoryException(org.openrdf.repository.RepositoryException) SailRepositoryConnection(org.openrdf.repository.sail.SailRepositoryConnection) SPARQLResultsJSONWriter(org.openrdf.query.resultio.sparqljson.SPARQLResultsJSONWriter) ParsedOperation(org.openrdf.query.parser.ParsedOperation) QueryResultHandlerException(org.openrdf.query.QueryResultHandlerException) RepositoryException(org.openrdf.repository.RepositoryException) TupleQueryResultHandlerException(org.openrdf.query.TupleQueryResultHandlerException) RDFParseException(org.openrdf.rio.RDFParseException) QueryEvaluationException(org.openrdf.query.QueryEvaluationException) UpdateExecutionException(org.openrdf.query.UpdateExecutionException) MalformedQueryException(org.openrdf.query.MalformedQueryException) RDFHandlerException(org.openrdf.rio.RDFHandlerException) IOException(java.io.IOException) SPARQLResultsXMLWriter(org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLWriter) ParsedUpdate(org.openrdf.query.parser.ParsedUpdate) Timer(java.util.Timer) TimerTask(java.util.TimerTask) RDFXMLWriter(org.openrdf.rio.rdfxml.RDFXMLWriter) MalformedQueryException(org.openrdf.query.MalformedQueryException) TupleQueryResultHandler(org.openrdf.query.TupleQueryResultHandler) RDFHandler(org.openrdf.rio.RDFHandler) ParsedTupleQuery(org.openrdf.query.parser.ParsedTupleQuery) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with ParsedTupleQuery

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);
        }
    }
}
Also used : SameAsVisitor(org.apache.rya.rdftriplestore.inference.SameAsVisitor) RdfCloudTripleStore(org.apache.rya.rdftriplestore.RdfCloudTripleStore) SymmetricPropertyVisitor(org.apache.rya.rdftriplestore.inference.SymmetricPropertyVisitor) SubClassOfVisitor(org.apache.rya.rdftriplestore.inference.SubClassOfVisitor) SubPropertyOfVisitor(org.apache.rya.rdftriplestore.inference.SubPropertyOfVisitor) SailException(org.openrdf.sail.SailException) TupleExpr(org.openrdf.query.algebra.TupleExpr) SailException(org.openrdf.sail.SailException) UnsupportedQueryLanguageException(org.openrdf.query.UnsupportedQueryLanguageException) QueryRulesetException(org.apache.rya.accumulo.mr.merge.util.QueryRuleset.QueryRulesetException) MalformedQueryException(org.openrdf.query.MalformedQueryException) IOException(java.io.IOException) FixedStatementPattern(org.apache.rya.rdftriplestore.utils.FixedStatementPattern) StatementPattern(org.openrdf.query.algebra.StatementPattern) InferenceEngine(org.apache.rya.rdftriplestore.inference.InferenceEngine) MalformedQueryException(org.openrdf.query.MalformedQueryException) TransitivePropertyVisitor(org.apache.rya.rdftriplestore.inference.TransitivePropertyVisitor) InverseOfVisitor(org.apache.rya.rdftriplestore.inference.InverseOfVisitor) QueryRulesetException(org.apache.rya.accumulo.mr.merge.util.QueryRuleset.QueryRulesetException) UnsupportedQueryLanguageException(org.openrdf.query.UnsupportedQueryLanguageException) ParsedTupleQuery(org.openrdf.query.parser.ParsedTupleQuery)

Example 4 with ParsedTupleQuery

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);
    }
}
Also used : SingletonSet(org.openrdf.query.algebra.SingletonSet) Filter(org.openrdf.query.algebra.Filter) ParsedTupleQuery(org.openrdf.query.parser.ParsedTupleQuery)

Example 5 with ParsedTupleQuery

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;
}
Also used : ProjectionElemList(org.openrdf.query.algebra.ProjectionElemList) Var(org.openrdf.query.algebra.Var) Projection(org.openrdf.query.algebra.Projection) TupleQueryBuilder(edu.mit.simile.backstage.model.TupleQueryBuilder) ParsedTupleQuery(org.openrdf.query.parser.ParsedTupleQuery) MyTupleQuery(edu.mit.simile.backstage.util.MyTupleQuery) TupleQuery(org.openrdf.query.TupleQuery) MyTupleQuery(edu.mit.simile.backstage.util.MyTupleQuery) ProjectionElem(org.openrdf.query.algebra.ProjectionElem) TupleExpr(org.openrdf.query.algebra.TupleExpr) ParsedTupleQuery(org.openrdf.query.parser.ParsedTupleQuery)

Aggregations

ParsedTupleQuery (org.openrdf.query.parser.ParsedTupleQuery)5 TupleExpr (org.openrdf.query.algebra.TupleExpr)3 IOException (java.io.IOException)2 MalformedQueryException (org.openrdf.query.MalformedQueryException)2 ParsedGraphQuery (org.openrdf.query.parser.ParsedGraphQuery)2 TupleQueryBuilder (edu.mit.simile.backstage.model.TupleQueryBuilder)1 MyTupleQuery (edu.mit.simile.backstage.util.MyTupleQuery)1 Timer (java.util.Timer)1 TimerTask (java.util.TimerTask)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 QueryRulesetException (org.apache.rya.accumulo.mr.merge.util.QueryRuleset.QueryRulesetException)1 RdfCloudTripleStore (org.apache.rya.rdftriplestore.RdfCloudTripleStore)1 InferenceEngine (org.apache.rya.rdftriplestore.inference.InferenceEngine)1 InverseOfVisitor (org.apache.rya.rdftriplestore.inference.InverseOfVisitor)1 SameAsVisitor (org.apache.rya.rdftriplestore.inference.SameAsVisitor)1 SubClassOfVisitor (org.apache.rya.rdftriplestore.inference.SubClassOfVisitor)1 SubPropertyOfVisitor (org.apache.rya.rdftriplestore.inference.SubPropertyOfVisitor)1 SymmetricPropertyVisitor (org.apache.rya.rdftriplestore.inference.SymmetricPropertyVisitor)1 TransitivePropertyVisitor (org.apache.rya.rdftriplestore.inference.TransitivePropertyVisitor)1 FixedStatementPattern (org.apache.rya.rdftriplestore.utils.FixedStatementPattern)1