Search in sources :

Example 1 with ParsedGraphQuery

use of org.openrdf.query.parser.ParsedGraphQuery 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 ParsedGraphQuery

use of org.openrdf.query.parser.ParsedGraphQuery 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 ParsedGraphQuery

use of org.openrdf.query.parser.ParsedGraphQuery in project incubator-rya by apache.

the class SpinConstructRuleTest method testMultipleConsequents.

@Test
public void testMultipleConsequents() throws Exception {
    String text = "CONSTRUCT {\n" + // bnodes due to an openrdf bug, resulting in incorrect matches
    "  ?this rdfs:subClassOf ?something .\n" + "  ?this owl:equivalentClass ?something .\n" + "  ?this rdfs:subClassOf owl:Thing .\n" + "  owl:Nothing rdfs:subClassOf ?this .\n" + "} WHERE { }";
    ParsedGraphQuery query = (ParsedGraphQuery) PARSER.parseQuery(text, null);
    SpinConstructRule rule = new SpinConstructRule(OWL.CLASS, RL_SCM_CLS, query);
    Multiset<StatementPattern> expectedAntecedents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("this"), c(RDF.TYPE), c(OWL.CLASS))));
    Multiset<StatementPattern> expectedConsequents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("subject"), new Var("predicate", RDFS.SUBCLASSOF), new Var("object")), new StatementPattern(new Var("subject"), new Var("predicate", OWL.EQUIVALENTCLASS), new Var("object")), new StatementPattern(new Var("subject"), new Var("predicate", RDFS.SUBCLASSOF), new Var("object", OWL.THING)), new StatementPattern(new Var("subject", OWL.NOTHING), new Var("predicate", RDFS.SUBCLASSOF), new Var("object"))));
    Assert.assertEquals(expectedAntecedents, HashMultiset.create(rule.getAntecedentPatterns()));
    Assert.assertEquals(expectedConsequents, HashMultiset.create(rule.getConsequentPatterns()));
    // Basic pattern matches
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), c(RDFS.SUBCLASSOF), new Var("y"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), c(OWL.EQUIVALENTCLASS), new Var("y"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), c(RDFS.SUBCLASSOF), c(OWL.THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), c(RDFS.SUBCLASSOF), new Var("y"))));
    // Broader patterns match (variables in place of constants)
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("a"), new Var("b"), new Var("c"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("a"), new Var("b"), c(OWL.THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), new Var("b"), new Var("c"))));
    // Narrower patterns match (constants in place of variables)
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(FOAF.PERSON), c(RDFS.SUBCLASSOF), new Var("x"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(FOAF.PERSON), c(OWL.EQUIVALENTCLASS), c(FOAF.PERSON))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), c(RDFS.SUBCLASSOF), c(FOAF.PERSON))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), c(OWL.EQUIVALENTCLASS), c(FOAF.PERSON))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), c(OWL.EQUIVALENTCLASS), c(OWL.THING))));
    // Incompatible patterns don't match (different constants)
    Assert.assertFalse(rule.canConclude(new StatementPattern(new Var("x"), c(RDFS.SUBPROPERTYOF), c(OWL.THING))));
}
Also used : StatementPattern(org.openrdf.query.algebra.StatementPattern) Var(org.openrdf.query.algebra.Var) ParsedGraphQuery(org.openrdf.query.parser.ParsedGraphQuery) Test(org.junit.Test)

Example 4 with ParsedGraphQuery

use of org.openrdf.query.parser.ParsedGraphQuery in project incubator-rya by apache.

the class SpinConstructRuleTest method testEmptyWhere.

