Java Code Examples for org.drools.core.impl.KnowledgeBaseFactory#newKnowledgeBase()

The following examples show how to use org.drools.core.impl.KnowledgeBaseFactory#newKnowledgeBase() . 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: JTMSTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromFile( String ruleFile ) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add( ResourceFactory.newClassPathResource( ruleFile, getClass() ),
            ResourceType.DRL );
    if ( kBuilder.hasErrors() ) {
        System.err.println( kBuilder.getErrors() );
        fail();
    }

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase( );
    kBase.addPackages( kBuilder.getKnowledgePackages() );

    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.JTMS );
    
    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example 3
Source File: CrossProductTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotRemoveIdentities() throws Exception {
    // Default is remove identity FALSE
    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
    System.out.println(values);
    assertEquals( 16,
                  this.values.size() );
}
 
Example 4
Source File: TypeDeclarationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypeDeclarationWithInnerClassesImport() {
    // DROOLS-150
    String str = "";
    str += "package org.drools.compiler;\n" +
           "\n" +
           "import org.drools.compiler.compiler.TypeDeclarationTest.EventBar.Foo;\n" +
           "" +
           "declare Foo\n" +
           " @role( event )\n" +
           "end\n" +
           "" +
           "rule R when Foo() then end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
                  ResourceType.DRL );
    System.err.println( kbuilder.getErrors() );
    assertFalse( kbuilder.hasErrors() );

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    kBase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession knowledgeSession = kBase.newKieSession();
    FactHandle handle = knowledgeSession.insert( new EventBar.Foo() );

    assertTrue( handle instanceof EventFactHandle );

}
 
Example 5
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogicalInsertionsLoop() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_LogicalInsertionsLoop.drl",
                                                        getClass() ),
                  ResourceType.DRL );
    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kpkgs );
    kbase = SerializationHelper.serializeObject(kbase);
    final KieSession session = createKnowledgeSession(kbase);
    try {
        final List l = new ArrayList();
        final Person a = new Person( "a" );
        session.setGlobal( "a",
                           a );
        session.setGlobal( "l",
                           l );

        session.fireAllRules();
        Collection< ? > list = session.getObjects( new ClassObjectFilter( a.getClass() ) );
        assertEquals(0, list.size(), "a still asserted.");
        assertEquals(10, l.size(), "Rule has not fired (looped) expected number of times");
    } finally {
        session.dispose();
    }
}
 
Example 6
Source File: FirstOrderLogicTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrWithVariableResolution2() throws Exception {
    //        KieBase kbase = loadKnowledgeBase( "test_OrCEFollowedByMultipleEval.drl");
    //        KieSession workingMemory = createKnowledgeSession(kbase);

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_OrCEFollowedByMultipleEval2.drl",
                                                        FirstOrderLogicTest.class ),
                  ResourceType.DRL );

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

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

    final KieSession ksession = createKnowledgeSession(kbase);

    final AgendaEventListener al = mock( AgendaEventListener.class );
    ksession.addEventListener( al );

    ksession.insert( new FactA( "a" ) );
    ksession.insert( new FactB( "b" ) );
    ksession.insert( new FactC( "c" ) );

    ksession.fireAllRules();
    verify( al,
            times( 8 ) ).afterMatchFired(any(AfterMatchFiredEvent.class));
}
 
Example 7
Source File: RuleExtensionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRuleExtendsMissingOnIncrementalKB() {
    // 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" +
                    "global java.util.List list;\n" +
                    "\n" +
                    "rule \"ExtYes\" extends \"Bse\"\n" +
                    "when\n" +
                    "then\n" +
                    "  list.add( 1 );\n" +
                    "end\n";

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

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

    KnowledgeBuilder kbuilder2 = KnowledgeBuilderFactory.newKnowledgeBuilder( kb );
    kbuilder2.add( ResourceFactory.newByteArrayResource( str2.getBytes() ), ResourceType.DRL );
    assertTrue(kbuilder2.hasErrors());
}
 
