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);
}
}
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());
}
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))));
}
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"))));
}
Aggregations