Search in sources :

Example 6 with ParsedGraphQuery

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

the class SailExecutionStrategy method executeConstructRule.

/**
 * Executes a CONSTRUCT query through the SAIL and inserts the results into
 * the DAO.
 * @param rule A construct query; not null.
 * @param metadata Metadata to add to any inferred triples; not null.
 * @return The number of inferred triples.
 * @throws ForwardChainException if query execution or data insert fails.
 */
@Override
public long executeConstructRule(AbstractConstructRule rule, StatementMetadata metadata) throws ForwardChainException {
    Preconditions.checkNotNull(rule);
    Preconditions.checkNotNull(metadata);
    if (!initialized) {
        initialize();
    }
    ParsedGraphQuery graphQuery = rule.getQuery();
    long statementsAdded = 0;
    logger.info("Applying inference rule " + rule + "...");
    for (String line : graphQuery.getTupleExpr().toString().split("\n")) {
        logger.debug("\t" + line);
    }
    InferredStatementHandler<?> handler = new InferredStatementHandler<>(dao, metadata);
    try {
        GraphQuery executableQuery = new SailGraphQuery(graphQuery, conn) {
        };
        executableQuery.evaluate(handler);
        statementsAdded = handler.getNumStatementsAdded();
        logger.info("Added " + statementsAdded + " inferred statements.");
        return statementsAdded;
    } catch (QueryEvaluationException e) {
        throw new ForwardChainException("Error evaluating query portion of construct rule", e);
    } catch (RDFHandlerException e) {
        throw new ForwardChainException("Error processing results of construct rule", e);
    }
}
Also used : QueryEvaluationException(org.openrdf.query.QueryEvaluationException) RDFHandlerException(org.openrdf.rio.RDFHandlerException) SailGraphQuery(org.openrdf.repository.sail.SailGraphQuery) ParsedGraphQuery(org.openrdf.query.parser.ParsedGraphQuery) ForwardChainException(org.apache.rya.forwardchain.ForwardChainException) ParsedGraphQuery(org.openrdf.query.parser.ParsedGraphQuery) GraphQuery(org.openrdf.query.GraphQuery) SailGraphQuery(org.openrdf.repository.sail.SailGraphQuery)

Example 7 with ParsedGraphQuery

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

the class SpinConstructRule method loadSpinRules.

/**
 * Load a set of SPIN rules from a data store.
 * @param conf Contains the connection information. Not null.
 * @return A map of rule identifiers to rule objects.
 * @throws ForwardChainException if connecting, querying for rules, or
 *  parsing rules fails.
 */