Example 8
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPopulatedSingleRuleNoSharing() throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase.newKieSession());

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

    wm.fireAllRules();


    kbase.addPackages( buildKnowledgePackage("r1", "   A() B() C(object == 2) 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();
    assertNotNull(sm.getStagedLeftTuples().getInsertFirst());

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

    assertEquals( "r1", ((Match)list.get(0)).getRule().getName() );
}
 
Example 9
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testTMSwithQueries() {
    String str =""+
            "package org.drools.compiler.test;\n" +
            "\n" +
            "global java.util.List list; \n" +
            "\n" +
            "declare Bean\n" +
            "    str : String\n" +
            "end\n" +
            "\n" +
            "query bean ( String $s )\n" +
            "    Bean(  $s ; )\n" +
            "end\n" +
            "\n" +
            "\n" +
            "rule \"init\"\n" +
            "when\n" +
            "then\n" +
            "    insert( new Bean(\"AAA\") );\n" +
            "    insert( \"x\" );\n" +
            "end\n" +
            "\n" +
            "rule \"LogicIn\"\n" +
            "when\n" +
            "    String( this == \"x\" )\n" +
            "    ?bean(  \"AAA\" ; )\n" +
            "then\n" +
            "    insertLogical(\"y\");\n" +
            "    retract(\"x\");\n" +
            "end " +
            "\n" +
            "rule \"Never\"\n" +
            "salience -999\n" +
            "when\n" +
            "    $s : String( this == \"y\" )\n" +
            "then\n" +
            "    list.add($s);\n" +
            "end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()),
            ResourceType.DRL );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession kSession = createKnowledgeSession(kbase);
    try {
        List list = new ArrayList();
        kSession.setGlobal("list",list);


        kSession.fireAllRules();
        assertEquals(0, list.size());
    } finally {
        kSession.dispose();
    }
}
 
Example 10
Source File: NodeSegmentUnlinkingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSingleNodeinSegment() {

    rule1 = new RuleImpl( "rule1" );
    rule2 = new RuleImpl( "rule2" );
    rule3 = new RuleImpl( "rule3" );

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    BuildContext buildContext = new BuildContext( kBase );

    MockObjectSource mockObjectSource = new MockObjectSource( 8 );
    MockTupleSource mockTupleSource = new MockTupleSource( 9 );

    // n2 is only node in it's segment
    ObjectTypeNode otn = new ObjectTypeNode( 2, null, new ClassObjectType( String.class ), buildContext );
    BetaNode n1 = new JoinNode( 10, new LeftInputAdapterNode(3, otn, buildContext ), mockObjectSource,
                                new EmptyBetaConstraints(), buildContext );
    BetaNode n2 = new JoinNode( 11, n1, mockObjectSource,
                                new EmptyBetaConstraints(), buildContext );
    BetaNode n3 = new JoinNode( 12, n1, mockObjectSource,
                                new EmptyBetaConstraints(), buildContext );
    BetaNode n4 = new JoinNode( 13, n2, mockObjectSource,
                                new EmptyBetaConstraints(), buildContext );
    BetaNode n5 = new JoinNode( 14, n2, mockObjectSource,
                                new EmptyBetaConstraints(), buildContext );

    n1.addAssociation( rule1 );
    n1.addAssociation( rule2 );
    n1.addAssociation( rule3 );

    n2.addAssociation( rule2 );
    n2.addAssociation( rule3 );

    n3.addAssociation( rule1 );
    n4.addAssociation( rule2 );
    n5.addAssociation( rule3 );

    mockObjectSource.attach(buildContext);
    mockTupleSource.attach(buildContext);
    n1.attach(buildContext);
    n2.attach(buildContext);
    n3.attach(buildContext);
    n4.attach(buildContext);
    n5.attach(buildContext);

    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();
    createSegmentMemory( n2, ksession );

    BetaMemory bm = (BetaMemory) ksession.getNodeMemory( n1 );
    assertNull( bm.getSegmentMemory() );

    bm = (BetaMemory) ksession.getNodeMemory( n3 );
    assertNull( bm.getSegmentMemory() );

    bm = (BetaMemory) ksession.getNodeMemory( n4 );
    assertNull( bm.getSegmentMemory() );

    bm = (BetaMemory) ksession.getNodeMemory( n2 );
    assertEquals( 1, bm.getNodePosMaskBit() );
    assertEquals( 1, bm.getSegmentMemory().getAllLinkedMaskTest() );
}
 
