use of org.kie.api.runtime.rule.QueryResults in project drools by kiegroup.
the class AccumulateTest method testAccumulateWithVarsOutOfHashOrder.
@Test(timeout = 10000)
public void testAccumulateWithVarsOutOfHashOrder() throws Exception {
// JBRULES-3494
String rule = "package com.sample;\n" + "\n" + "import java.util.List;\n" + "\n" + "declare MessageHolder\n" + " id : String\n" + " msg: String\n" + "end\n" + "\n" + "query getResults( String $mId, List $holders )\n" + " accumulate( \n" + " $holder : MessageHolder( id == $mId, $ans : msg ),\n" + " $holders := collectList( $holder )\n" + " ) \n" + "end\n" + "\n" + "rule \"Init\"\n" + "when\n" + "then\n" + " insert( new MessageHolder( \"1\", \"x\" ) );\n" + "end\n";
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newReaderResource(new StringReader(rule)), ResourceType.DRL);
if (kbuilder.hasErrors()) {
fail(kbuilder.getErrors().toString());
}
final InternalKnowledgeBase kbase = (InternalKnowledgeBase) getKnowledgeBase();
KieSession ksession = createKnowledgeSession(kbase);
kbase.addPackages(loadKnowledgePackagesFromString(rule));
ksession.fireAllRules();
QueryResults res = ksession.getQueryResults("getResults", "1", Variable.v);
assertEquals(1, res.size());
Object o = res.iterator().next().get("$holders");
assertTrue(o instanceof List);
assertEquals(1, ((List) o).size());
}
use of org.kie.api.runtime.rule.QueryResults 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.QueryResults in project drools by kiegroup.
the class CepEspTest method testTemporalQuery.
@Test
public void testTemporalQuery() {
// BZ-967441
String drl = "package org.drools.compiler.integrationtests;\n" + "\n" + "import org.drools.compiler.integrationtests.CepEspTest.TestEvent;\n" + "\n" + "declare TestEvent\n" + " @role( event )\n" + "end\n" + "\n" + "query EventsBeforeNineSeconds\n" + " $event : TestEvent() from entry-point EStream\n" + " $result : TestEvent ( this after [0s, 9s] $event) from entry-point EventStream\n" + "end\n";
KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();
kfs.write("src/main/resources/querytest.drl", drl);
KieBuilder kbuilder = KieServices.Factory.get().newKieBuilder(kfs);
kbuilder.buildAll();
KieBase kbase = KieServices.Factory.get().newKieContainer(kbuilder.getKieModule().getReleaseId()).getKieBase();
KieSessionConfiguration ksconfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
ksconfig.setOption(ClockTypeOption.get("pseudo"));
KieSession ksession = kbase.newKieSession(ksconfig, null);
SessionPseudoClock clock = ksession.getSessionClock();
EntryPoint ePoint = ksession.getEntryPoint("EStream");
EntryPoint entryPoint = ksession.getEntryPoint("EventStream");
ePoint.insert(new TestEvent("zero"));
entryPoint.insert(new TestEvent("one"));
clock.advanceTime(10, TimeUnit.SECONDS);
entryPoint.insert(new TestEvent("two"));
clock.advanceTime(10, TimeUnit.SECONDS);
entryPoint.insert(new TestEvent("three"));
QueryResults results = ksession.getQueryResults("EventsBeforeNineSeconds");
assertEquals(1, results.size());
ksession.dispose();
}
use of org.kie.api.runtime.rule.QueryResults in project drools by kiegroup.
the class CepEspTest method AfterOperatorInCEPQueryTest.
@Test
public void AfterOperatorInCEPQueryTest() {
String drl = "package org.drools;\n" + "import org.drools.compiler.StockTick; \n" + "\n" + "declare StockTick\n" + " @role( event )\n" + "end\n" + "\n" + "query EventsBeforeNineSeconds\n" + " $event : StockTick() from entry-point EStream\n" + " $result : StockTick ( this after [0s, 9s] $event) from entry-point EventStream\n" + "end\n" + "\n" + "query EventsBeforeNineteenSeconds\n" + " $event : StockTick() from entry-point EStream\n" + " $result : StockTick ( this after [0s, 19s] $event) from entry-point EventStream\n" + "end\n" + "\n" + "query EventsBeforeHundredSeconds\n" + " $event : StockTick() from entry-point EStream\n" + " $result : StockTick ( this after [0s, 100s] $event) from entry-point EventStream\n" + "end\n";
final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
kbconf.setOption(EventProcessingOption.STREAM);
final KieBase kbase = loadKnowledgeBaseFromString(kbconf, drl);
KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
ksconf.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));
KieSession ksession = createKnowledgeSession(kbase, ksconf);
SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock();
EntryPoint ePoint = ksession.getEntryPoint("EStream");
EntryPoint entryPoint = ksession.getEntryPoint("EventStream");
ePoint.insert(new StockTick(0L, "zero", 0.0, 0));
entryPoint.insert(new StockTick(1L, "one", 0.0, 0));
clock.advanceTime(10, TimeUnit.SECONDS);
entryPoint.insert(new StockTick(2L, "two", 0.0, 0));
clock.advanceTime(10, TimeUnit.SECONDS);
entryPoint.insert(new StockTick(3L, "three", 0.0, 0));
QueryResults results = ksession.getQueryResults("EventsBeforeNineSeconds");
assertEquals(0, results.size());
results = ksession.getQueryResults("EventsBeforeNineteenSeconds");
assertEquals(0, results.size());
results = ksession.getQueryResults("EventsBeforeHundredSeconds");
assertEquals(1, results.size());
ksession.dispose();
}
use of org.kie.api.runtime.rule.QueryResults in project drools by kiegroup.
the class BackwardChainingTest method testOpenBackwardChain.
// (timeout = 10000)
@Test
public void testOpenBackwardChain() throws Exception {
// http://www.amzi.com/AdventureInProlog/advtop.php
String str = "" + "package org.drools.compiler.test \n" + "import java.util.List\n" + "import java.util.ArrayList\n" + "import org.drools.compiler.Person\n" + "global List list\n" + "dialect \"mvel\"\n" + "declare Location\n" + " thing : String \n" + " location : String \n" + "end" + "\n" + "query isContainedIn( String x, String y ) \n" + " Location(x, y;)\n" + " or \n" + " ( Location(z, y;) and isContainedIn(x, z;) )\n" + "end\n" + "\n" + "rule look when \n" + " Person( $l : likes ) \n" + " isContainedIn( $l, 'office'; )\n" + "then\n" + " insertLogical( 'blah' );" + "end\n" + "rule existsBlah when \n" + " exists String( this == 'blah') \n" + "then\n" + " list.add( 'exists blah' );" + "end\n" + "\n" + "rule notBlah when \n" + " not String( this == 'blah') \n" + "then\n" + " list.add( 'not blah' );" + "end\n" + "\n" + "rule init when\n" + "then\n" + // " insert( new Location(\"apple\", \"kitchen\") );\n" +
" insert( new Location(\"desk\", \"office\") );\n" + // " insert( new Location(\"flashlight\", \"desk\") );\n" +
" insert( new Location(\"envelope\", \"desk\") );\n" + " insert( new Location(\"key\", \"envelope\") );\n" + // " insert( new Location(\"computer\", \"office\") );\n" +
"end\n" + "\n" + "rule go1 when \n" + " String( this == 'go1') \n" + "then\n" + " list.add( rule.getName() ); \n" + " insert( new Location('lamp', 'desk') );\n" + "end\n" + "\n" + "rule go2 when \n" + " String( this == 'go2') \n" + " $l : Location('lamp', 'desk'; )\n" + "then\n" + " list.add( rule.getName() ); \n" + " retract( $l );\n" + "end\n" + "\n" + "rule go3 when \n" + " String( this == 'go3') \n" + "then\n" + " list.add( rule.getName() ); \n" + " insert( new Location('lamp', 'desk') );\n" + "end\n" + "\n" + "rule go4 when \n" + " String( this == 'go4') \n" + " $l : Location('lamp', 'desk'; )\n" + "then\n" + " list.add( rule.getName() ); \n" + " modify( $l ) { thing = 'book' };\n" + "end\n" + "\n" + "rule go5 when \n" + " String( this == 'go5') \n" + " $l : Location('book', 'desk'; )\n" + "then\n" + " list.add( rule.getName() ); \n" + " modify( $l ) { thing = 'lamp' };\n" + "end\n" + "\n" + "rule go6 when \n" + " String( this == 'go6') \n" + " $l : Location( 'lamp', 'desk'; )\n" + "then\n" + " list.add( rule.getName() ); \n" + " modify( $l ) { thing = 'book' };\n" + "end\n" + "\n" + "rule go7 when \n" + " String( this == 'go7') \n" + " $p : Person( likes == 'lamp' ) \n" + "then\n" + " list.add( rule.getName() ); \n" + " modify( $p ) { likes = 'key' };\n" + "end\n" + "\n";
KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBaseFromString(str));
KieSession ksession = createKnowledgeSession(kbase);
List<String> list = new ArrayList<String>();
ksession.setGlobal("list", list);
QueryResults results = null;
Person p = new Person();
p.setLikes("lamp");
FactHandle handle = ksession.insert(p);
// ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
assertEquals("not blah", list.get(0));
list.clear();
InternalFactHandle fh = (InternalFactHandle) ksession.insert("go1");
// ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.retract(fh);
assertEquals("go1", list.get(0));
assertEquals("exists blah", list.get(1));
fh = (InternalFactHandle) ksession.insert("go2");
// ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.retract(fh);
assertEquals("go2", list.get(2));
assertEquals("not blah", list.get(3));
fh = (InternalFactHandle) ksession.insert("go3");
logger.trace("--------------");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.retract(fh);
assertEquals("go3", list.get(4));
assertEquals("exists blah", list.get(5));
fh = (InternalFactHandle) ksession.insert("go4");
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.retract(fh);
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
assertEquals("go4", list.get(6));
assertEquals("not blah", list.get(7));
fh = (InternalFactHandle) ksession.insert("go5");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.retract(fh);
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
assertEquals("go5", list.get(8));
assertEquals("exists blah", list.get(9));
// This simulates a modify of the root DroolsQuery object, but first we break it
fh = (InternalFactHandle) ksession.insert("go6");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.retract(fh);
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
assertEquals("go6", list.get(10));
assertEquals("not blah", list.get(11));
// now fix it
fh = (InternalFactHandle) ksession.insert("go7");
ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
ksession.fireAllRules();
fh = getFactHandle(fh, ksession);
ksession.retract(fh);
ksession = getSerialisedStatefulKnowledgeSession(ksession, true);
assertEquals("go7", list.get(12));
assertEquals("exists blah", list.get(13));
}
Aggregations