@Test public void testAnalyzeConditionWithVariableRegExp() throws Exception { // JBRULES-3659 String str = "dialect \"mvel\"\n" + "\n" + "declare Person\n" + " name : String\n" + "end\n" + "declare Stuff\n" + " regexp : String\n" + "end\n" + "\n" + "rule \"Test Regex\"\n" + " salience 100\n" + " when\n" + " then\n" + " insert (new Stuff(\"Test\"));\n" + " insert (new Person(\"Test\"));\n" + "end\n" + "\n" + "rule \"Test Equality\"\n" + " salience 10\n" + " when\n" + " Stuff( $regexp : regexp )\n" + " Person( name matches $regexp )\n" + " //Person( name matches \"Test\" )\n" + " then\n" + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); assertEquals(2, ksession.fireAllRules()); }
@Test public void testJitConstraintWithOperationOnBigDecimal() { // DROOLS-32 String str = "import org.drools.integrationtests.MiscTest2.Model;\n" + "import java.math.BigDecimal;\n" + "\n" + "rule \"minCost\" dialect \"mvel\" \n" + "when\n" + " $product : Model(price < (cost + 0.10B))\n" + "then\n" + " modify ($product) { price = $product.cost + 0.10B }\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); final Model model = new Model(); model.setCost(new BigDecimal("2.43")); model.setPrice(new BigDecimal("2.43")); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession.insert(model); int fired = ksession.fireAllRules(2); if (fired > 1) throw new RuntimeException("loop"); }
public Void execute(Context context) { em.joinTransaction(); em.persist(mainObject); if (subObject != null) { KieSession ksession = ((KnowledgeCommandContext) context).getKieSession(); // THe following 3 lines are the important ones! (See below for an explanation) KnowledgeBase cleanKBase = KnowledgeBaseFactory.newKnowledgeBase(); cleanKBase.addKnowledgePackages( ((KnowledgeBase) ksession.getKieBase()).getKnowledgePackages()); StatefulKnowledgeSession commandKSession = JPAKnowledgeService.newStatefulKnowledgeSession( cleanKBase, null, initializeEnvironment()); /** * Here's what's going on: If the SingleSessionCommandService (SSCS) & JtaTransactionManager * (JTM) were _not_ aware of transactions, -> then inserting the mainObject _before_ having * inserted the subObject would cause the operation/persist to fail and the transaction to * fail. - This is because the mainObject contains a foreign key referring to the subObject. * * <p>However, the SSCS & JTM check whether or not they're owners of the transaction when * starting and when committing the transaction they use. -> So that when we insert the * mainObject here (via a _new_ CommandBasedStatefulKnowledgeSession), it does _not_ mess with * the transaction state and the operation succeeds. */ TransactionTestCommand transactionTestSubCommand = new TransactionTestCommand(this.subObject, getPersistenceEnvironment()); commandKSession.execute(transactionTestSubCommand); } return null; }
public void testProcessFactory() { RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process"); factory // header .name("My process") .packageName("org.jbpm") // nodes .startNode(1) .name("Start") .done() .actionNode(2) .name("Action") .action("java", "System.out.println(\"Action\");") .done() .endNode(3) .name("End") .done() // connections .connection(1, 2) .connection(2, 3); RuleFlowProcess process = factory.validate().getProcess(); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newByteArrayResource( XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes()), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); ksession.startProcess("org.jbpm.process"); }
@Test public void testAllowEqualityBetweenObjectAndPrimitiveInt() { // DROOLS-20 String str = "declare Bean\n" + " items : int\n" + "end\n" + "\n" + "rule \"O\"\n" + "when\n" + "then\n" + " insert( new Bean( 2 ) );\n" + "end\n" + "\n" + "rule \"X\"\n" + "when\n" + " Bean( $num : items ) \n" + " accumulate( $o : Object(),\n" + " $list : collectList( $o );\n" + " $list.size == $num" + " )\n" + "then\n" + " System.out.println( \"Success!\" );\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); assertEquals(2, ksession.fireAllRules()); }
@Test(timeout = 10000) public void testConcurrentInsertions() { String str = "import MultithreadTest.Bean\n" + "\n" + "rule \"R\"\n" + "when\n" + " $a : Bean( seed != 1 )\n" + "then\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); Executor executor = Executors.newCachedThreadPool( new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } }); final int OBJECT_NR = 1000; final int THREAD_NR = 4; CompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(executor); for (int i = 0; i < THREAD_NR; i++) { ecs.submit( new Callable<Boolean>() { public Boolean call() throws Exception { try { FactHandle[] facts = new FactHandle[OBJECT_NR]; for (int i = 0; i < OBJECT_NR; i++) facts[i] = ksession.insert(new Bean(i)); ksession.fireAllRules(); for (FactHandle fact : facts) ksession.retract(fact); ksession.fireAllRules(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }); } boolean success = true; for (int i = 0; i < THREAD_NR; i++) { try { success = ecs.take().get() && success; } catch (Exception e) { throw new RuntimeException(e); } } assertTrue(success); ksession.dispose(); }
public void receive(Object object, PipelineContext context) { StatefulKnowledgeSessionPipelineContext kContext = (StatefulKnowledgeSessionPipelineContext) context; StatefulKnowledgeSession ksession = kContext.getStatefulKnowledgeSession(); Object result = ksession.getGlobal((String) object); emit(result, kContext); }
public void testSignalBoundaryEvent() { KnowledgeBase kbase = createKnowledgeBase( "BPMN2-BoundarySignalEventOnTaskbpmn2.bpmn", "BPMN2-IntermediateThrowEventSignal.bpmn2"); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); TestWorkItemHandler handler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); ProcessInstance processInstance = ksession.startProcess("BoundarySignalOnTask"); ProcessInstance processInstance2 = ksession.startProcess("SignalIntermediateEvent"); assertProcessInstanceCompleted(processInstance2.getId(), ksession); assertProcessInstanceCompleted(processInstance.getId(), ksession); }
public void testSingleActionNode() throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( new ClassPathResource("ActionNodeTest.xml", ActionNodeTest.class), ResourceType.DRF); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); List<String> list = new ArrayList<String>(); ksession.setGlobal("list", list); ksession.startProcess("process name"); assertEquals(1, list.size()); assertEquals("action node was here", list.get(0)); }
@Test public void testShareAlphaNodesRegardlessDoubleOrSingleQuotes() { // JBRULES-3640 String str = "declare RecordA\n" + " id : long\n" + "end\n" + "\n" + "declare RecordB\n" + " id : long\n" + "role : String\n" + "end\n" + "\n" + "rule \"insert data 1\"\n" + " salience 10\n" + " when\n" + " then\n" + " insert (new RecordA(100));\n" + " insert (new RecordB(100, \"1\"));\n" + " insert (new RecordB(100, \"2\"));\n" + "end\n" + "\n" + "rule \"test 1\"\n" + " when\n" + " a : RecordA( )\n" + " b : RecordB( id == b.id, role == '1' )\n" + " then\n" + "end\n" + "\n" + "rule \"test 2\"\n" + " when\n" + " a : RecordA( )\n" + " b : RecordB( id == b.id, role == \"1\" )\n" + " then\n" + "end\n" + "\n" + "rule \"test 3\"\n" + " when\n" + " a : RecordA( )\n" + " b : RecordB( id == b.id, role == \"2\" )\n" + " then\n" + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); assertEquals(4, ksession.fireAllRules()); }
@Test public void testPropertyReactivityWithNestedAccessorsInModify() { // JBRULES-3691 String str = "package com.ilesteban.rulenotbeingfired;\n" + "\n" + "import java.util.Map;\n" + "import java.util.EnumMap;\n" + "import org.drools.integrationtests.MiscTest2.Parameter\n" + "import org.drools.integrationtests.MiscTest2.DataSample\n" + "\n" + "declare Recommendation\n" + " parameter : Parameter\n" + " value : double\n" + "end\n" + "\n" + "rule \"Init\" salience 100\n" + "when\n" + "then\n" + " insert(new Recommendation(Parameter.PARAM_A, 1.0));" + "end\n" + "rule \"Rule 1\"\n" + "when\n" + " $d: DataSample()\n" + " $re: Recommendation ($p: parameter, $v: value)\n" + "then\n" + " System.out.println(drools.getRule().getName());\n" + " modify($d){\n" + " addValue($re.getParameter(), $re.getValue())\n" + " }\n" + "end\n" + "\n" + "rule \"Data with messages\"\n" + "salience -100\n" + "when\n" + " $d: DataSample(notEmpty == true)\n" + "then\n" + " System.out.println(drools.getRule().getName());\n" + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession.insert(new DataSample()); assertEquals(3, ksession.fireAllRules()); }
public void testSignalBetweenProcesses() { KnowledgeBase kbase = createKnowledgeBase( "BPMN2-IntermediateCatchSignalSingle.bpmn2", "BPMN2-IntermediateThrowEventSignal.bpmn2"); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); TestWorkItemHandler handler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); ProcessInstance processInstance = ksession.startProcess("BPMN2-IntermediateCatchSignalSingle"); ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); ProcessInstance processInstance2 = ksession.startProcess("SignalIntermediateEvent"); assertProcessInstanceCompleted(processInstance2.getId(), ksession); assertProcessInstanceCompleted(processInstance.getId(), ksession); }
public static void run(String demo) { TraitFactory.reset(); StatefulKnowledgeSession kSession = getSession(demo); kSession.fireAllRules(); Collection c = kSession.getObjects(); System.out.println("------------------------- " + c.size() + " ----------------------"); for (Object o : c) { System.out.println(" \t --- " + o); } System.out.println("-----------------------------------------------------------------"); kSession.dispose(); }
@Test public void testIntSorting2() { // DROOLS-15 String str = "global java.util.List list\n" + "rule R\n" + "dialect \"mvel\"\n" + "when\n" + " $number : Number()\n" + " not Number(intValue > $number.intValue)\n" + "then\n" + " list.add($number);\n" + " retract($number);\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); List<Integer> list = new ArrayList<Integer>(); ksession.setGlobal("list", list); ksession.insert(3); ksession.insert(7); ksession.insert(4); ksession.insert(5); ksession.insert(2); ksession.insert(1); ksession.insert(6); ksession.fireAllRules(); assertEquals(Arrays.asList(7, 6, 5, 4, 3, 2, 1), list); }
public void testSignalToStartProcess() { KnowledgeBase kbase = createKnowledgeBase("BPMN2-SignalStart.bpmn2", "BPMN2-IntermediateThrowEventSignal.bpmn2"); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); TestWorkItemHandler handler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); final List<String> startedProcesses = new ArrayList<String>(); ksession.addEventListener( new DefaultProcessEventListener() { @Override public void beforeProcessStarted(ProcessStartedEvent event) { startedProcesses.add(event.getProcessInstance().getProcessId()); } }); ProcessInstance processInstance2 = ksession.startProcess("SignalIntermediateEvent"); assertProcessInstanceCompleted(processInstance2.getId(), ksession); assertEquals(2, startedProcesses.size()); }
@Test public void testNumberCoercionOnNonGenericMap() { // JBRULES-3708 String str = "package com.ilesteban.jit;\n" + "\n" + "import java.util.Map;\n" + "import java.util.EnumMap;\n" + "import org.drools.integrationtests.MiscTest2.Parameter\n" + "import org.drools.integrationtests.MiscTest2.DataSample\n" + "\n" + "declare TestObject\n" + " data : java.util.Map\n" + "end\n" + "\n" + "rule \"Rule 1\"\n" + "when\n" + " $d: DataSample()\n" + "then\n" + " //create a new object copying the Map<Parameter, Double> to a Map<Object, Object>\n" + " insert( new TestObject($d.getValues()));\n" + "end\n" + "\n" + "rule \"Rule 2\"\n" + "when\n" + " TestObject(data[Parameter.PARAM_A] > 3)\n" + "then\n" + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); Map<Parameter, Double> values = new EnumMap<Parameter, Double>(Parameter.class); values.put(Parameter.PARAM_A, 4.0); DataSample data = new DataSample(); data.setValues(values); ksession.insert(data); assertEquals(2, ksession.fireAllRules()); }
@Test public void testDeclaredTypeExtendingInnerClass() { // DROOLS-27 String str = "import org.drools.integrationtests.MiscTest2.StaticPerson\n" + "declare StaticPerson end\n" + "declare Student extends StaticPerson end\n" + "rule Init when\n" + "then\n" + " Student s = new Student();\n" + " s.setName( \"Mark\" );\n" + " insert( s );\n" + "end\n" + "rule Check when\n" + " StaticPerson( name == \"Mark\")\n" + "then\n" + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); assertEquals(2, ksession.fireAllRules()); }
@Test public void testBigDecimalComparison() throws Exception { // JBRULES-3715 String str = "import org.drools.Person;\n" + "rule \"Big Decimal Comparison\"\n" + " dialect \"mvel\"\n" + "when\n" + " Person( bigDecimal == 0.0B )\n" + "then\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); Person p = new Person("Mario", 38); p.setBigDecimal(new BigDecimal("0")); ksession.insert(p); assertEquals(1, ksession.fireAllRules()); ksession.dispose(); }
@Test public void testMvelAssignmentToPublicField() { String str = "import org.drools.integrationtests.MiscTest2.Foo\n" + "rule R\n" + "dialect \"mvel\"\n" + "when\n" + " $foo : Foo()\n" + "then\n" + " $foo.x = 1;\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); Foo foo1 = new Foo(); Foo foo2 = new Foo(); ksession.insert(foo1); ksession.insert(foo2); ksession.fireAllRules(); assertEquals(1, foo1.x); assertEquals(1, foo2.x); }
@Test public void testMvelInvokeAsList() { String str = "import java.util.List;\n" + "import java.util.Arrays;\n" + "import java.util.ArrayList;\n" + "\n" + "declare Project\n" + "@typesafe (false)\n" + " list1 : List\n" + " list2 : List\n" + "end\n" + "\n" + "rule kickoff\n" + "salience 999999\n" + "when\n" + "then\n" + " insert( new Project() );\n" + " insert( new Project() ); // necessary to trigger the exception\n" + "end\n" + "\n" + "rule \" Config rule \"\n" + "dialect \"mvel\"\n" + "no-loop true\n" + "when\n" + " P : Project()\n" + "then\n" + " modify(P) {\n" + " list1 = Arrays.asList(10, 15, 20, 25),\n" + " list2 = Arrays.asList(11, 2, 3, 4, 5, 10, 9, 8, 7)\n" + " };\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession.fireAllRules(); }
public void testEntry(KProjectTestClass testClass, String jarName) { List<String> list = new ArrayList<String>(); StatelessKnowledgeSession stlsKsession = testClass.getKBase1KSession1(); stlsKsession.setGlobal("list", list); stlsKsession.execute("dummy"); assertEquals(2, list.size()); assertTrue(list.contains(jarName + ".test1:rule1")); assertTrue(list.contains(jarName + ".test1:rule2")); list.clear(); StatefulKnowledgeSession stflKsession = testClass.getKBase1KSession2(); stflKsession.setGlobal("list", list); stflKsession.fireAllRules(); assertEquals(2, list.size()); assertTrue(list.contains(jarName + ".test1:rule1")); assertTrue(list.contains(jarName + ".test1:rule2")); list.clear(); stflKsession = testClass.getKBase2KSession3(); stflKsession.setGlobal("list", list); stflKsession.fireAllRules(); assertEquals(2, list.size()); assertTrue(list.contains(jarName + ".test2:rule1")); assertTrue(list.contains(jarName + ".test2:rule2")); list.clear(); stlsKsession = testClass.getKBase3KSession4(); stlsKsession.setGlobal("list", list); stlsKsession.execute("dummy"); assertEquals(4, list.size()); assertTrue(list.contains(jarName + ".test1:rule1")); assertTrue(list.contains(jarName + ".test1:rule2")); assertTrue(list.contains(jarName + ".test2:rule1")); assertTrue(list.contains(jarName + ".test2:rule2")); }
@Test(timeout = 5000) public void testInfiniteLoopCausedByInheritance() throws Exception { // DROOLS-13 String str = "declare Parent\n" + " active : boolean\n" + "end\n" + " \n" + "declare Child extends Parent\n" + "end\n" + " \n" + "rule \"Init\"\n" + "when\n" + "then\n" + " insert( new Child( false ) );\n" + "end\n" + " \n" + "rule \"Print\"\n" + "when\n" + " $g : Child( active == true )\n" + "then\n" + "end\n" + " \n" + " \n" + "rule \"Switch\"\n" + "when\n" + " $item : Parent( active == false )\n" + "then\n" + " modify ( $item ) {\n" + " setActive( true );\n" + " }\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession.fireAllRules(); }
public static void main(final String[] args) { final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newClassPathResource( "WorkItemConsequence1.drl", WorkItemConsequenceExample1.class), ResourceType.DRL); final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); if (kbuilder.hasErrors()) { throw new RuntimeException("Compilation error.\n" + kbuilder.getErrors().toString()); } final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession .getWorkItemManager() .registerWorkItemHandler("EmailWorkItemHandler", new EmailWorkItemHandler()); // KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, // "log/WorkItemConsequence.log"); // Brains does not cause concern PersonLocation brains = new PersonLocation("Brains", 5); ksession.insert(brains); ksession.fireAllRules(); // Gargamel is too far away to care PersonLocation gargamel = new PersonLocation("Gargamel", 10); FactHandle gargamelFactHandle = ksession.insert(gargamel); ksession.fireAllRules(); // Uh oh, Gargamel moves closer gargamel.setDistance(5); ksession.update(gargamelFactHandle, gargamel); ksession.fireAllRules(); // logger.close(); ksession.dispose(); // Stateful rule session must always be disposed when finished }
@Test public void testUpdateWithNonEffectiveActivations() throws Exception { // JBRULES-3604 String str = "package inheritance\n" + "\n" + "import org.drools.Address\n" + "\n" + "rule \"Parent\"\n" + " enabled false\n" + " when \n" + " $a : Address(suburb == \"xyz\")\n" + " then \n" + " System.out.println( $a ); \n" + "end \n" + "rule \"Child\" extends \"Parent\" \n" + " when \n" + " $b : Address( this == $a, street == \"123\")\n" + " then \n" + " System.out.println( $b ); \n" + "end"; KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder(); builder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); if (builder.hasErrors()) { throw new RuntimeException(builder.getErrors().toString()); } KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kconf.setOption(LRUnlinkingOption.ENABLED); KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(kconf); knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages()); StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession(); Address address = new Address(); address.setSuburb("xyz"); org.kie.runtime.rule.FactHandle addressHandle = ksession.insert(address); int rulesFired = ksession.fireAllRules(); assertEquals(0, rulesFired); address.setStreet("123"); ksession.update(addressHandle, address); rulesFired = ksession.fireAllRules(); System.out.println(rulesFired); assertEquals(1, rulesFired); ksession.dispose(); }
private String insertMessageAndFire(String message, boolean stateful) throws IllegalAccessException, InstantiationException { System.out.println("********** Firing rules"); String result = null; FactType testFactType = kagent.getKnowledgeBase().getFactType("test", "TestFact"); Object fact = testFactType.newInstance(); testFactType.set(fact, "message", message); if (stateful) { StatefulKnowledgeSession session = kagent.getKnowledgeBase().newStatefulKnowledgeSession(); session.insert(fact); session.fireAllRules(); result = (String) testFactType.get(fact, "message"); session.dispose(); } else { StatelessKnowledgeSession session = kagent.getKnowledgeBase().newStatelessKnowledgeSession(); session.execute(fact); result = (String) testFactType.get(fact, "message"); } return result; }
@Test public void testDynamicAddRule() { // DROOLS-17 String str = "import org.drools.integrationtests.MiscTest2.A\n" + "rule r1 when\n" + " $a : A( f1 == 1 )\n" + "then\n" + "end\n" + "\n" + "rule r2 when\n" + " $a : A( f2 == 1 )\n" + "then\n" + "end\n" + "\n" + "rule r3 when\n" + " $a : A( f3 == 1 )" + "then\n" + "end"; String str2 = "import org.drools.integrationtests.MiscTest2.A\n" + "rule r4 when\n" + " $a : A( f2 == 1, f4 == 1 )" + "then\n" + "end"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { fail(kbuilder.getErrors().toString()); } KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); FactHandle fh = ksession.insert(new A(1, 1, 1, 1)); ksession.fireAllRules(); kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str2.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { fail(kbuilder.getErrors().toString()); } kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); ksession.fireAllRules(); // this second insert forces the regeneration of the otnIds ksession.insert(new A(2, 2, 2, 2)); LeftTuple leftTuple = ((DefaultFactHandle) fh).getFirstLeftTuple(); ObjectTypeNode.Id letTupleOtnId = leftTuple.getLeftTupleSink().getLeftInputOtnId(); leftTuple = leftTuple.getLeftParentNext(); while (leftTuple != null) { assertTrue(letTupleOtnId.before(leftTuple.getLeftTupleSink().getLeftInputOtnId())); letTupleOtnId = leftTuple.getLeftTupleSink().getLeftInputOtnId(); leftTuple = leftTuple.getLeftParentNext(); } }
@Test public void testPropertyReactiveAccumulateModification() { // DROOLS-16 String str = "package org.drools.test;\n" + "\n" + "declare Neuron\n" + "@propertyReactive\n" + " id : int\n" + " value : double\n" + "end\n" + "\n" + "declare Charge\n" + " nId : int\n" + " val : double\n" + "end\n" + "\n" + "rule \"Log 2\"\n" + "salience 9999\n" + "when\n" + " $n : Object();\n" + "then\n" + "end\n" + "rule \"Update\"\n" + "salience -9999\n" + "when\n" + " $c : Charge( val == 1.0 );\n" + "then\n" + " modify ( $c ) { " + " setVal( 2.0 ); \n" + " } \n" + "end\n" + "\n" + "rule \"Init\"\n" + "when\n" + "then\n" + " insert( new Neuron( 0, 0.0 ) );\n" + " insert( new Charge( 0, 1.0 ) );\n" + "end\n" + "\n" + "rule \"Modify\"\n" + "salience -100\n" + "when\n" + " $n : Neuron( )\n" + " accumulate( Charge( $v : val ), $x : sum( $v ) )\n" + "then\n" + " modify ( $n ) {\n" + " setValue( $x.doubleValue() );\n" + " }\n" + "end\n" + "\n" + "rule \"Watch\"\n" + "when\n" + " $n : Neuron() @watch( value )" + "then\n" + "end\n" + "\n" + "query getNeuron\n" + " Neuron( $value : value )\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession.fireAllRules(); assertEquals(2.0, ksession.getQueryResults("getNeuron").iterator().next().get("$value")); }
@Test @Ignore public void testReuseAgendaAfterException() throws Exception { // JBRULES-3677 String str = "import org.drools.Person;\n" + "global java.util.List results;" + "rule R1\n" + "ruleflow-group \"test\"\n" + "when\n" + " Person( $age : age ) \n" + "then\n" + " if ($age > 40) throw new RuntimeException(\"Too old\");\n" + " results.add(\"OK\");" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); List<String> res = new ArrayList<String>(); ksession.setGlobal("results", res); AgendaEventListener agendaEventListener = new AgendaEventListener() { public void matchCreated(org.kie.event.rule.MatchCreatedEvent event) {} public void matchCancelled(org.kie.event.rule.MatchCancelledEvent event) {} public void beforeMatchFired(org.kie.event.rule.BeforeMatchFiredEvent event) {} public void afterMatchFired(org.kie.event.rule.AfterMatchFiredEvent event) {} public void agendaGroupPopped(org.kie.event.rule.AgendaGroupPoppedEvent event) {} public void agendaGroupPushed(org.kie.event.rule.AgendaGroupPushedEvent event) {} public void beforeRuleFlowGroupActivated( org.kie.event.rule.RuleFlowGroupActivatedEvent event) {} public void afterRuleFlowGroupActivated( org.kie.event.rule.RuleFlowGroupActivatedEvent event) { ksession.fireAllRules(); } public void beforeRuleFlowGroupDeactivated( org.kie.event.rule.RuleFlowGroupDeactivatedEvent event) {} public void afterRuleFlowGroupDeactivated( org.kie.event.rule.RuleFlowGroupDeactivatedEvent event) {} }; ksession.addEventListener(agendaEventListener); FactHandle fact1 = ksession.insert(new Person("Mario", 38)); ((AgendaImpl) ksession.getAgenda()).activateRuleFlowGroup("test"); assertEquals(1, res.size()); res.clear(); ksession.retract(fact1); FactHandle fact2 = ksession.insert(new Person("Mario", 48)); try { ((AgendaImpl) ksession.getAgenda()).activateRuleFlowGroup("test"); fail("should throw an Exception"); } catch (Exception e) { } ksession.retract(fact2); assertEquals(0, res.size()); // try to reuse the ksession after the Exception FactHandle fact3 = ksession.insert(new Person("Mario", 38)); ((AgendaImpl) ksession.getAgenda()).activateRuleFlowGroup("test"); assertEquals(1, res.size()); ksession.retract(fact3); ksession.dispose(); }
@Test(timeout = 5000) public void testPropertyReactiveOnAlphaNodeFollowedByAccumulate() { // DROOLS-16 String str = "package org.drools.pmml.pmml_4_1.test;\n" + "\n" + "declare Charge\n" + " context : String\n" + " index : String = \"-1\"\n" + " source : String = \"-1\"\n" + " value : double\n" + "end\n" + "\n" + "declare Neuron\n" + "@propertyReactive\n" + " context : String @key\n" + " index : String @key\n" + " layerIndex : int\n" + " bias : double\n" + " fanIn : int\n" + " value : double\n" + " dvalue : double\n" + " normalized : boolean\n" + "end\n" + "\n" + "rule \"LinkSynapses\"\n" + "when\n" + "then\n" + " Charge c = new Charge();\n" + " c.setContext( \"MockCold\" );\n" + " c.setSource( \"0\" );\n" + " c.setIndex( \"1\" );\n" + " c.setValue( 0.43 );\n" + " insert(c);\n" + "end\n" + "\n" + "rule \"NeuralFire_MockCold_Layer0\"\n" + "when\n" + " $neur : Neuron( context == \"MockCold\",\n" + " layerIndex == 0\n" + " )\n" + " accumulate( $c : Charge( context == \"MockCold\", index == $neur.index, $in : value ),\n" + " $list : collectList( $c ),\n" + " $val : sum( $in );\n" + " $list.size() == $neur.fanIn )\n" + "then\n" + " double x = 1.0; // $neur.getBias() + $val.doubleValue();\n" + " modify ( $neur ) {\n" + " setValue( x );\n" + " }\n" + "end\n" + "\n" + "rule \"BuildNeurons_MockCold_Layer0\"\n" + "when\n" + "then\n" + " insert( new Neuron( \"MockCold\",\n" + " \"1\",\n" + " 0,\n" + " 1.0,\n" + " 1,\n" + " 0.0,\n" + " 0.0,\n" + " true\n" + " ) );\n" + "end"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); assertEquals(3, ksession.fireAllRules()); }
public void testEvent1() { RuleFlowProcess process = new RuleFlowProcess(); process.setId("org.drools.process.event"); process.setName("Event Process"); List<Variable> variables = new ArrayList<Variable>(); Variable variable = new Variable(); variable.setName("event"); ObjectDataType personDataType = new ObjectDataType(); personDataType.setClassName("org.drools.Person"); variable.setType(personDataType); variables.add(variable); process.getVariableScope().setVariables(variables); StartNode startNode = new StartNode(); startNode.setName("Start"); startNode.setId(1); process.addNode(startNode); MilestoneNode milestoneNode = new MilestoneNode(); milestoneNode.setName("Milestone"); milestoneNode.setConstraint("eval(false)"); milestoneNode.setId(2); process.addNode(milestoneNode); new ConnectionImpl( startNode, Node.CONNECTION_DEFAULT_TYPE, milestoneNode, Node.CONNECTION_DEFAULT_TYPE); EventNode eventNode = new EventNode(); EventTypeFilter eventFilter = new EventTypeFilter(); eventFilter.setType("myEvent"); eventNode.addEventFilter(eventFilter); eventNode.setVariableName("event"); eventNode.setId(3); process.addNode(eventNode); final List<String> myList = new ArrayList<String>(); ActionNode actionNode = new ActionNode(); actionNode.setName("Print"); DroolsAction action = new DroolsConsequenceAction("java", null); action.setMetaData( "Action", new Action() { public void execute(ProcessContext context) throws Exception { System.out.println( "Detected event for person " + ((Person) context.getVariable("event")).getName()); myList.add("Executed action"); } }); actionNode.setAction(action); actionNode.setId(4); process.addNode(actionNode); new ConnectionImpl( eventNode, Node.CONNECTION_DEFAULT_TYPE, actionNode, Node.CONNECTION_DEFAULT_TYPE); Join join = new Join(); join.setName("XOR Join"); join.setType(Join.TYPE_XOR); join.setId(5); process.addNode(join); new ConnectionImpl( milestoneNode, Node.CONNECTION_DEFAULT_TYPE, join, Node.CONNECTION_DEFAULT_TYPE); new ConnectionImpl( actionNode, Node.CONNECTION_DEFAULT_TYPE, join, Node.CONNECTION_DEFAULT_TYPE); EndNode endNode = new EndNode(); endNode.setName("EndNode"); endNode.setId(6); process.addNode(endNode); new ConnectionImpl( join, Node.CONNECTION_DEFAULT_TYPE, endNode, Node.CONNECTION_DEFAULT_TYPE); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); ((AbstractRuleBase) ((InternalKnowledgeBase) kbase).getRuleBase()).addProcess(process); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ProcessInstance processInstance = ksession.startProcess("org.drools.process.event"); assertEquals(0, myList.size()); Person jack = new Person(); jack.setName("Jack"); processInstance.signalEvent("myEvent", jack); assertEquals(1, myList.size()); assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState()); }