Example 11
Source File: SessionInspectorTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetSessionInfo() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "org/drools/compiler/integrationtests/test_SubNetworks.drl" ),
                  ResourceType.DRL );
    kbuilder.add( ResourceFactory.newClassPathResource("org/drools/compiler/integrationtests/test_AccumulateWithFromChaining.drl"),
                  ResourceType.DRL );
    kbuilder.add( ResourceFactory.newClassPathResource( "org/drools/compiler/integrationtests/test_CollectResultsBetaConstraint.drl" ),
                  ResourceType.DRL );
    kbuilder.add( ResourceFactory.newClassPathResource( "org/drools/compiler/integrationtests/test_QueryMemoryLeak.drl" ),
                  ResourceType.DRL );

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

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    
    KieSession ksession = createKnowledgeSession(kbase);
    ksession.setGlobal( "results", new ArrayList<Object>() );
    
    ksession.insert( new Dimension( 100, 50 ) );
    ksession.insert( new Dimension( 130, 80 ) );
    ksession.insert( new Dimension( 50, 40 ) );
    ksession.insert( new Dimension( 50, 40 ) );
    Cheesery cheesery = new Cheesery();
    cheesery.addCheese( new Cheese( "brie", 10 ));
    cheesery.addCheese( new Cheese( "brie", 10 ));
    cheesery.addCheese( new Cheese( "brie", 10 ));
    cheesery.addCheese( new Cheese( "brie", 10 ));
    cheesery.addCheese( new Cheese( "muzzarella", 10 ));
    cheesery.addCheese( new Cheese( "muzzarella", 10 ));
    cheesery.addCheese( new Cheese( "muzzarella", 10 ));
    cheesery.addCheese( new Cheese( "muzzarella", 10 ));
    cheesery.addCheese( new Cheese( "muzzarella", 10 ));
    cheesery.addCheese( new Cheese( "muzzarella", 10 ));
    cheesery.addCheese( new Cheese( "muzzarella", 10 ));
    cheesery.addCheese( new Cheese( "stilton", 10 ));
    cheesery.addCheese( new Cheese( "stilton", 10 ));
    cheesery.addCheese( new Cheese( "stilton", 10 ));
    cheesery.addCheese( new Cheese( "stilton", 10 ));
    cheesery.addCheese( new Cheese( "stilton", 10 ));
    cheesery.addCheese( new Cheese( "stilton", 10 ));
    cheesery.addCheese( new Cheese( "stilton", 10 ));
    ksession.insert( cheesery );
    ksession.insert( new Person( "Bob", "muzzarella") );
    ksession.insert( new Person( "Mark", "brie") );
    ksession.insert( new Cheese( "brie", 10 ) );
    ksession.insert( new Cheese( "brie", 10 ) );
    ksession.insert( new Cheese( "brie", 10 ) );
    ksession.insert( new Cheese( "brie", 10 ) );
    ksession.insert( new Cheese( "muzzarella", 10 ) );
    ksession.insert( new Cheese( "muzzarella", 10 ) );
    ksession.insert( new Cheese( "muzzarella", 10 ) );
    ksession.insert( new Cheese( "muzzarella", 10 ) );
    ksession.insert( new Cheese( "Stilton", 10 ) );
    ksession.insert( new Cheese( "Stilton", 10 ) );
    ksession.insert( new Cheese( "Stilton", 10 ) );
    ksession.insert( new Double( 10 ) );
    ksession.insert( new Double( 11 ) );
    ksession.insert( new Double( 12 ) );
    ksession.insert( new Double( 13 ) );
    ksession.insert( new Double( 14 ) );
    ksession.insert( new Integer( 15 ) );
    ksession.insert( new Integer( 16 ) );
    ksession.insert( new Integer( 17 ) );
    ksession.insert( new Integer( 18 ) );
    FactHandle handle = ksession.insert( new Worker( ) );
    
    ksession.retract( handle );
    
    SessionInspector inspector = new SessionInspector( ksession );
    
    StatefulKnowledgeSessionInfo info = inspector.getSessionInfo();
    
    String report = SessionReporter.generateReport( "simple", info, null );
    
    assertNotNull( report );
}
 
