Java Code Examples for org.drools.core.impl.InternalKnowledgeBase#newKieSession()

The following examples show how to use org.drools.core.impl.InternalKnowledgeBase#newKieSession() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CrossProductTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveIdentities() throws Exception {
    System.setProperty( "drools.removeIdentities",
                        "true" );
    try {
        InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
        kBase.addPackage( this.pkg );

        this.ksession = kBase.newKieSession();
        this.ksession.insert( "F1" );
        this.ksession.insert( "F2" );
        this.ksession.insert( "F3" );
        this.ksession.insert( "F4" );

        this.ksession.fireAllRules();

        // A full cross product is 16, this is just 12
        assertEquals( 12,
                      this.values.size() );
    } finally {
        System.setProperty( "drools.removeIdentities",
                            "false" );
    }
}
 
Example 2
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPopulatedMultipleShares() throws Exception {
    InternalKnowledgeBase kbase1 = buildKnowledgeBase("r1", "   A(1;)  A(2;) B(1;) B(2;) C(1;) D() E()\n" );
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase1.newKieSession());
    List list = new ArrayList();
    wm.setGlobal("list", list);

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new A(2));
    wm.insert(new A(3));
    wm.insert(new B(1));
    wm.insert(new B(2));
    wm.insert(new C(1));
    wm.insert(new C(2));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.fireAllRules();
    assertEquals( 2, list.size() );

    kbase1.addPackages( buildKnowledgePackage("r2", "   A(1;)  A(2;) B(1;) B(2;) C(2;) D() E()\n") );

    kbase1.addPackages( buildKnowledgePackage("r3", "   A(1;)  A(3;) B(1;) B(2;) C(2;) D() E()\n") );


    wm.fireAllRules();
    System.out.println(list);
    assertEquals( 5, list.size() );

    assertEquals("r1", ((Match) list.get(0)).getRule().getName());
    assertEquals( "r1", ((Match)list.get(1)).getRule().getName() );
    assertEquals( "r3", ((Match)list.get(2)).getRule().getName() ); // only one A3
    assertEquals( "r2", ((Match)list.get(3)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(4)).getRule().getName() );
}
 
Example 3
Source File: LazyTMSEnablingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    tms = ((NamedEntryPoint)ksession.getWorkingMemoryEntryPoint( EntryPointId.DEFAULT.getEntryPointId() ) ).getTruthMaintenanceSystem();

}
 
Example 4
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPopulatedSharedToRtn() throws Exception {
    InternalKnowledgeBase kbase1 = buildKnowledgeBase("r1", "   A() B() C() D() E()\n");
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase1.newKieSession());
    List list = new ArrayList();
    wm.setGlobal("list", list);

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new B(1));
    wm.insert(new C(1));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.fireAllRules();
    assertEquals( 2, list.size() );

    kbase1.addPackages( buildKnowledgePackage("r2", "   A() B() C() D() E()\n") );

    ObjectTypeNode eotn = getObjectTypeNode(kbase1, E.class );
    JoinNode eNode = (JoinNode) eotn.getObjectSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn = ( RuleTerminalNode ) eNode.getSinkPropagator().getLastLeftTupleSink();

    PathMemory pm = (PathMemory) wm.getNodeMemory(rtn);
    SegmentMemory sm = pm.getSegmentMemory();
    assertNotNull( sm.getStagedLeftTuples().getInsertFirst() );
    assertNotNull( sm.getStagedLeftTuples().getInsertFirst().getStagedNext() );
    assertNull( sm.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext() );

    wm.fireAllRules();
    assertNull( sm.getStagedLeftTuples().getInsertFirst() );
    assertEquals(4, list.size() );

    assertEquals("r1", ((Match) list.get(0)).getRule().getName());
    assertEquals( "r1", ((Match)list.get(1)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(2)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(3)).getRule().getName() );
}
 
Example 5
Source File: DynamicRuleRemovalTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicRuleRemoval() throws Exception {
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    addRule(kbase, "rule1");
    addRule(kbase, "rule2");
    addRule(kbase, "rule3");

    final KieSession ksession = kbase.newKieSession();
    List<String> rulesList = new ArrayList<String>();
    ksession.setGlobal("list", rulesList);

    ksession.insert("2");
    ksession.fireAllRules();
    assertEquals(3, rulesList.size());
    assertTrue(rulesList.contains("rule1"));
    assertTrue(rulesList.contains("rule2"));
    assertTrue(rulesList.contains("rule3"));

    removeRule(kbase, "rule1");

    rulesList.clear();
    ksession.insert("3");
    ksession.fireAllRules();
    assertEquals(2, rulesList.size());
    assertFalse(rulesList.contains("rule1"));
    assertTrue(rulesList.contains("rule2"));
    assertTrue(rulesList.contains("rule3"));
}
 