public static Ruleset loadSpinRules(RdfCloudTripleStoreConfiguration conf) throws ForwardChainException {
    Preconditions.checkNotNull(conf);
    Map<Resource, Rule> rules = new ConcurrentHashMap<>();
    // Connect to Rya
    SailRepository repository = null;
    SailRepositoryConnection conn = null;
    try {
        repository = new SailRepository(RyaSailFactory.getInstance(conf));
    } catch (Exception e) {
        throw new ForwardChainException("Couldn't initialize SAIL from configuration", e);
    }
    // Load and parse the individual SPIN rules from the data store
    String ruleQueryString = "SELECT ?type ?rule ?text WHERE {\n" + "  ?type <" + SPIN.RULE_PROPERTY.stringValue() + "> ?rule .\n" + "  {\n" + "    ?rule a <" + SP.CONSTRUCT_CLASS.stringValue() + "> .\n" + "    ?rule <" + SP.TEXT_PROPERTY.stringValue() + "> ?text .\n" + "  } UNION {\n" + "    ?rule a ?template .\n" + "    ?template <" + SPIN.BODY_PROPERTY + ">? ?body .\n" + "    ?body a <" + SP.CONSTRUCT_CLASS.stringValue() + "> .\n" + "    ?body <" + SP.TEXT_PROPERTY.stringValue() + "> ?text .\n" + "  }\n" + "}";
    SPARQLParser parser = new SPARQLParser();
    try {
        conn = repository.getConnection();
        TupleQuery ruleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, ruleQueryString);
        ruleQuery.evaluate(new TupleQueryResultHandlerBase() {

            @Override
            public void handleSolution(BindingSet bs) throws TupleQueryResultHandlerException {
                // For each rule identifier found, instantiate a SpinRule
                Value requiredType = bs.getValue("type");
                Value ruleIdentifier = bs.getValue("rule");
                Value ruleText = bs.getValue("text");
                if (requiredType instanceof Resource && ruleIdentifier instanceof Resource && ruleText instanceof Literal) {
                    ParsedQuery parsedRule;
                    try {
                        parsedRule = parser.parseQuery(ruleText.stringValue(), null);
                        if (parsedRule instanceof ParsedGraphQuery) {
                            SpinConstructRule rule = new SpinConstructRule((Resource) requiredType, (Resource) ruleIdentifier, (ParsedGraphQuery) parsedRule);
                            if (rule.hasAnonymousConsequent()) {
                                logger.error("Skipping unsupported rule " + ruleIdentifier + " -- consequent refers to bnode, which is not" + " currently supported (creating new bnodes at each" + " application could lead to infinite recursion).");
                            } else {
                                rules.put((Resource) ruleIdentifier, rule);
                            }
                        }
                    } catch (Exception e) {
                        throw new TupleQueryResultHandlerException(e);
                    }
                }
            }
        });
    } catch (TupleQueryResultHandlerException | QueryEvaluationException | MalformedQueryException | RepositoryException e) {
        throw new ForwardChainException("Couldn't retrieve SPIN rules", e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (RepositoryException e) {
                logger.warn("Error closing repository connection", e);
            }
        }
        if (repository.isInitialized()) {
            try {
                repository.shutDown();
            } catch (RepositoryException e) {
                logger.warn("Error shutting down repository", e);
            }
        }
    }
    return new Ruleset(rules.values());
}
Also used : TupleQueryResultHandlerBase(org.openrdf.query.TupleQueryResultHandlerBase) SailRepository(org.openrdf.repository.sail.SailRepository) ParsedQuery(org.openrdf.query.parser.ParsedQuery) TupleQuery(org.openrdf.query.TupleQuery) Literal(org.openrdf.model.Literal) MalformedQueryException(org.openrdf.query.MalformedQueryException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) BindingSet(org.openrdf.query.BindingSet) SPARQLParser(org.openrdf.query.parser.sparql.SPARQLParser) TupleQueryResultHandlerException(org.openrdf.query.TupleQueryResultHandlerException) ParsedGraphQuery(org.openrdf.query.parser.ParsedGraphQuery) Resource(org.openrdf.model.Resource) RepositoryException(org.openrdf.repository.RepositoryException) SailRepositoryConnection(org.openrdf.repository.sail.SailRepositoryConnection) RepositoryException(org.openrdf.repository.RepositoryException) QueryEvaluationException(org.openrdf.query.QueryEvaluationException) MalformedQueryException(org.openrdf.query.MalformedQueryException) TupleQueryResultHandlerException(org.openrdf.query.TupleQueryResultHandlerException) ForwardChainException(org.apache.rya.forwardchain.ForwardChainException) QueryEvaluationException(org.openrdf.query.QueryEvaluationException) Value(org.openrdf.model.Value) ForwardChainException(org.apache.rya.forwardchain.ForwardChainException)

Example 8 with ParsedGraphQuery

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

the class SpinConstructRuleTest method testAnonymousConsequent.

@Test
public void testAnonymousConsequent() throws Exception {
    String text = "CONSTRUCT {\n" + "  ?x ?p2 _:something" + "} 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"))));
    Assert.assertEquals(expectedAntecedents, HashMultiset.create(rule.getAntecedentPatterns()));
    // should have detected anonymous node
    Assert.assertTrue(rule.hasAnonymousConsequent());
    Var anonymousObject = new Var("object");
    anonymousObject.setAnonymous(true);
    Multiset<StatementPattern> expectedConsequents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("subject"), new Var("predicate"), anonymousObject)));
    Assert.assertEquals(expectedConsequents, HashMultiset.create(rule.getConsequentPatterns()));
    // Pattern matches should be unaffected by anonymous node status
    Assert.assertTrue(rule.canConclude(new StatementPattern(new Var("a"), new Var("b"), new Var("c"))));
    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)

Example 9 with ParsedGraphQuery

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

the class SpinConstructRuleTest method testThisUnbound.

@Test
public void testThisUnbound() throws Exception {
    String text = "CONSTRUCT {\n" + "  ?ind a ?superclass .\n" + "} WHERE {\n" + "  ?ind a ?subclass .\n" + "  ?subclass rdfs:subClassOf ?superclass .\n" + "}";
    ParsedGraphQuery query = (ParsedGraphQuery) PARSER.parseQuery(text, null);
    SpinConstructRule rule = new SpinConstructRule(OWL.THING, RL_CAX_SCO, query);
    Multiset<StatementPattern> expectedAntecedents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("subclass"), ac(RDFS.SUBCLASSOF), new Var("superclass")), new StatementPattern(new Var("ind"), ac(RDF.TYPE), new Var("subclass"))));
    Multiset<StatementPattern> expectedConsequents = HashMultiset.create(Arrays.asList(new StatementPattern(new Var("subject"), new Var("predicate", RDF.TYPE), 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("x"), c(RDF.TYPE), 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"))));
    // Narrower patterns match (constants in place of variables)
    Assert.assertTrue(rule.canConclude(new StatementPattern(c(RDF.TYPE), c(RDF.TYPE), c(RDF.TYPE))));
    // Incompatible patterns don't match (different constants)
    Assert.assertFalse(rule.canConclude(new StatementPattern(new Var("x"), c(RDFS.SUBCLASSOF), new Var("y"))));
}
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