Search in sources :

Example 26 with FactHandle

use of org.kie.api.runtime.rule.FactHandle in project drools by kiegroup.

the class TruthMaintenanceTest method testLogicalInsertions3.

// (timeout=10000)
@Test
public void testLogicalInsertions3() throws Exception {
    KieBase kbase = loadKnowledgeBase("test_logicalInsertions3.drl");
    KieSession ksession = kbase.newKieSession();
    final List list = new ArrayList();
    ksession.setGlobal("events", list);
    // asserting the sensor object
    final Sensor sensor = new Sensor(150, 100);
    FactHandle sensorHandle = ksession.insert(sensor);
    ksession.fireAllRules();
    ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
    // alarm must sound
    assertEquals(2, list.size());
    assertEquals(2, ksession.getObjects().size());
    // modifying sensor
    sensor.setTemperature(125);
    sensorHandle = getFactHandle(sensorHandle, ksession);
    ksession.update(sensorHandle, sensor);
    ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
    ksession.fireAllRules();
    ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
    // alarm must continue to sound
    assertEquals(3, list.size());
    assertEquals(2, ksession.getObjects().size());
    // modifying sensor
    sensor.setTemperature(80);
    sensorHandle = getFactHandle(sensorHandle, ksession);
    ksession.update(sensorHandle, sensor);
    ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
    ksession.fireAllRules();
    // no alarms anymore
    assertEquals(3, list.size());
    assertEquals(1, ksession.getObjects().size());
}
Also used : InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) KieBase(org.kie.api.KieBase) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) List(java.util.List) ArrayList(java.util.ArrayList) Sensor(org.drools.compiler.Sensor) Test(org.junit.Test)

Example 27 with FactHandle

use of org.kie.api.runtime.rule.FactHandle in project drools by kiegroup.

the class MultithreadTest method testConcurrentDelete.