Example 6
Source File: ReteooWorkingMemoryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
@Disabled
public void testExecuteQueueActions() {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();
    final ReentrantAction action = new ReentrantAction();
    ksession.queueWorkingMemoryAction( action );
    ksession.flushPropagations();
    assertEquals( 2, action.counter.get() );
}
 
Example 7
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMVELTypeCoercion() {
    final String str = "package org.drools.compiler.test; \n" +
            "\n" +
            "global java.util.List list;" +
            "\n" +
            "declare Bean\n" +
            // NOTICE: THIS WORKS WHEN THE FIELD IS "LIST", BUT USED TO WORK WITH ARRAYLIST TOO
            "  field : java.util.ArrayList\n" +
            "end\n" +
            "\n" +
            "\n" +
            "rule \"Init\"\n" +
            "when  \n" +
            "then\n" +
            "  insert( new Bean( new java.util.ArrayList( java.util.Arrays.asList( \"x\" ) ) ) );\n" +
            "end\n" +
            "\n" +
            "rule \"Check\"\n" +
            "when\n" +
            "  $b : Bean( $fld : field == [\"x\"] )\n" +
            "then\n" +
            "  System.out.println( $fld );\n" +
            "  list.add( \"OK\" ); \n" +
            "end";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    final KieBaseConfiguration kbConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbConf.setOption(EqualityBehaviorOption.EQUALITY);
    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbConf);
    kbase.addPackages(kbuilder.getKnowledgePackages());
    final KieSession ksession = kbase.newKieSession();

    final List list = new ArrayList();
    ksession.setGlobal("list", list);

    ksession.fireAllRules();
    assertTrue(list.contains("OK"));

    ksession.dispose();
}
 
Example 8
Source File: DescrBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testAccumulate() throws InstantiationException,
        IllegalAccessException {

    PackageDescrBuilder packBuilder =
            DescrFactory.newPackage()
                    .newGlobal().identifier( "list" ).type( List.class.getName() ).end()
                    .name( "org.drools.compiler" )
                        .newRule().name( "r1" )
                            .lhs()
                                .pattern().id( "$tot", true ).type( Double.class.getName() ).end()
                                .accumulate().source().pattern().id( "$i", false ).type( Integer.class.getName() ).end().end()
                                    .function( "sum", "$tot", true, "$i" )
                                    .constraint( "$tot > 15" )
                            .end()
                        .end()
                        .rhs( "list.add( $tot );" )
                        .end()
                        .newRule().name( "r2" )
                            .attribute( "dialect", "mvel" )
                            .lhs()
                                .pattern().id( "$tot", true ).type( Double.class.getName() ).end()
                                .accumulate().source().pattern().id( "$i", false ).type( Integer.class.getName() ).end().end()
                                    .function( "sum", "$tot", true, "$i" )
                                    .constraint( "$tot > 15" )
                            .end()
                        .end()
                        .rhs( "list.add( $tot * 2 );" )
                    .end();

    String drl = new DrlDumper().dump( packBuilder.getDescr() );
    System.out.println(drl);

    KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    knowledgeBuilder.add( new ByteArrayResource( drl.getBytes() ), ResourceType.DRL );
    System.err.println( knowledgeBuilder.getErrors() );
    assertFalse(knowledgeBuilder.hasErrors() , knowledgeBuilder.getErrors().toString());


    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( knowledgeBuilder.getKnowledgePackages() );
    KieSession knowledgeSession = kbase.newKieSession();
    List list = new ArrayList();
    knowledgeSession.setGlobal( "list", list );

    knowledgeSession.insert( 3 );
    knowledgeSession.insert( 39 );
    knowledgeSession.insert( 24.0 );
    knowledgeSession.insert( 42.0 );

    knowledgeSession.fireAllRules();
    assertEquals( Arrays.asList( 42.0, 84.0 ), list );
}
 