Example 12
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test @Disabled("All the classes generated by type declarations are now defined in the ProjectClassLoader")
public void testUndoTypeDeclaration() throws Exception {
    String rule = "package org.drools.compiler.test\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";

    String declarationA = "package org.drools.compiler.test\n" +
                          "global java.util.List list\n" +
                          "declare FactA\n" +
                          "    j : 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 );
    assertFalse( kbuilder.hasErrors() );

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

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

    declarationA = "package org.drools.compiler.test\n" +
                   "global java.util.List list\n" +
                   "declare FactA\n" +
                   "    i : int\n" +
                   "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: DescrBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testTopLevelAccumulate() throws InstantiationException,
                                   IllegalAccessException {
    PackageDescr pkg = DescrFactory.newPackage()
            .name( "org.drools.compiler" )
            .newRule().name( "r1" )
                .lhs()
                    .accumulate()
                        .source()
                            .pattern("StockTick").constraint( "company == \"RHT\"" ).bind( "$p", "price", false ).end()
                        .end()
                        .function( "sum", "$sum", false, "$p" )
                        .function( "count", "$cnt", false, "$p" )
                    .end()
                .end()
                .rhs( "// some comment" )
            .end()
            .getDescr();

    KiePackage kpkg = compilePkgDescr( pkg );
    assertEquals( "org.drools.compiler",
                  kpkg.getName() );
    
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( Collections.singletonList( kpkg ) );
    
    KieSession ksession = kbase.newKieSession();
    AgendaEventListener ael = mock( AgendaEventListener.class );
    ksession.addEventListener( ael );
    
    ksession.insert( new StockTick(1, "RHT", 80, 1 ) );
    ksession.insert( new StockTick(2, "RHT", 100, 10 ) );
    int rules = ksession.fireAllRules();
    assertEquals( 1, rules );
    
    ArgumentCaptor<AfterMatchFiredEvent> cap = ArgumentCaptor.forClass( AfterMatchFiredEvent.class );
    verify( ael ).afterMatchFired(cap.capture());
    
    assertThat((Number)cap.getValue().getMatch().getDeclarationValue( "$sum" )).isEqualTo(180.0);
    assertThat((Number)cap.getValue().getMatch().getDeclarationValue( "$cnt" )).isEqualTo(2L);
}
 
Example 14
Source File: LinkingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testNotNodeUnlinksWithNoConstriants() {
    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 : A() \n";
    str += "   not B() \n";
    str += "   $c : C() \n";        
    str += "then \n";
    str += "  list.add( 'x' ); \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 aotn = getObjectTypeNode(kbase, A.class );

    InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl)kbase.newKieSession());
    List list = new ArrayList();
    wm.setGlobal( "list", list );
    
    LeftInputAdapterNode aNode = (LeftInputAdapterNode) aotn.getObjectSinkPropagator().getSinks()[0];
    NotNode bNode = ( NotNode) aNode.getSinkPropagator().getSinks()[0];        
    JoinNode cNode = ( JoinNode) bNode.getSinkPropagator().getSinks()[0];                
    
    SegmentUtilities.createSegmentMemory( cNode, wm );
    LiaNodeMemory amem = ( LiaNodeMemory ) wm.getNodeMemory( aNode );  
    
    // Only NotNode is linked in
    assertEquals( 2, amem.getSegmentMemory().getLinkedNodeMask() );
    
    FactHandle fha = wm.insert(  new A() );
    FactHandle fhb = wm.insert(  new B() );
    FactHandle fhc = wm.insert(  new C() );        
    wm.fireAllRules();
    assertEquals( 0, list.size() );
    
    // NotNode unlinks, which is allowed because it has no variable constraints
    assertEquals( 5, amem.getSegmentMemory().getLinkedNodeMask() );        
    
    // NotNode links back in again, which is allowed because it has no variable constraints
    wm.retract( fhb);
    wm.flushPropagations();
    assertEquals( 7, amem.getSegmentMemory().getLinkedNodeMask() );
    wm.fireAllRules();
    assertEquals( 1, list.size() ); 
    
    // Now try with lots of facthandles on NotNode
    
    list.clear();
    List<FactHandle> handles = new ArrayList<FactHandle>();
    for ( int i = 0; i < 5; i++ ) {
        handles.add(  wm.insert(  new B() ) );
    }
    wm.fireAllRules();
    assertEquals( 0, list.size() );
    
    assertEquals( 5, amem.getSegmentMemory().getLinkedNodeMask() );
    for ( FactHandle fh : handles ) {
        wm.retract( fh );
    }
    wm.flushPropagations();

    assertEquals( 7, amem.getSegmentMemory().getLinkedNodeMask() );
    wm.fireAllRules();
    assertEquals( 1, list.size() );        
}
 