@Test(timeout = 20000)
public void testConcurrentDelete() {
    final String drl = "import " + SlowBean.class.getCanonicalName() + ";\n" + "rule R when\n" + "  $sb1: SlowBean() \n" + "  $sb2: SlowBean( id > $sb1.id ) \n" + "then " + "  System.out.println($sb2 + \" > \"+ $sb1);" + "end\n";
    final KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession();
    final int BEAN_NR = 4;
    for (int step = 0; step < 2; step++) {
        final FactHandle[] fhs = new FactHandle[BEAN_NR];
        for (int i = 0; i < BEAN_NR; i++) {
            fhs[i] = ksession.insert(new SlowBean(i + step * BEAN_NR));
        }
        final CyclicBarrier barrier = new CyclicBarrier(2);
        new Thread(new Runnable() {

            @Override
            public void run() {
                ksession.fireAllRules();
                try {
                    barrier.await();
                } catch (final Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        try {
            Thread.sleep(15L);
        } catch (final InterruptedException e) {
            throw new RuntimeException(e);
        }
        for (int i = 0; i < BEAN_NR; i++) {
            if (i % 2 == 1) {
                ksession.delete(fhs[i]);
            }
        }
        try {
            barrier.await();
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("Done step " + step);
    }
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) KieHelper(org.kie.internal.utils.KieHelper) EntryPoint(org.kie.api.runtime.rule.EntryPoint) CyclicBarrier(java.util.concurrent.CyclicBarrier) KieSession(org.kie.api.runtime.KieSession) Test(org.junit.Test)

Example 28 with FactHandle

use of org.kie.api.runtime.rule.FactHandle in project drools by kiegroup.

the class RuleUnitCoordinationTest method testCoordination.

@Test
public void testCoordination() throws Exception {
    String drl1 = "package org.drools.compiler.integrationtests\n" + "unit " + getCanonicalSimpleName(MasterModelUnit.class) + ";\n" + "import " + MasterModel.class.getCanonicalName() + "\n" + "import " + ApplicableModel.class.getCanonicalName() + "\n" + "import " + ApplyMathModel.class.getCanonicalName() + "\n" + "import " + ApplyStringModel.class.getCanonicalName() + "\n" + "import " + ScheduledModelApplicationUnit.class.getCanonicalName() + "\n" + "\n" + "rule FindModelToApply \n" + "when\n" + "   $mm: MasterModel( subModels != null ) from models\n" + "   $am: ApplicableModel( applied == false, $idx: index ) from $mm.subModels\n" + // "   not ApplicableModel( applied == false, index < $idx ) from $mm.subModels\n" +
    "then\n" + "   applicableModels.insert($am);\n" + "   drools.run(new ScheduledModelApplicationUnit(models,applicableModels));\n" + "end\n" + "";
    String drl2 = "package org.drools.compiler.integrationtests\n" + "unit " + getCanonicalSimpleName(ScheduledModelApplicationUnit.class) + ";\n" + "import " + MasterModel.class.getCanonicalName() + "\n" + "import " + ApplicableModel.class.getCanonicalName() + "\n" + "import " + ApplyMathModel.class.getCanonicalName() + "\n" + "import " + ApplyStringModel.class.getCanonicalName() + "\n" + "\n" + "rule Apply_ApplyMathModel_Addition \n" + "when\n" + "    $amm: ApplyMathModel( applied == false, inputValue1 != null, " + "                          inputValue2 != null, operation == \"add\" ) from applicableModels\n" + "    $v1: Integer() from $amm.inputValue1 \n" + "    $v2: Integer() from $amm.inputValue2 \n" + "then\n" + "    modify($amm) { \n" + "       setResult($v1.intValue() + $v2.intValue()), \n" + "       setApplied(true) \n" + "    };\n" + "    System.out.println(\"Result = \"+$amm.getResult());\n" + "end\n" + "\n" + "rule Apply_ApplyStringModel_Concat \n" + "when\n" + "    $asm: ApplyStringModel( applied == false, inputString1 != null, " + "                            inputString2 != null, operation == \"concat\" ) from applicableModels \n" + "    $v1: String() from $asm.inputString1 \n" + "    $v2: String() from $asm.inputString2 \n" + "then\n" + "    String result = $v1+\" \"+$v2; \n" + "    modify($asm) {\n" + "       setResult(result),\n" + "       setApplied(true)\n" + "    };\n" + "    System.out.println(\"Result = \"+$asm.getResult());\n" + "end\n" + "";
    MasterModel master = new MasterModel("TestMaster");
    ApplyMathModel mathModel = new ApplyMathModel(1, "Math1", "add", 10, 10);
    ApplyStringModel stringModel = new ApplyStringModel(2, "String1", "concat", "hello", "world");
    master.addSubModel(mathModel);
    master.addSubModel(stringModel);
    KieBase kbase = new KieHelper().addContent(drl1, ResourceType.DRL).addContent(drl2, ResourceType.DRL).build();
    RuleUnitExecutor executor = RuleUnitExecutor.create().bind(kbase);
    DataSource<MasterModel> masterModels = executor.newDataSource("models");
    DataSource<ApplicableModel> applicableModels = executor.newDataSource("applicableModel");
    FactHandle masterFH = masterModels.insert(master);
    RuleUnit unit = new MasterModelUnit(masterModels, applicableModels);
    // int x = 1;
    // while (x > 0) {
    // x = executor.run( unit );
    // System.out.println( x );
    // // I'm reinserting the master model to reinforce its evaluation, as I said in our call this is necessary because
    // // the second level froms are made on plain lists which are not normally re-evaluated by from nodes (regardless of rule units).
    // // In theory also the update should be more correct and enough to reinforce this re-evaluation, but for some reason
    // // in this case is not working. I suspect we have a bug in our NotNode related to this specific case, but I'm still
    // // evaluating it. For now the insert should be good enough to allow you to make some progress on this.
    // // masterModels.update( masterFH, master, "subModels" );
    // masterModels.insert( master );
    // }
    executor.run(unit);
    assertEquals(20, (int) mathModel.getResult());
    assertEquals("hello world", stringModel.getResult());
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) KieHelper(org.kie.internal.utils.KieHelper) RuleUnitExecutor(org.kie.api.runtime.rule.RuleUnitExecutor) KieBase(org.kie.api.KieBase) RuleUnit(org.kie.api.runtime.rule.RuleUnit) Test(org.junit.Test)

Example 29 with FactHandle

use of org.kie.api.runtime.rule.FactHandle in project drools by kiegroup.

the class RuleUnitTest method testMultiLevelGuards.

@Test
public void testMultiLevelGuards() throws Exception {
    String drl1 = "package org.drools.compiler.integrationtests\n" + "unit " + getCanonicalSimpleName(Unit0.class) + "\n" + "import " + UnitA.class.getCanonicalName() + "\n" + "rule X when\n" + "    $b: /ds#Boolean\n" + "then\n" + "    Boolean b = $b;\n" + "    drools.guard( UnitA.class );\n" + "end";
    String drl2 = "package org.drools.compiler.integrationtests\n" + "unit " + getCanonicalSimpleName(UnitA.class) + "\n" + "import " + UnitB.class.getCanonicalName() + "\n" + "rule A when\n" + "    $s: /ds#String\n" + "then\n" + "    drools.guard( UnitB.class );" + "end";
    String drl3 = "package org.drools.compiler.integrationtests\n" + "unit " + getCanonicalSimpleName(UnitB.class) + "\n" + "import " + UnitB.class.getCanonicalName() + "\n" + "rule B when\n" + "    $i: /ds#Integer\n" + "then\n" + "    list.add($i);" + "end";
    KieBase kbase = new KieHelper().addContent(drl1, ResourceType.DRL).addContent(drl2, ResourceType.DRL).addContent(drl3, ResourceType.DRL).build();
    RuleUnitExecutor executor = RuleUnitExecutor.create().bind(kbase);
    DataSource<Object> ds = executor.newDataSource("ds");
    List<Integer> list = new ArrayList<>();
    executor.bindVariable("list", list);
    ds.insert(1);
    executor.run(Unit0.class);
    // all units are inactive
    assertEquals(0, list.size());
    FactHandle guardA = ds.insert(true);
    executor.run(Unit0.class);
    // UnitB still inactive
    assertEquals(0, list.size());
    FactHandle guardB = ds.insert("test");
    executor.run(Unit0.class);
    // all units are active
    assertEquals(1, list.size());
    // all units are active
    assertEquals(1, (int) list.get(0));
    list.clear();
    ds.insert(2);
    executor.run(Unit0.class);
    // all units are inactive
    assertEquals(1, list.size());
    // all units are active
    assertEquals(2, (int) list.get(0));
    list.clear();
    // retracting guard A deactivate unitA and in cascade unit B
    ds.delete(guardA);
    ds.insert(3);
    executor.run(Unit0.class);
    // all units are inactive
    assertEquals(0, list.size());
    // activating guard A reactivate unitA and in cascade unit B
    guardA = ds.insert(true);
    executor.run(Unit0.class);
    // all units are active
    assertEquals(1, list.size());
    list.clear();
}
Also used : InternalRuleUnitExecutor(org.drools.core.impl.InternalRuleUnitExecutor) RuleUnitExecutor(org.kie.api.runtime.rule.RuleUnitExecutor) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBase(org.kie.api.KieBase) ArrayList(java.util.ArrayList) KieHelper(org.kie.internal.utils.KieHelper) Test(org.junit.Test)

Example 30 with FactHandle

use of org.kie.api.runtime.rule.FactHandle in project drools by kiegroup.

the class SegmentCreationTest method testBranchCESingleSegment.

@Test
public void testBranchCESingleSegment() throws Exception {
    KieBase kbase = buildKnowledgeBase("   $a : A() \n" + "   if ( $a != null ) do[t1] \n" + "   B() \n");
    InternalWorkingMemory wm = ((InternalWorkingMemory) kbase.newKieSession());
    ObjectTypeNode aotn = getObjectTypeNode(kbase, LinkingTest.A.class);
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getObjectSinkPropagator().getSinks()[0];
    ConditionalBranchNode cen1Node = (ConditionalBranchNode) liaNode.getSinkPropagator().getSinks()[0];
    JoinNode bNode = (JoinNode) cen1Node.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn1 = (RuleTerminalNode) bNode.getSinkPropagator().getSinks()[0];
    FactHandle bFh = wm.insert(new LinkingTest.B());
    wm.flushPropagations();
    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory smem = liaMem.getSegmentMemory();
    assertEquals(1, smem.getAllLinkedMaskTest());
    // B links, but it will not trigger mask
    assertEquals(4, smem.getLinkedNodeMask());
    assertFalse(smem.isSegmentLinked());
    PathMemory pmem = (PathMemory) wm.getNodeMemory(rtn1);
    assertEquals(1, pmem.getAllLinkedMaskTest());
    assertEquals(0, pmem.getLinkedSegmentMask());
    assertFalse(pmem.isRuleLinked());
    wm.insert(new LinkingTest.A());
    wm.flushPropagations();
    // A links in segment
    assertEquals(5, smem.getLinkedNodeMask());
    assertTrue(smem.isSegmentLinked());
    assertEquals(1, pmem.getLinkedSegmentMask());
    assertTrue(pmem.isRuleLinked());
    // retract B does not unlink the rule
    wm.delete(bFh);
    wm.flushPropagations();
    assertEquals(1, pmem.getLinkedSegmentMask());
    assertTrue(pmem.isRuleLinked());
}
Also used : SegmentMemory(org.drools.core.reteoo.SegmentMemory) FactHandle(org.kie.api.runtime.rule.FactHandle) JoinNode(org.drools.core.reteoo.JoinNode) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) ConditionalBranchNode(org.drools.core.reteoo.ConditionalBranchNode) LiaNodeMemory(org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KieBase(org.kie.api.KieBase) LeftInputAdapterNode(org.drools.core.reteoo.LeftInputAdapterNode) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) PathMemory(org.drools.core.reteoo.PathMemory) Test(org.junit.Test)

Aggregations

FactHandle (org.kie.api.runtime.rule.FactHandle)650 Test (org.junit.Test)547 KieSession (org.kie.api.runtime.KieSession)506 KieBase (org.kie.api.KieBase)304 ArrayList (java.util.ArrayList)298 InternalFactHandle (org.drools.core.common.InternalFactHandle)192 List (java.util.List)165 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)119 StatelessKieSession (org.kie.api.runtime.StatelessKieSession)66 KieHelper (org.kie.internal.utils.KieHelper)50 Person (org.drools.modelcompiler.domain.Person)46 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)43 HashMap (java.util.HashMap)41 Person (org.drools.compiler.Person)41 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)39 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)39 Person (org.drools.mvel.compiler.Person)38 Ignore (org.junit.Ignore)36 Match (org.kie.api.runtime.rule.Match)36 Collection (java.util.Collection)34