Example 9
Source File: PhreakLiaNodeTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
    public void test() {
        String str = "package org.drools.compiler.test\n" +
                "\n" +
                "import " + A.class.getCanonicalName() + "\n" +
                "import " + B.class.getCanonicalName() + "\n" +
                "\n" +
                "rule r1 \n" +
                "    when \n" +
                "        $a : A( object == 1 )\n" +
                "    then \n" +
                "        System.out.println( $a ); \n" +
                "end \n" +
                "rule r2 \n" +
                "    when \n" +
                "        $a : A( object == 2 )\n" +
                "    then \n" +
                "        System.out.println( $a ); \n" +
                "end \n " +
                "rule r3 \n" +
                "    when \n" +
                "        $a : A( object == 2 )\n" +
                "        $b : B( )\n" +
                "    then \n" +
                "        System.out.println( $a ); \n" +
                "end \n " +                
                "rule r4 \n" +
                "    when \n" +
                "        $a : A( object == 3 )\n" +
                "    then \n" +
                "        System.out.println( $a ); \n" +
                "end \n";
                
        KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();

        builder.add( ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

        if ( builder.hasErrors() ) {
            throw new RuntimeException(builder.getErrors().toString());
        }
        
        InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addPackages(builder.getKnowledgePackages());

        KieSession ksession = knowledgeBase.newKieSession();

        InternalFactHandle fhB = ( InternalFactHandle ) ksession.insert( B.b(1) );
        
        InternalFactHandle fhA = ( InternalFactHandle ) ksession.insert( A.a(1) );
        ksession.fireAllRules();        
        System.out.println( "---1---" );
        
//        ksession.update( fhA, a(1) );
//        ksession.fireAllRules();
//        System.out.println( "---2---" );
//
        ksession.update( fhA, A.a(2) );
        ksession.fireAllRules(); 
        System.out.println( "---3---" );

        ksession.update( fhA, A.a(2) );
        ksession.fireAllRules();
        System.out.println( "---4---" );
        
        ksession.update( fhA, A.a(3) );
        ksession.fireAllRules(); 
        System.out.println( "---5---" );
        
        ksession.update( fhB, B.b(1) );

        ksession.update( fhA, A.a(3) );
        ksession.fireAllRules();  
        
//        ksession.update( fhA, a(1) );
//        ksession.fireAllRules();        
//
//        ksession.update( fhA, a(1) );
//        ksession.fireAllRules();          
        
        ksession.dispose();        
    }
 
Example 10
Source File: RuleExtensionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testRuleExtendsBetweenDRLs() {
    // DROOLS-100
    String str =
            "package org.drools.test;\n" +
                    "\n" +
                    "global java.util.List list;\n" +
                    "\n" +
                    "rule \"Base\"\n" +
                    "when\n" +
                    "  String( this == \"go\" )\n" +
                    "then\n" +
                    "end\n" +
                    "";

    String str2 =
            "package org.drools.test;\n" +
                    "\n" +
                    "rule \"ExtYes\" extends \"Base\"\n" +
                    "when\n" +
                    "then\n" +
                    "  list.add( 1 );\n" +
                    "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), ResourceType.DRL );
    kbuilder.add( ResourceFactory.newByteArrayResource( str2.getBytes() ), ResourceType.DRL );
    assertFalse(kbuilder.hasErrors());

    InternalKnowledgeBase kb = KnowledgeBaseFactory.newKnowledgeBase();
    kb.addPackages( kbuilder.getKnowledgePackages() );

    KieSession knowledgeSession = kb.newKieSession();

    List list = new ArrayList();
    knowledgeSession.setGlobal( "list", list );

    knowledgeSession.fireAllRules();
    assertEquals(0, list.size());

    knowledgeSession.insert( "go" );
    knowledgeSession.fireAllRules();

    assertEquals( 1, list.size() );
}
 
Example 11
Source File: LinkingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testNotNodeMasksWithoutConstraints() throws Exception {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n" ;
    str += "import " + B.class.getCanonicalName() + "\n" ;
    str += "import " + C.class.getCanonicalName() + "\n" ;
    str += "import " + D.class.getCanonicalName() + "\n" ;
    str += "import " + E.class.getCanonicalName() + "\n" ;
    str += "import " + F.class.getCanonicalName() + "\n" ;
    str += "import " + G.class.getCanonicalName() + "\n" ;
    str += "global java.util.List list \n";

    str += "rule rule1 when \n";
    str += "   A() \n";
    str += "   not( B( ) ) \n";
    str += "   C() \n";
    str += "then \n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
                  ResourceType.DRL );

    assertFalse( kbuilder.hasErrors(), kbuilder.getErrors().toString());

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );

    ObjectTypeNode node = getObjectTypeNode(kbase, A.class );
    InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl)kbase.newKieSession());

    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) node.getObjectSinkPropagator().getSinks()[0];
    assertEquals( 1, liaNode.getSinkPropagator().size() );

    wm.insert( new A() );
    wm.flushPropagations();

    NotNode notNode = ( NotNode) liaNode.getSinkPropagator().getSinks()[0];
    JoinNode cNode = ( JoinNode) notNode.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn = ( RuleTerminalNode ) cNode.getSinkPropagator().getSinks()[0];

    PathMemory pmem =  ( PathMemory ) wm.getNodeMemory(rtn);
    assertEquals( 1, pmem.getSegmentMemories().length );
    assertEquals( 1, pmem.getAllLinkedMaskTest() );

    SegmentMemory sm = pmem.getSegmentMemories()[0];
    assertEquals( 7, sm.getAllLinkedMaskTest() );

    assertEquals( 3, sm.getLinkedNodeMask() );
    assertFalse( sm.isSegmentLinked() );
    assertFalse( pmem.isRuleLinked() );

    wm.insert( new C() );
    wm.flushPropagations();
    assertEquals( 7, sm.getLinkedNodeMask() );
    assertTrue( sm.isSegmentLinked() );
    assertTrue( pmem.isRuleLinked() );
}
 