Example 15
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testTMSWithEquivalentSubclasses() {
    String droolsSource =
            "package project_java_rules2_xxx \n" +
            "import " + HashBrown.class.getCanonicalName() + "; \n" +

            "declare Foo id : int @key end \n\n" +

            "rule Zero \n" +
            "when \n" +
            " $s : String( this == \"go\" ) \n" +
            "then \n" +
            " insertLogical( new HashBrown(1) ); \n" +
            "end \n" +

            "rule Init \n" +
            "when \n" +
            "then \n" +
            " insertLogical( new HashBrown(7) ); \n" +
            "end \n" ;

    /////////////////////////////////////

    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add( new ByteArrayResource( droolsSource.getBytes() ), ResourceType.DRL );
    assertFalse(kBuilder.hasErrors(), kBuilder.getErrors().toString());

    final RuleBaseConfiguration conf = new RuleBaseConfiguration();
    conf.setAssertBehaviour( RuleBaseConfiguration.AssertBehaviour.EQUALITY );
    conf.setSequentialAgenda( RuleBaseConfiguration.SequentialAgenda.SEQUENTIAL );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase( conf );
    kbase.addPackages( kBuilder.getKnowledgePackages() );

    KieSession session = kbase.newKieSession();
    try {
        session.fireAllRules();

        FactHandle handle = session.insert( new HashBlack( 1 ) );
        session.insert( "go" );
        session.fireAllRules();

        assertNotNull( ((DefaultFactHandle) handle).getEqualityKey() );
    } finally {
        session.dispose();
    }
}
 