@Test
public void testEmptyWhere() throws Exception {
    String text = "CONSTRUCT {\n" + "  ?this a <" + LIVING_THING.stringValue() + "> .\n" + "} WHERE { }";
    ParsedGraphQuery query = (ParsedGraphQuery) PARSER.parseQuery(text, null);
    SpinConstructRule rule = new SpinConstructRule(FOAF.PERSON, VF.createURI("urn:person-is-living"), query);
    Multiset<StatementPattern> expectedAntecedents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("this"), c(RDF.TYPE), c(FOAF.PERSON))));
    Multiset<StatementPattern> expectedConsequents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("subject"), new Var("predicate", RDF.TYPE), new Var("object", LIVING_THING))));
    Assert.assertEquals(expectedAntecedents, HashMultiset.create(rule.getAntecedentPatterns()));
    Assert.assertEquals(expectedConsequents, HashMultiset.create(rule.getConsequentPatterns()));
    Assert.assertFalse(rule.hasAnonymousConsequent());
    // Basic pattern matches
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), c(RDF.TYPE), c(LIVING_THING))));
    // Broader patterns match (variables in place of constants)
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), c(RDF.TYPE), new Var("y"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), new Var("y"), c(LIVING_THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("a"), new Var("b"), new Var("c"))));
    // Narrower patterns match (constants in place of variables)
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(RDF.TYPE), c(RDF.TYPE), c(LIVING_THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(FOAF.MBOX), c(RDF.TYPE), new Var("y"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(RDF.ALT), new Var("y"), c(LIVING_THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(RDF.BAG), new Var("b"), new Var("c"))));
    // Incompatible patterns don't match (different constants)
    Assert.assertFalse(rule.canConclude(new StatementPattern(new Var("x"), c(RDFS.SUBCLASSOF), new Var("y"))));
    Assert.assertFalse(rule.canConclude(new StatementPattern(new Var("x"), new Var("y"), c(FOAF.PERSON))));
    Assert.assertFalse(rule.canConclude(new StatementPattern(c(RDF.TYPE), c(RDF.TYPE), c(RDF.TYPE))));
}
Also used : StatementPattern(org.openrdf.query.algebra.StatementPattern) Var(org.openrdf.query.algebra.Var) ParsedGraphQuery(org.openrdf.query.parser.ParsedGraphQuery) Test(org.junit.Test)

Example 5 with ParsedGraphQuery

use of org.openrdf.query.parser.ParsedGraphQuery in project incubator-rya by apache.

the class SpinConstructRuleTest method testGeneralConsequent.

@Test
public void testGeneralConsequent() throws Exception {
    String text = "CONSTRUCT {\n" + "  ?x ?p2 ?y" + "} WHERE {\n" + "  ?x ?p1 ?y .\n" + "  ?p1 rdfs:subPropertyOf ?p2 .\n" + "}";
    ParsedGraphQuery query = (ParsedGraphQuery) PARSER.parseQuery(text, null);
    SpinConstructRule rule = new SpinConstructRule(OWL.THING, RL_PRP_SPO1, query);
    Multiset<StatementPattern> expectedAntecedents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("p1"), ac(RDFS.SUBPROPERTYOF), new Var("p2")), new StatementPattern(new Var("x"), new Var("p1"), new Var("y"))));
    Multiset<StatementPattern> expectedConsequents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("subject"), new Var("predicate"), new Var("object"))));
    Assert.assertEquals(expectedAntecedents, HashMultiset.create(rule.getAntecedentPatterns()));
    Assert.assertEquals(expectedConsequents, HashMultiset.create(rule.getConsequentPatterns()));
    Assert.assertFalse(rule.hasAnonymousConsequent());
    // Basic pattern matches
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("a"), new Var("b"), new Var("c"))));
    // Narrower patterns match (constants in place of variables)
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("x"), c(RDFS.SUBPROPERTYOF), c(OWL.THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), new Var("prop"), c(OWL.THING))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(FOAF.PERSON), c(RDFS.SUBCLASSOF), new Var("x"))));
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(OWL.NOTHING), c(RDFS.SUBCLASSOF), c(FOAF.PERSON))));
}
Also used : StatementPattern(org.openrdf.query.algebra.StatementPattern) Var(org.openrdf.query.algebra.Var) ParsedGraphQuery(org.openrdf.query.parser.ParsedGraphQuery) Test(org.junit.Test)

Aggregations

ParsedGraphQuery (org.openrdf.query.parser.ParsedGraphQuery)9 Test (org.junit.Test)5 StatementPattern (org.openrdf.query.algebra.StatementPattern)5 Var (org.openrdf.query.algebra.Var)5 QueryEvaluationException (org.openrdf.query.QueryEvaluationException)3 ForwardChainException (org.apache.rya.forwardchain.ForwardChainException)2 MalformedQueryException (org.openrdf.query.MalformedQueryException)2 TupleQueryResultHandlerException (org.openrdf.query.TupleQueryResultHandlerException)2 ParsedQuery (org.openrdf.query.parser.ParsedQuery)2 ParsedTupleQuery (org.openrdf.query.parser.ParsedTupleQuery)2 RepositoryException (org.openrdf.repository.RepositoryException)2 SailRepositoryConnection (org.openrdf.repository.sail.SailRepositoryConnection)2 RDFHandlerException (org.openrdf.rio.RDFHandlerException)2 IOException (java.io.IOException)1 Timer (java.util.Timer)1 TimerTask (java.util.TimerTask)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 Literal (org.openrdf.model.Literal)1 Resource (org.openrdf.model.Resource)1