Example 12
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testUndoRule() throws Exception {
    String rule = "package org.drools.compiler.test\n" +
                  "global java.util.List list\n" +
                  "import org.drools.compiler.test.FactA\n" +
                  "import org.drools.compiler.test.FactB\n" +
                  "rule R1 when\n" +
                  "   FactA( j == 1 )\n" +
                  "   FactB( i == 1 )\n" +
                  "then\n" +
                  "   list.add(\"OK\");" +
                  "end\n";

    String declarationA = "package org.drools.compiler.test\n" +
                          "declare FactA\n" +
                          "    i : int\n" +
                          "end\n";

    String declarationB = "package org.drools.compiler.test\n" +
                          "declare FactB\n" +
                          "    i : int\n" +
                          "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( declarationB.getBytes() ), ResourceType.DRL );
    kbuilder.add( ResourceFactory.newByteArrayResource( declarationA.getBytes() ), ResourceType.DRL );
    assertFalse( kbuilder.hasErrors() );

    kbuilder.batch()
            .type( ResourceType.DRL )
            .add( ResourceFactory.newByteArrayResource( rule.getBytes() ) )
            .build();

    assertTrue( kbuilder.hasErrors() );
    kbuilder.undo();
    assertFalse( kbuilder.hasErrors() );

    rule = "package org.drools.compiler.test\n" +
           "global java.util.List list\n" +
           "import org.drools.compiler.test.FactA\n" +
           "import org.drools.compiler.test.FactB\n" +
           "rule R1 when\n" +
           "   FactA( i == 1 )\n" +
           "   FactB( i == 1 )\n" +
           "then\n" +
           "   list.add(\"OK\");" +
           "end\n";

    kbuilder.batch()
            .type( ResourceType.DRL )
            .add( ResourceFactory.newByteArrayResource( rule.getBytes() ) )
            .add( ResourceFactory.newByteArrayResource( declarationA.getBytes() ) )
            .build();

    assertFalse( kbuilder.hasErrors() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = kbase.newKieSession();

    List list = new ArrayList();
    ksession.setGlobal( "list", list );

    FactType aType = kbase.getFactType( "org.drools.compiler.test", "FactA" );
    Object a = aType.newInstance();
    aType.set( a, "i", 1 );

    FactType bType = kbase.getFactType( "org.drools.compiler.test", "FactB" );
    Object b = bType.newInstance();
    bType.set( b, "i", 1 );

    ksession.insert( a );
    ksession.insert( b );

    int rules = ksession.fireAllRules();
    assertEquals( 1, rules );
    assertEquals( "OK", list.get( 0 ) );
}
 
Example 13
Source File: RemoveRuleTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testPopulatedMultipleSharesRemoveMid() throws Exception {
    InternalKnowledgeBase kbase1 = buildKnowledgeBase("r1", "   A(1;)  A(2;) B(1;) B(2;) C(1;) D() E()\n" );
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase1.newKieSession());
    List list = new ArrayList();
    wm.setGlobal("list", list);

    InternalFactHandle fh1 = ( InternalFactHandle ) wm.insert(new A(1));
    InternalFactHandle fh2 = ( InternalFactHandle ) wm.insert(new A(2));
    InternalFactHandle fh3 = ( InternalFactHandle ) wm.insert(new A(2));
    InternalFactHandle fh4 = ( InternalFactHandle ) wm.insert(new A(3));
    InternalFactHandle fh5 =  (InternalFactHandle) wm.insert(new B(1));
    InternalFactHandle fh6 =  (InternalFactHandle) wm.insert(new B(2));
    InternalFactHandle fh7 =  (InternalFactHandle) wm.insert(new C(1));
    InternalFactHandle fh8 =  (InternalFactHandle) wm.insert(new C(2));
    InternalFactHandle fh9 =  (InternalFactHandle) wm.insert(new D(1));
    InternalFactHandle fh10 =  (InternalFactHandle) wm.insert(new E(1));

    wm.fireAllRules();
    assertEquals( 2, list.size() );

    kbase1.addPackages( buildKnowledgePackage("r2", "   A(1;)  A(2;) B(1;) B(2;) C(2;) D() E()\n") );
    kbase1.addPackages( buildKnowledgePackage("r3", "   A(1;)  A(3;) B(1;) B(2;) C(2;) D() E()\n") );

    wm.fireAllRules();
    assertEquals( 5, list.size() );


    kbase1.removeRule("org.kie", "r2");
    list.clear();

    wm.update( fh1, fh1.getObject() );
    wm.update( fh2, fh2.getObject() );
    wm.update( fh3, fh3.getObject() );
    wm.update( fh4, fh4.getObject() );
    wm.update( fh5, fh5.getObject() );
    wm.update( fh6, fh6.getObject() );
    wm.update( fh7, fh7.getObject() );
    wm.update( fh8, fh8.getObject() );
    wm.update( fh9, fh9.getObject() );
    wm.update( fh10, fh10.getObject() );

    wm.fireAllRules();
    assertEquals( 3, list.size() );
}
 