Example 16
Source File: SerializedPackageMergeTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildAndSerializePackagesWithSamePackageName() throws IOException, ClassNotFoundException    {
    // RHBRMS-2773
    String str1 =
            "package com.sample\n" +
            "import org.drools.compiler.Person\n" +
            "global java.util.List list\n" +
            "rule R1 when\n" +
            "  $p : Person( name == \"John\" )\n" +
            "then\n" +
            "  list.add($p);" +
            "end\n";

    String str2 =
            "package com.sample\n" +
            "import org.drools.compiler.Person\n" +
            "global java.util.List list\n" +
            "rule R2 when\n" +
            "  $p : Person( name == \"Paul\" )\n" +
            "then\n" +
            "  list.add($p);" +
            "end\n";

    // Create 2 knowledgePackages separately (but these rules have the same package name)
    KnowledgeBuilder builder1 = KnowledgeBuilderFactory.newKnowledgeBuilder();
    builder1.add( ResourceFactory.newByteArrayResource( str1.getBytes() ), ResourceType.DRL );
    Collection<KiePackage> knowledgePackages1 = builder1.getKnowledgePackages();

    KnowledgeBuilder builder2 = KnowledgeBuilderFactory.newKnowledgeBuilder();
    builder2.add( ResourceFactory.newByteArrayResource( str2.getBytes() ), ResourceType.DRL );
    Collection<KiePackage> knowledgePackages2 = builder2.getKnowledgePackages();

    // Combine the knowledgePackages
    InternalKnowledgeBase knowledgeBase1 = KnowledgeBaseFactory.newKnowledgeBase();
    knowledgeBase1.addPackages( knowledgePackages1 );
    knowledgeBase1.addPackages( knowledgePackages2 );
    Collection<KiePackage> knowledgePackagesCombined = knowledgeBase1.getKiePackages();

    // serialize
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new DroolsObjectOutputStream( baos );
    out.writeObject( knowledgePackagesCombined );
    out.flush();
    out.close();

    // deserialize
    ObjectInputStream in = new DroolsObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) );
    Collection<KiePackage> deserializedPackages = (Collection<KiePackage>) in.readObject();

    // Use the deserialized knowledgePackages
    InternalKnowledgeBase knowledgeBase2 = KnowledgeBaseFactory.newKnowledgeBase();
    knowledgeBase2.addPackages(deserializedPackages);

    KieSession ksession = knowledgeBase2.newKieSession();
    try {
        List<String> list = new ArrayList<String>();
        ksession.setGlobal( "list", list );
        ksession.insert(new org.drools.compiler.Person("John"));
        ksession.insert(new org.drools.compiler.Person("Paul"));
        ksession.fireAllRules();

        assertEquals(2, list.size());
    } finally {
        ksession.dispose();
    }
}
 
Example 17
Source File: LinkingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
    public void testNestedSubnetwork() 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 : A() \n";
        str += "   exists ( B() and exists( C() and D() ) and E() ) \n";
        str += "   $f : F() \n";        
        str += "then \n";
        str += "  list.add( 'x' ); \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 aotn = getObjectTypeNode(kbase, A.class );
        ObjectTypeNode botn = getObjectTypeNode(kbase, A.class );
        ObjectTypeNode cotn = getObjectTypeNode(kbase, A.class );

        InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl)kbase.newKieSession());
        List list = new ArrayList();
        wm.setGlobal( "list", list );
        
        wm.insert( new A() );
        wm.insert( new B() );
        for ( int i = 0; i < 28; i++ ) {
            wm.insert( new C() );
        }
        for ( int i = 0; i < 29; i++ ) {
            wm.insert( new D() );
        }
        wm.insert( new E() );
        wm.insert( new F() );
        
//        DefaultAgenda agenda = ( DefaultAgenda ) wm.getAgenda();
//        InternalAgendaGroup group = (InternalAgendaGroup) agenda.getNextFocus();
//        AgendaItem item = (AgendaItem) group.remove();
//        int count = ((RuleAgendaItem)item).evaluateNetworkAndFire( wm );
//        //assertEquals(7, count ); // proves we correctly track nested sub network staged propagations
//                
//        agenda.addActivation( item, true );
//        agenda = ( DefaultAgenda ) wm.getAgenda();
//        group = (InternalAgendaGroup) agenda.getNextFocus();
//        item = (AgendaItem) group.remove();
//        
//        agenda.fireActivation( item );
//        assertEquals( 1, list.size() );        
//        
//        agenda = ( DefaultAgenda ) wm.getAgenda();
//        group = (InternalAgendaGroup) agenda.getNextFocus();
//        item = (AgendaItem) group.remove();
//        count = ((RuleAgendaItem)item).evaluateNetworkAndFire( wm );
//        //assertEquals(0, count );        
        
        wm.fireAllRules();
        assertEquals( 1, list.size() );
        
        wm.fireAllRules();
        assertEquals( 1, list.size() );         
    }
 
