use of org.kie.api.runtime.rule.ViewChangedEventListener in project drools by kiegroup.
the class IndexingTest method testFullFastIteratorResume.
@Test(timeout = 10000)
public void testFullFastIteratorResume() throws Exception {
String str = "";
str += "package org.drools.compiler.test \n";
str += "import org.drools.compiler.Person \n";
str += "query peeps( String $name, int $age ) \n";
str += " not $p2 : Person( $name := name, age > $age ) \n";
str += "end\n";
KieBase kbase = loadKnowledgeBaseFromString(str);
List<ObjectTypeNode> nodes = ((KnowledgeBaseImpl) kbase).getRete().getObjectTypeNodes();
ObjectTypeNode node = null;
for (ObjectTypeNode n : nodes) {
if (((ClassObjectType) n.getObjectType()).getClassType() == DroolsQuery.class) {
node = n;
break;
}
}
StatefulKnowledgeSessionImpl wm = ((StatefulKnowledgeSessionImpl) kbase.newKieSession());
AlphaNode alphanode = (AlphaNode) node.getObjectSinkPropagator().getSinks()[0];
LeftInputAdapterNode liaNode = (LeftInputAdapterNode) alphanode.getObjectSinkPropagator().getSinks()[0];
NotNode n = (NotNode) liaNode.getSinkPropagator().getSinks()[0];
DoubleNonIndexSkipBetaConstraints c = (DoubleNonIndexSkipBetaConstraints) n.getRawConstraints();
// assertEquals( "$name", ((VariableConstraint)c.getConstraint()).getRequiredDeclarations()[0].getIdentifier() );
assertTrue(c.isIndexed());
BetaMemory bm = (BetaMemory) wm.getNodeMemory(n);
System.out.println(bm.getLeftTupleMemory().getClass());
System.out.println(bm.getRightTupleMemory().getClass());
assertTrue(bm.getLeftTupleMemory() instanceof TupleIndexHashTable);
assertTrue(bm.getRightTupleMemory() instanceof TupleIndexHashTable);
final Map<String, Integer> map = new HashMap<String, Integer>();
map.put("inserted", new Integer(0));
map.put("deleted", new Integer(0));
map.put("updated", new Integer(0));
wm.openLiveQuery("peeps", new Object[] { Variable.v, 99 }, new ViewChangedEventListener() {
@Override
public void rowInserted(Row row) {
}
@Override
public void rowDeleted(Row row) {
}
@Override
public void rowUpdated(Row row) {
}
});
Map<String, InternalFactHandle> peeps = new HashMap<String, InternalFactHandle>();
Person p = new Person("x0", 100);
InternalFactHandle fh = (InternalFactHandle) wm.insert(p);
peeps.put(p.getName(), fh);
for (int i = 1; i < 100; i++) {
p = new Person("x" + i, 101);
fh = (InternalFactHandle) wm.insert(p);
wm.fireAllRules();
peeps.put(p.getName(), fh);
}
List<RightTuple> list = new ArrayList<RightTuple>(100);
FastIterator it = n.getRightIterator(bm.getRightTupleMemory());
for (RightTuple rt = n.getFirstRightTuple(null, bm.getRightTupleMemory(), null, it); rt != null; rt = (RightTuple) it.next(rt)) {
list.add(rt);
}
assertEquals(100, list.size());
// check we can resume from each entry in the list above.
for (int i = 0; i < 100; i++) {
RightTuple rightTuple = list.get(i);
// resumes from the current rightTuple
it = n.getRightIterator(bm.getRightTupleMemory(), rightTuple);
int j = i + 1;
for (RightTuple rt = (RightTuple) it.next(rightTuple); rt != null; rt = (RightTuple) it.next(rt)) {
assertSame(list.get(j), rt);
j++;
}
}
}
use of org.kie.api.runtime.rule.ViewChangedEventListener in project drools by kiegroup.
the class LiveQueriesBadResultTest method testAccessToNotExistingVariable.
@Test
public void testAccessToNotExistingVariable() {
ViewChangedEventListener listener = new ViewChangedEventListener() {
@Override
public void rowUpdated(Row row) {
updated.add(row.get("bad"));
}
@Override
public void rowInserted(Row row) {
inserted.add(row.get("bad"));
}
@Override
public void rowDeleted(Row row) {
deleted.add(row.get("bad"));
}
};
final KieBase kieBase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "query.drl");
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Petr", 25));
Assertions.assertThatThrownBy(() -> ksession.openLiveQuery("simple query with no parameters", new Object[] { "Petr", 26 }, listener)).isInstanceOf(RuntimeException.class).hasMessage("The identifier 'bad' does not exist as a bound variable for this query");
}
use of org.kie.api.runtime.rule.ViewChangedEventListener in project drools by kiegroup.
the class IndexingTest method testIndexingOnQueryUnificationWithNot.
@Test(timeout = 10000)
public void testIndexingOnQueryUnificationWithNot() throws Exception {
String str = "";
str += "package org.drools.compiler.test \n";
str += "import org.drools.compiler.Person \n";
str += "query peeps( String $name, int $age ) \n";
str += " not $p2 : Person( $name := name, age > $age ) \n";
str += "end\n";
KieBase kbase = loadKnowledgeBaseFromString(str);
List<ObjectTypeNode> nodes = ((KnowledgeBaseImpl) kbase).getRete().getObjectTypeNodes();
ObjectTypeNode node = null;
for (ObjectTypeNode n : nodes) {
if (((ClassObjectType) n.getObjectType()).getClassType() == DroolsQuery.class) {
node = n;
break;
}
}
StatefulKnowledgeSessionImpl wm = ((StatefulKnowledgeSessionImpl) kbase.newKieSession());
AlphaNode alphanode = (AlphaNode) node.getObjectSinkPropagator().getSinks()[0];
LeftInputAdapterNode liaNode = (LeftInputAdapterNode) alphanode.getObjectSinkPropagator().getSinks()[0];
NotNode n = (NotNode) liaNode.getSinkPropagator().getSinks()[0];
DoubleNonIndexSkipBetaConstraints c = (DoubleNonIndexSkipBetaConstraints) n.getRawConstraints();
// assertEquals( "$name", ((VariableConstraint)c.getConstraint()).getRequiredDeclarations()[0].getIdentifier() );
assertTrue(c.isIndexed());
BetaMemory bm = (BetaMemory) wm.getNodeMemory(n);
System.out.println(bm.getLeftTupleMemory().getClass());
System.out.println(bm.getRightTupleMemory().getClass());
assertTrue(bm.getLeftTupleMemory() instanceof TupleIndexHashTable);
assertTrue(bm.getRightTupleMemory() instanceof TupleIndexHashTable);
final Map<String, Integer> map = new HashMap<String, Integer>();
map.put("inserted", new Integer(0));
map.put("deleted", new Integer(0));
map.put("updated", new Integer(0));
wm.openLiveQuery("peeps", new Object[] { Variable.v, 99 }, new ViewChangedEventListener() {
@Override
public void rowInserted(Row row) {
System.out.println("inserted");
Integer integer = map.get("inserted");
map.put("inserted", integer.intValue() + 1);
}
@Override
public void rowDeleted(Row row) {
System.out.println("deleted");
Integer integer = map.get("deleted");
map.put("deleted", integer.intValue() + 1);
}
@Override
public void rowUpdated(Row row) {
System.out.println("updated");
Integer integer = map.get("updated");
map.put("updated", integer.intValue() + 1);
}
});
System.out.println("inserted: " + map.get("inserted"));
System.out.println("deleted: " + map.get("deleted"));
System.out.println("updated: " + map.get("updated"));
Map<String, InternalFactHandle> peeps = new HashMap<String, InternalFactHandle>();
Person p = null;
InternalFactHandle fh = null;
int max = 3;
// 1 matched, prior to any insertions
assertEquals(1, map.get("inserted").intValue());
assertEquals(0, map.get("deleted").intValue());
assertEquals(0, map.get("updated").intValue());
// x0 is the blocker
for (int i = 0; i < max; i++) {
p = new Person("x" + i, 100);
fh = (InternalFactHandle) wm.insert(p);
wm.fireAllRules();
peeps.put(p.getName(), fh);
}
// insertions case 1 deletion
assertEquals(1, map.get("inserted").intValue());
assertEquals(1, map.get("deleted").intValue());
assertEquals(0, map.get("updated").intValue());
// each x is blocker in turn up to x99
for (int i = 0; i < (max - 1); i++) {
fh = peeps.get("x" + i);
p = (Person) fh.getObject();
p.setAge(90);
wm.update(fh, p);
wm.fireAllRules();
// make sure this doesn't change
assertEquals("i=" + i, 1, map.get("inserted").intValue());
}
// no change
assertEquals(1, map.get("inserted").intValue());
assertEquals(1, map.get("deleted").intValue());
assertEquals(0, map.get("updated").intValue());
// x99 is still the blocker, everything else is just added
for (int i = 0; i < (max - 1); i++) {
fh = peeps.get("x" + i);
p = (Person) fh.getObject();
p.setAge(102);
wm.update(fh, p);
wm.fireAllRules();
// make sure this doesn't change
assertEquals("i=" + i, 1, map.get("inserted").intValue());
}
// no change
assertEquals(1, map.get("inserted").intValue());
assertEquals(1, map.get("deleted").intValue());
assertEquals(0, map.get("updated").intValue());
// x99 is still the blocker
for (int i = (max - 2); i >= 0; i--) {
fh = peeps.get("x" + i);
p = (Person) fh.getObject();
p.setAge(90);
wm.update(fh, p);
wm.fireAllRules();
// make sure this doesn't change
assertEquals("i=" + i, 1, map.get("inserted").intValue());
}
// move x99, should no longer be a blocker, now it can increase
fh = peeps.get("x" + (max - 1));
p = (Person) fh.getObject();
p.setAge(90);
wm.update(fh, p);
wm.fireAllRules();
assertEquals(2, map.get("inserted").intValue());
}
use of org.kie.api.runtime.rule.ViewChangedEventListener in project drools by kiegroup.
the class BackwardChainingTest method testSubNetworksAndQueries.
@Test(timeout = 10000)
public void testSubNetworksAndQueries() throws Exception {
String str = "" + "package org.drools.compiler.test \n" + "import java.util.List\n" + "import java.util.ArrayList\n" + "import java.util.Map\n" + "import java.util.HashMap\n" + "global List list\n" + "dialect \"mvel\"\n" + "\n" + "declare Location\n" + " thing : String \n" + " location : String \n" + "end" + "\n" + "declare Edible\n" + " thing : String\n" + "end" + "\n" + "query whereFood( String x, String y ) \n" + " Location(x, y;) Edible(x;) \n" + "end\n" + "\n" + "query look(String place, List food ) \n" + " $s : String() // just here to give a OTN lookup point\n" + " food := List() from accumulate( whereFood(thing, place;) ," + " collectList( thing ) )\n" + " exists( whereFood(thing, place;) )\n" + " not( whereFood(thing, place;) and\n " + " String( this == $s ) from thing )\n" + "end\n" + "\n" + "rule init when\n" + "then\n" + " \n" + " insert( new Location(\"apple\", \"kitchen\") );\n" + " insert( new Location(\"crackers\", \"kitchen\") );\n" + " insert( new Location(\"broccoli\", \"kitchen\") );\n" + " insert( new Location(\"computer\", \"office\") );\n" + " insert( new Edible(\"apple\") );\n" + " insert( new Edible(\"crackers\") );\n" + "end\n" + "";
logger.debug(str);
KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBaseFromString(str));
// Get the accumulate node, so we can test it's memory later
// now check beta memory was correctly cleared
List<ObjectTypeNode> nodes = ((KnowledgeBaseImpl) kbase).getRete().getObjectTypeNodes();
ObjectTypeNode node = null;
for (ObjectTypeNode n : nodes) {
if (((ClassObjectType) n.getObjectType()).getClassType() == String.class) {
node = n;
break;
}
}
BetaNode stringBetaNode = (BetaNode) node.getObjectSinkPropagator().getSinks()[0];
QueryElementNode queryElementNode1 = (QueryElementNode) stringBetaNode.getSinkPropagator().getSinks()[0];
RightInputAdapterNode riaNode1 = (RightInputAdapterNode) queryElementNode1.getSinkPropagator().getSinks()[0];
AccumulateNode accNode = (AccumulateNode) riaNode1.getObjectSinkPropagator().getSinks()[0];
QueryElementNode queryElementNode2 = (QueryElementNode) accNode.getSinkPropagator().getSinks()[0];
RightInputAdapterNode riaNode2 = (RightInputAdapterNode) queryElementNode2.getSinkPropagator().getSinks()[0];
ExistsNode existsNode = (ExistsNode) riaNode2.getObjectSinkPropagator().getSinks()[0];
QueryElementNode queryElementNode3 = (QueryElementNode) existsNode.getSinkPropagator().getSinks()[0];
FromNode fromNode = (FromNode) queryElementNode3.getSinkPropagator().getSinks()[0];
RightInputAdapterNode riaNode3 = (RightInputAdapterNode) fromNode.getSinkPropagator().getSinks()[0];
NotNode notNode = (NotNode) riaNode3.getObjectSinkPropagator().getSinks()[0];
KieSession ksession = createKnowledgeSession(kbase);
InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl) ksession);
AccumulateMemory accMemory = (AccumulateMemory) wm.getNodeMemory(accNode);
BetaMemory existsMemory = (BetaMemory) wm.getNodeMemory(existsNode);
FromMemory fromMemory = (FromMemory) wm.getNodeMemory(fromNode);
BetaMemory notMemory = (BetaMemory) wm.getNodeMemory(notNode);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
ksession.setGlobal("list", list);
FactHandle fh = ksession.insert("bread");
ksession.fireAllRules();
final List food = new ArrayList();
QueryResults results = null;
// Execute normal query and check no subnetwork tuples are left behind
results = ksession.getQueryResults("look", new Object[] { "kitchen", Variable.v });
assertEquals(1, results.size());
for (org.kie.api.runtime.rule.QueryResultsRow row : results) {
food.addAll((Collection) row.get("food"));
logger.debug(row.get("food").toString());
}
assertEquals(2, food.size());
assertContains(new String[] { "crackers", "apple" }, food);
assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(0, existsMemory.getRightTupleMemory().size());
assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
// Now execute an open query and ensure the memory is left populated
food.clear();
final List foodUpdated = new ArrayList();
LiveQuery query = ksession.openLiveQuery("look", new Object[] { "kitchen", Variable.v }, new ViewChangedEventListener() {
public void rowUpdated(Row row) {
foodUpdated.addAll((Collection) row.get("food"));
}
public void rowDeleted(Row row) {
}
public void rowInserted(Row row) {
food.addAll((Collection) row.get("food"));
}
});
assertEquals(2, food.size());
assertContains(new String[] { "crackers", "apple" }, food);
assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(2, existsMemory.getRightTupleMemory().size());
assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
food.clear();
// Now try again, make sure it only delete's it's own tuples
results = ksession.getQueryResults("look", new Object[] { "kitchen", Variable.v });
assertEquals(1, results.size());
for (org.kie.api.runtime.rule.QueryResultsRow row : results) {
food.addAll((Collection) row.get("food"));
logger.debug(row.get("food").toString());
}
assertEquals(2, food.size());
assertContains(new String[] { "crackers", "apple" }, food);
assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(2, existsMemory.getRightTupleMemory().size());
assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
food.clear();
// do an update and check it's still memory size 2
// however this time the food should be empty, as 'crackers' now blocks the not.
ksession.update(fh, "crackers");
ksession.fireAllRules();
assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(2, existsMemory.getRightTupleMemory().size());
assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(1, notMemory.getRightTupleMemory().size());
assertEquals(0, foodUpdated.size());
// do an update and check it's still memory size 2
// this time
ksession.update(fh, "oranges");
ksession.fireAllRules();
assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(2, existsMemory.getRightTupleMemory().size());
assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
assertEquals(2, food.size());
assertContains(new String[] { "crackers", "apple" }, food);
// Close the open
query.close();
assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
assertEquals(0, existsMemory.getRightTupleMemory().size());
assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
assertEquals(0, notMemory.getRightTupleMemory().size());
}
use of org.kie.api.runtime.rule.ViewChangedEventListener in project drools by kiegroup.
the class LiveQueriesBadResultTest method testOfBadParameters.
@Ignore("TODO - check correct exception in this test when DROOLS-2187 is fixed.")
@Test
public void testOfBadParameters() {
ViewChangedEventListener listener = new ViewChangedEventListener() {
@Override
public void rowUpdated(Row row) {
updated.add(row.get("person"));
}
@Override
public void rowInserted(Row row) {
inserted.add(row.get("person"));
}
@Override
public void rowDeleted(Row row) {
deleted.add(row.get("person"));
}
};
final KieBase kieBase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "query.drl");
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Petr", 25));
ksession.openLiveQuery("queryWithParamWithoutType", (Object[]) null, listener);
}
Aggregations