Example 14
Source File: ReteooWorkingMemoryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled
public void testBasicWorkingMemoryActions() {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    final TruthMaintenanceSystem tms = ((NamedEntryPoint)ksession.getWorkingMemoryEntryPoint(EntryPointId.DEFAULT.getEntryPointId()) ).getTruthMaintenanceSystem();
    final String string = "test";

    FactHandle fd = ksession.insert( string );

    FactHandle fz = ksession.getTruthMaintenanceSystem().insert( string, null, null, new MockActivation() );

    assertEquals( 1,
                  tms.getEqualityKeyMap().size() );

    EqualityKey key = tms.get( string );
    assertSame( fz,
                key.getFactHandle() );
    assertEquals( 2, key.size() );

    ksession.update( fd, string );

    assertEquals( 1,
                  tms.getEqualityKeyMap().size() );
    key = tms.get( string );
    assertSame( fz,
                key.getFactHandle() );
    assertEquals( 2, key.size() );

    ksession.retract( fd );

    assertEquals( 1,
                  tms.getEqualityKeyMap().size() );
    key = tms.get( string );

    fd = ksession.insert( string );

    assertEquals( 1,
                  tms.getEqualityKeyMap().size() );

    assertEquals( 1,
                  tms.getEqualityKeyMap().size() );
    key = tms.get( string );
    assertSame( fd,
                key.getFactHandle() );
    assertEquals( 1, key.size() );
}
 