Example 18
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 19
Source File: QueryBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testQuery() throws Exception {
    final KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();

    final PackageDescr packageDescr = new PackageDescr( "p1" );
    final QueryDescr queryDescr = new QueryDescr( "query1" );
    queryDescr.addParameter( "String",
                             "$type" );

    packageDescr.addRule( queryDescr );

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

    final PatternDescr pattern = new PatternDescr( Cheese.class.getName(),
                                                   "stilton" );
    lhs.addDescr( pattern );

    pattern.addConstraint( new ExprConstraintDescr("type == $type") );

    // Another query, no parameters
    QueryDescr queryDescr2 = new QueryDescr( "query2" );
    packageDescr.addRule( queryDescr2 );
    AndDescr lhs2 = new AndDescr();
    queryDescr2.setLhs( lhs2 );
    PatternDescr pattern2 = new PatternDescr( Cheese.class.getName() );
    lhs2.addDescr( pattern2 );

    builder.addPackage( packageDescr );

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

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(Arrays.asList( new KiePackage[] { builder.getPackage(packageDescr.getName()) } ) );

    final KieSession session = kbase.newKieSession();

    session.insert( new Cheese( "stilton",
                                15 ) );

    QueryResults results = session.getQueryResults( "query1",
                                                    "stilton" );
    assertEquals( 1,
                  results.size() );

    Object object = results.iterator().next().get("stilton");
    assertEquals( new Cheese( "stilton",
                              15 ),
                  object );

    results = session.getQueryResults( "query1",
                                       new Object[]{"cheddar"} );
    assertEquals( 0,
                  results.size() );

    session.insert(new Cheese("dolcelatte",
                              20));
    results = session.getQueryResults( "query2",
                                       new Object[]{} );
    assertEquals( 2,
                  results.size() );
}
 
Example 20
Source File: JavaActionBuilderTest.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();
    JavaDialect javaDialect = ( JavaDialect ) dialectRegistry.getDialect( "java" );

    ProcessDescr processDescr = new ProcessDescr();
    processDescr.setClassName( "Process1" );
    processDescr.setName( "Process1" );
    
    WorkflowProcessImpl process = new WorkflowProcessImpl();
    process.setName( "Process1" );
    process.setPackageName( "pkg1" );

    ProcessBuildContext context = new ProcessBuildContext(pkgBuilder, pkgBuilder.getPackage("pkg1"), null, processDescr, dialectRegistry, javaDialect);
    
    context.init( pkgBuilder, pkg, null, dialectRegistry, javaDialect, null);
    
    pkgBuilder.addPackageFromDrl( new StringReader("package pkg1;\nglobal java.util.List list;\n") );        
    
    ActionNode actionNode = new ActionNode();
    DroolsAction action = new DroolsConsequenceAction("java", null);
    actionNode.setAction(action);
    
    ProcessDialect dialect = ProcessDialectRegistry.getDialect( "java" );            
    dialect.getActionBuilder().build( context, action, actionDescr, actionNode );
    dialect.addProcess( context );
    javaDialect.compileAll();            
    assertEquals( 0, javaDialect.getResults().size() );

    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 );        
    
    ProcessContext processContext = new ProcessContext( ((InternalWorkingMemory) wm).getKnowledgeRuntime() );
    ((Action) actionNode.getAction().getMetaData("Action")).execute( processContext );
   
    assertEquals("hello world", list.get(0) );
}