Example 15
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testPopulatedSingleRuleNoSharingWithSubnetworkAtStart() throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase.newKieSession());

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.insert(new C(2));
    wm.fireAllRules();


    kbase.addPackages( buildKnowledgePackage("r1", "   A() not( B() and C() ) D() E()\n") );
    List list = new ArrayList();
    wm.setGlobal("list", list);

    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class );
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getObjectSinkPropagator().getSinks()[0];

    LiaNodeMemory lm = ( LiaNodeMemory ) wm.getNodeMemory(liaNode);
    SegmentMemory sm = lm.getSegmentMemory();
    assertNull( sm.getStagedLeftTuples().getInsertFirst() );

    SegmentMemory subSm = sm.getFirst();
    SegmentMemory mainSm = subSm.getNext();


    assertNotNull( subSm.getStagedLeftTuples().getInsertFirst() );
    assertNotNull( subSm.getStagedLeftTuples().getInsertFirst().getStagedNext() );
    assertNull( subSm.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext() );
    assertNotNull( mainSm.getStagedLeftTuples().getInsertFirst() );
    assertNotNull( mainSm.getStagedLeftTuples().getInsertFirst().getStagedNext() );
    assertNull( mainSm.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext() );

    wm.fireAllRules();
    assertNull(subSm.getStagedLeftTuples().getInsertFirst());
    assertNull(mainSm.getStagedLeftTuples().getInsertFirst());
    assertEquals(2, list.size() );

    assertEquals( "r1", ((Match)list.get(0)).getRule().getName() );
}
 
Example 16
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSerializable() throws Exception {
    final KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();

    final PackageDescr packageDescr = new PackageDescr( "p1" );
    final RuleDescr ruleDescr = new RuleDescr( "rule-1" );
    packageDescr.addRule( ruleDescr );

    final AndDescr lhs = new AndDescr();
    ruleDescr.setLhs( lhs );

    packageDescr.addGlobal( new GlobalDescr( "map",
                                             "java.util.Map" ) );

    ruleDescr.setConsequence( "map.put(\"value\", new Integer(1) );" );
    //check that packageDescr is serializable
    final PackageDescr back = (PackageDescr) SerializationHelper.serializeObject( packageDescr );
    assertNotNull( back );
    assertEquals( "p1",
                  back.getName() );

    builder.addPackage( packageDescr );
    InternalKnowledgePackage pkg = builder.getPackage(packageDescr.getName());
    final RuleImpl rule = pkg.getRule( "rule-1" );

    assertThat((Object[]) builder.getErrors().getErrors()).hasSize(0);

    InternalKnowledgePackage newPkg = SerializationHelper.serializeObject( pkg );
    final RuleImpl newRule = newPkg.getRule( "rule-1" );

    InternalKnowledgeBase kBase = (InternalKnowledgeBase)KnowledgeBaseFactory.newKnowledgeBase();

    // It's been serialised so we have to simulate the re-wiring process
    newPkg.getDialectRuntimeRegistry().onAdd( kBase.getRootClassLoader() );
    newPkg.getDialectRuntimeRegistry().onBeforeExecute();

    kBase.getGlobals().put( "map", Map.class );
    final KieSession workingMemory = kBase.newKieSession();

    final HashMap map = new HashMap();

    workingMemory.setGlobal( "map",
                             map );

    final LeftTupleImpl tuple = new MockTuple( new HashMap() );
    tuple.setLeftTupleSink( new RuleTerminalNode(1, new CompositeObjectSinkAdapterTest.MockBetaNode(), newRule,newRule.getLhs(), 0, new BuildContext(kBase) )  );
    final Activation activation = new MockActivation( newRule,
                                                      0,
                                                      newRule.getLhs(),
                                                      tuple );

    final DefaultKnowledgeHelper knowledgeHelper = new org.drools.core.base.DefaultKnowledgeHelper( ((StatefulKnowledgeSessionImpl)workingMemory) );
    knowledgeHelper.setActivation( activation );

    newRule.getConsequence().evaluate( knowledgeHelper,
                                       ((StatefulKnowledgeSessionImpl)workingMemory) );
    assertEquals( new Integer( 1 ),
                  map.get( "value" ) );
}
 
Example 17
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testPopulatedRuleWithEvals() throws Exception {
    InternalKnowledgeBase kbase1 = buildKnowledgeBase("r1", "   a:A() B() eval(1==1) eval(1==1) C(1;) \n");
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase1.newKieSession());
    List list = new ArrayList();
    wm.setGlobal("list", list);

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new A(3));
    wm.insert(new B(1));
    wm.insert(new C(1));
    wm.insert(new C(2));

    wm.fireAllRules();
    assertEquals( 3, list.size() );

    kbase1.addPackages( buildKnowledgePackage("r2", "   a:A() B() eval(1==1) eval(1==1) C(2;) \n") );

    ObjectTypeNode aotn = getObjectTypeNode(kbase1, A.class );
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getObjectSinkPropagator().getSinks()[0];
    JoinNode bNode = (JoinNode) liaNode.getSinkPropagator().getFirstLeftTupleSink();

    EvalConditionNode e1 = (EvalConditionNode) bNode.getSinkPropagator().getFirstLeftTupleSink();
    EvalConditionNode e2 = (EvalConditionNode) e1.getSinkPropagator().getFirstLeftTupleSink();

    JoinNode c1Node = (JoinNode) e2.getSinkPropagator().getFirstLeftTupleSink();
    JoinNode c2Node = (JoinNode) e2.getSinkPropagator().getLastLeftTupleSink();

    LiaNodeMemory lm = ( LiaNodeMemory ) wm.getNodeMemory(liaNode);
    SegmentMemory sm = lm.getSegmentMemory();

    BetaMemory c1Mem = ( BetaMemory ) wm.getNodeMemory(c1Node);
    assertSame( sm.getFirst(), c1Mem.getSegmentMemory());
    assertEquals( 3, c1Mem.getLeftTupleMemory().size() );
    assertEquals( 1, c1Mem.getRightTupleMemory().size() );

    BetaMemory c2Mem = ( BetaMemory ) wm.getNodeMemory(c2Node);
    SegmentMemory c2Smem =  sm.getFirst().getNext();
    assertSame( c2Smem, c2Mem.getSegmentMemory());
    assertEquals( 0, c2Mem.getLeftTupleMemory().size() );
    assertEquals( 0, c2Mem.getRightTupleMemory().size() );
    assertNotNull( c2Smem.getStagedLeftTuples().getInsertFirst() );
    assertNotNull( c2Smem.getStagedLeftTuples().getInsertFirst().getStagedNext() );
    assertNotNull( c2Smem.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext() );
    assertNull( c2Smem.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext().getStagedNext() );

    wm.fireAllRules();
    assertEquals( 3, c2Mem.getLeftTupleMemory().size() );
    assertEquals( 1, c2Mem.getRightTupleMemory().size() );
    assertNull( c2Smem.getStagedLeftTuples().getInsertFirst() );
    assertEquals(6, list.size() );

    assertEquals( "r1", ((Match)list.get(0)).getRule().getName() );
    assertEquals( "r1", ((Match)list.get(1)).getRule().getName() );
    assertEquals( "r1", ((Match)list.get(2)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(3)).getRule().getName() );
    assertEquals( 3, ((A)((Match)list.get(3)).getDeclarationValue("a")).getObject() );
    assertEquals( "r2", ((Match)list.get(4)).getRule().getName() );
    assertEquals( 2, ((A)((Match)list.get(4)).getDeclarationValue("a")).getObject() );
    assertEquals( "r2", ((Match)list.get(5)).getRule().getName() );
    assertEquals( 1, ((A)((Match)list.get(5)).getDeclarationValue("a")).getObject() );
}
 
Example 18
Source File: MVELActionBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSimpleAction() throws Exception {
    final InternalKnowledgePackage pkg = new KnowledgePackageImpl( "pkg1" );

    ActionDescr actionDescr = new ActionDescr();
    actionDescr.setText( "list.add( 'hello world' )" );       

    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl( pkg );
    DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry( pkg.getName() ).getDialectCompiletimeRegistry();
    MVELDialect mvelDialect = ( MVELDialect ) dialectRegistry.getDialect( "mvel" );

    PackageBuildContext context = new PackageBuildContext();
    context.init( pkgBuilder, pkg, null, dialectRegistry, mvelDialect, null);
    
    pkgBuilder.addPackageFromDrl( new StringReader("package pkg1;\nglobal java.util.List list;\n") );        
    
    ActionNode actionNode = new ActionNode();
    DroolsAction action = new DroolsConsequenceAction("mvel", null);
    actionNode.setAction(action);
    
    final MVELActionBuilder builder = new MVELActionBuilder();
    builder.build( context,
                   action,
                   actionDescr,
                   actionNode );

    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( Arrays.asList(pkgBuilder.getPackages()) );
    final KieSession wm = kbase.newKieSession();

    List<String> list = new  ArrayList<String>();
    wm.setGlobal( "list", list );     
    
    MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkgBuilder.getPackage("pkg1").getDialectRuntimeRegistry().getDialectData( "mvel");
    
    ((MVELAction) actionNode.getAction().getMetaData("Action")).compile( data );
    
    ProcessContext processContext = new ProcessContext( ((InternalWorkingMemory) wm).getKnowledgeRuntime() );
    ((Action) actionNode.getAction().getMetaData("Action")).execute( processContext );
    
    assertEquals("hello world", list.get(0) );
}
 
Example 19
Source File: LogicalTraitTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@ParameterizedLogicalTraitTest
public void testShadowAliasTraitOnClass(VirtualPropertyMode mode) {

    String drl = "package org.drools.test; \n" +
            "import org.drools.core.factmodel.traits.*; \n" +
            "import org.drools.core.factmodel.traits.Trait; \n" +
            "" +
            "global java.util.List list; \n" +
            "" +
            "declare trait X \n" +
            "  fld : T \n" +
            "end \n" +
            "" +
            "declare Y \n" +
            "@Traitable( logical = true ) \n" +
            "  fld : K \n" +
            "end \n" +
            "" +
            "declare trait T @Trait( logical=true ) end \n" +
            "declare K @Traitable() end \n" +
            "" +
            "rule Don \n" +
            "when \n" +
            "then \n" +
            "  Y y = new Y( new K() ); \n" +
            "  don( y, X.class ); \n" +
            "end \n" +
            "" +
            "rule Check \n" +
            "when \n" +
            "  X( fld isA T ) \n" +
            "then \n" +
            "  list.add( \"ok\" );" +
            "end \n";

    KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilderImpl.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilderImpl.hasErrors()) {
        fail(kbuilderImpl.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilderImpl.getKnowledgePackages());

    TraitFactory.setMode(mode, kbase);

    KieSession ks = kbase.newKieSession();
    ArrayList list = new ArrayList();
    ks.setGlobal("list", list);

    ks.fireAllRules();
    for (Object o : ks.getObjects()) {
        System.out.println(o);
    }
    assertEquals(Arrays.asList("ok"), list);

    try {
        ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 20
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testPopulatedSharedLiaNode() throws Exception {
    InternalKnowledgeBase kbase1 = buildKnowledgeBase("r1", "   A() B(1;) C() D() E()\n");
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase1.newKieSession());
    List list = new ArrayList();
    wm.setGlobal("list", list);

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new A(3));
    wm.insert(new B(1));
    wm.insert(new B(2));
    wm.insert(new C(1));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.fireAllRules();
    assertEquals( 3, list.size() );

    kbase1.addPackages( buildKnowledgePackage("r2", "   a : A() B(2;) C() D() E()\n") );

    ObjectTypeNode aotn = getObjectTypeNode(kbase1, A.class );
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getObjectSinkPropagator().getSinks()[0];
    JoinNode bNode1 = (JoinNode) liaNode.getSinkPropagator().getFirstLeftTupleSink();
    JoinNode bNode2 = (JoinNode) liaNode.getSinkPropagator().getLastLeftTupleSink();

    BetaMemory bm = ( BetaMemory ) wm.getNodeMemory(bNode2);
    SegmentMemory sm = bm.getSegmentMemory();
    assertNotNull( sm.getStagedLeftTuples().getInsertFirst() );
    assertNotNull( sm.getStagedLeftTuples().getInsertFirst().getStagedNext() );
    assertNotNull( sm.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext() );
    assertNull( sm.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext().getStagedNext() );

    wm.fireAllRules();
    assertNull( sm.getStagedLeftTuples().getInsertFirst() );
    assertEquals(6, list.size() );

    assertEquals( "r1", ((Match)list.get(0)).getRule().getName() );
    assertEquals( "r1", ((Match)list.get(1)).getRule().getName() );
    assertEquals( "r1", ((Match)list.get(2)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(3)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(4)).getRule().getName() );
    assertEquals( "r2", ((Match)list.get(5)).getRule().getName() );

    List results = new ArrayList();
    results.add(((A)((Match)list.get(3)).getDeclarationValue("a")).getObject());
    results.add(((A)((Match)list.get(4)).getDeclarationValue("a")).getObject());
    results.add(((A)((Match)list.get(5)).getDeclarationValue("a")).getObject());
    assertTrue(results.containsAll(asList(1, 2, 3)));
}