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

The following examples show how to use org.drools.core.impl.InternalKnowledgeBase#addPackages() . 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: DescrBuilderTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleRHSComment() throws InstantiationException,
                                   IllegalAccessException {
    PackageDescr pkg = DescrFactory.newPackage()
            .name( "org.drools.compiler" )
            .newRule().name( "r1" )
                .lhs()
                    .pattern("StockTick").constraint( "company == \"RHT\"" ).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();
    ksession.insert( new StockTick(1, "RHT", 80, 1 ) );
    int rules = ksession.fireAllRules();
    assertEquals( 1, rules );
}
 
Example 2
Source File: DslTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private List doTest(String dsl, String drl) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(dsl.getBytes()), ResourceType.DSL );
    kbuilder.add( ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DSLR );

    assertFalse(kbuilder.hasErrors());

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

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

    ksession.insert(new Person("Mario", 38));
    ksession.fireAllRules();
    ksession.dispose();

    return list;
}
 
Example 3
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 4
Source File: ChangeSetTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testIntegregation() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource("changeset1Test.xml",
            getClass()),
                  ResourceType.CHANGE_SET );
    assertFalse( kbuilder.hasErrors() );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );
    ksession.fireAllRules();
    ksession.dispose();

    assertEquals( 2,
                  list.size() );
    assertTrue( list.containsAll( Arrays.asList( new String[]{"rule1", "rule2"} ) ) );
}
 
Example 5
Source File: InterpretedRuleUnit.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public RuleUnitInstance<T> internalCreateInstance(T data) {
    KnowledgeBuilder kBuilder = new KnowledgeBuilderImpl();
    Class<? extends RuleUnitData> wmClass = data.getClass();
    String canonicalName = wmClass.getCanonicalName();

    // transform foo.bar.Baz to /foo/bar/Baz.drl
    // this currently only works for single files
    InputStream resourceAsStream = wmClass.getResourceAsStream(
            String.format("/%s.drl", canonicalName.replace('.', '/')));
    kBuilder.add(new InputStreamResource(resourceAsStream), ResourceType.DRL);

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

    return new InterpretedRuleUnitInstance<>(this, data, kSession);
}
 
Example 6
Source File: UnmarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBase initializeKnowledgeBase( String rule ) {
    // Setup knowledge base
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newReaderResource(new StringReader(rule)),
                  ResourceType.DRL );
    if ( kbuilder.hasErrors() ) {
        throw new RuntimeException( kbuilder.getErrors().toString() );
    }
    KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption( EventProcessingOption.STREAM );
    InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase( config );
    knowledgeBase.addPackages( kbuilder.getKnowledgePackages() );

    return knowledgeBase;
}
 
Example 7
Source File: I18nTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test @Disabled("Fails because of JBRULES-3435. But the JBRULES-2853 part works fine. Support for i18n properties must be fixed in mvel")
public void readDrlInEncodingUtf8() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_I18nPerson_utf8.drl", "UTF-8", getClass() ),
                  ResourceType.DRL );
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }

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

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

    I18nPerson i18nPerson = new I18nPerson();
    i18nPerson.setGarçon("Value 1");
    i18nPerson.setÉlève("Value 2");
    i18nPerson.setИмя("Value 3");
    i18nPerson.set名称("Value 4");
    ksession.insert(i18nPerson);
    ksession.fireAllRules();

    assertTrue(list.contains("garçon"));
    assertTrue(list.contains("élève"));
    assertTrue(list.contains("имя"));
    assertTrue(list.contains("名称"));
    ksession.dispose();
}
 
Example 8
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleInheritanceWithPosition4() throws Exception {
    // DROOLS-249
    String drl =
            "package org.drools.test\n" +
            "declare trait PosTrait\n" +
            "@propertyReactive\n" +
            " field0 : int = 100 @position(1)\n" +
            " field1 : int = 101 @position(0)\n" +
            " field2 : int = 102 @position(0)\n" +
            "end\n" +
            "\n" +
            "declare trait MultiInhPosTrait extends PosTrait\n" +
            "@propertyReactive\n" +
            " mfield0 : int = 200 @position(0)\n" +
            " mfield1 : int = 201 @position(2)\n" +
            "end";
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( );
    kBuilder.add( new ByteArrayResource( drl.getBytes() ), ResourceType.DRL );
    if ( kBuilder.hasErrors() ) {
        System.err.println( kBuilder.getErrors() );
    }
    assertFalse( kBuilder.hasErrors() );

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

    FactType sw = knowledgeBase.getFactType( "org.drools.test", "MultiInhPosTrait" );
    assertEquals( 5, sw.getFields().size() );
    assertEquals( "field1", sw.getFields().get(0).getName() );
    assertEquals( "field2", sw.getFields().get(1).getName() );
    assertEquals( "mfield0", sw.getFields().get(2).getName() );
    assertEquals( "field0", sw.getFields().get(3).getName() );
    assertEquals( "mfield1", sw.getFields().get(4).getName() );
}
 
Example 9
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemovePackage() throws Exception {
    Collection<KiePackage> kpkgs = SerializationHelper.serializeObject(loadKnowledgePackages("test_RemovePackage.drl"));
    final String packageName = kpkgs.iterator().next().getName();
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) loadKnowledgeBase( );

    kbase.addPackages( kpkgs );
    kbase = SerializationHelper.serializeObject( kbase );

    KieSession session = createKnowledgeSession( kbase );

    session.insert( new Precondition( "genericcode",
                                      "genericvalue" ) );
    session.fireAllRules();

    InternalKnowledgeBase ruleBaseWM = (InternalKnowledgeBase) session.getKieBase();
    ruleBaseWM.removeKiePackage( packageName );
    
    kpkgs = SerializationHelper.serializeObject( loadKnowledgePackages(  "test_RemovePackage.drl" ) );
    ruleBaseWM.addPackages( kpkgs );
    ruleBaseWM = SerializationHelper.serializeObject( ruleBaseWM );

    session = SerializationHelper.getSerialisedStatefulKnowledgeSession( session, 
                                                                         true );
    session.fireAllRules();

    ruleBaseWM.removeKiePackage(packageName);
    ruleBaseWM.addPackages( SerializationHelper.serializeObject( kpkgs ) );

    ruleBaseWM.removeKiePackage( packageName );
    ruleBaseWM.addPackages(SerializationHelper.serializeObject(kpkgs));
}
 
Example 10
Source File: DslTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void checkDSLExpanderTest(KnowledgeBuilder kbuilder) throws IOException, ClassNotFoundException {
    assertFalse( kbuilder.hasErrors() );
    final String err = kbuilder.getErrors().toString();
    assertEquals( "",
                  err );
    assertEquals( 0,
                  kbuilder.getErrors().size() );

    // the compiled package
    final Collection<KiePackage> pkgs = kbuilder.getKnowledgePackages();
    assertEquals( 2, pkgs.size() );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( pkgs );
    kbase    = SerializationHelper.serializeObject(kbase);

    KieSession session = createKnowledgeSession(kbase);
    session.insert( new Person( "Bob",
                           "http://foo.bar" ) );
    session.insert( new Cheese( "stilton",
                           42 ) );

    final List messages = new ArrayList();
    session.setGlobal( "messages",
                  messages );
    session.fireAllRules();

    assertEquals( 1, messages.size() );
}
 
Example 11
Source File: AsmGeneratorTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatterDeclarations() {
    String s = 
        "package org.kie.test\n" +
        "global java.util.List list\n" +        
        "rule r1 when\n" +
        "    s1 : String( this == 's1' )\n" +
        "    s2 : String( this == 's2' )\n" +
        "    s3 : String( this == 's3' )\n" +
        "    s4 : String( this == 's4' )\n" +
        "    s5 : String( this == 's5' )\n" +
        "then\n" +
        "    // s5 is missed out on purpose to make sure we only resolved required declarations\n" +
        "   list.add( s1 + s2 + s3 + s5 ); \n" +
        "end\n";
    
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(s.getBytes()), ResourceType.DRL );
    
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list", list );        
    
    ksession.insert( "s1" );
    ksession.insert( "s2" );
    ksession.insert( "s3" );
    ksession.insert( "s4" );
    ksession.insert( "s5" );
    
    ksession.fireAllRules();     
    assertEquals( 1, list.size() );
    assertEquals( "s1s2s3s5", list.get( 0 ));        
}
 
Example 12
Source File: LogicalTraitTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@ParameterizedLogicalTraitTest
public void shadowAliasSelf(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 VIP \n" +
            "@Trait( logical=true ) \n" +
            "  friend : VIP \n" +
            "end \n" +
            "" +
            "declare Pers \n" +
            "@Traitable( logical = true ) \n" +
            "  friend : Pers \n" +
            "end \n" +
            "" +
            "rule Don \n" +
            "when \n" +
            "then \n" +
            "  Pers p = new Pers(); " +
            "  p.setFriend( p ); \n\n" +
            "  don( p, VIP.class ); \n" +
            "end \n" +
            "" +
            "rule Check \n" +
            "salience 1 \n" +
            "when \n" +
            "  $x : Pers( friend isA VIP ) \n" +
            "then \n" +
            "  list.add( \"ok1\" );" +
            "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();
    assertEquals(Arrays.asList("ok1"), list);

    try {
        ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example 13
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testPopulatedRuleMidwayShare() throws Exception {
    InternalKnowledgeBase kbase1 = buildKnowledgeBase("r1", "   a : A() B() 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(3));
    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();
    assertEquals( 3, list.size() );

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

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

    JoinNode c1Node = (JoinNode) bNode.getSinkPropagator().getFirstLeftTupleSink();
    JoinNode c2Node = (JoinNode) bNode.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 14
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 15
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 16
Source File: JavaReturnValueConstraintEvaluatorBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSimpleReturnValueConstraintEvaluator() throws Exception {
    final InternalKnowledgePackage pkg = new KnowledgePackageImpl( "pkg1" );

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

    ReturnValueDescr descr = new ReturnValueDescr();
    descr.setText( "return value;" );

    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl( pkg );
    DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry( pkg.getName() ).getDialectCompiletimeRegistry();
    JavaDialect javaDialect = (JavaDialect) dialectRegistry.getDialect( "java" );

    ProcessBuildContext context = new ProcessBuildContext( pkgBuilder,
                                                           pkg,
                                                           process,
                                                           processDescr,
                                                           dialectRegistry,
                                                           javaDialect );

    pkgBuilder.addPackageFromDrl( new StringReader( "package pkg1;\nglobal Boolean value;" ) );

    ReturnValueConstraintEvaluator node = new ReturnValueConstraintEvaluator();

    final JavaReturnValueEvaluatorBuilder builder = new JavaReturnValueEvaluatorBuilder();
    builder.build( context,
                   node,
                   descr,
                   null );

    ProcessDialectRegistry.getDialect(JavaDialect.ID).addProcess( context );
    javaDialect.compileAll();
    assertEquals( 0, javaDialect.getResults().size() );

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

    ksession.setGlobal( "value", true );

    RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();
    processInstance.setKnowledgeRuntime( (InternalKnowledgeRuntime) ksession );

    SplitInstance splitInstance = new SplitInstance();
    splitInstance.setProcessInstance( processInstance );

    assertTrue( node.evaluate( splitInstance,
                               null,
                               null ) );

    ksession.setGlobal( "value",
                  false );

    assertFalse( node.evaluate( splitInstance,
                                null,
                                null ) );
}
 
Example 17
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 18
Source File: RuleExtensionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testRuleExtendsOnIncrementalKB() {
    // 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 \"Base\"\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 );
    assertFalse(kbuilder2.hasErrors());

    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 19
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSegmentMerging() {
    String drl1 = "global java.util.List list\n" +
                  "rule R1 when\n" +
                  "  $s : String()\n" +
                  "  $i : Integer( this == $s.length() )\n" +
                  "  $j : Integer( this == $i * 2 )\n" +
                  "then\n" +
                  "  list.add( $j );\n" +
                  "end\n";

    String drl2 = "global java.util.List list\n" +
                  "rule R2 when\n" +
                  "  $s : String()\n" +
                  "  $i : Integer( this == $s.length() )\n" +
                  "  $j : Integer( this == $i * 3 )\n" +
                  "then\n" +
                  "  list.add( $j );\n" +
                  "end\n";

    InternalKnowledgeBase kbase = (InternalKnowledgeBase)getKnowledgeBase( );

    kbase.addPackages(loadKnowledgePackagesFromString( drl1 ));

    KieSession ksession = createKnowledgeSession(kbase);
    List<Integer> list = new ArrayList<Integer>();
    ksession.setGlobal("list", list);

    ksession.insert("test");
    ksession.insert(4);
    ksession.insert(8);
    ksession.insert(12);

    ksession.fireAllRules();
    assertEquals(8, (int)list.get(0));
    list.clear();

    kbase.addPackages(loadKnowledgePackagesFromString(drl2));

    kbase.removeRule("defaultpkg", "R1");

    ksession.fireAllRules();
    assertEquals(12, (int)list.get(0));
}
 
Example 20
Source File: LinkingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubNetworkRiaLinking() 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 += "global java.util.List list \n";

    str += "rule rule1 when \n";
    str += "   A() \n";
    str += "   B() \n";
    str += "   exists( C() and D() ) \n";
    str += "   E() \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() );

    JoinNode bNode = ( JoinNode) liaNode.getSinkPropagator().getSinks()[0];
    assertEquals( 2, bNode.getSinkPropagator().size() );

    ExistsNode exists1n = ( ExistsNode) bNode.getSinkPropagator().getSinks()[1];

    JoinNode cNode = ( JoinNode) bNode.getSinkPropagator().getSinks()[0];
    JoinNode dNode = ( JoinNode) cNode.getSinkPropagator().getSinks()[0];
    assertEquals( 1, dNode.getSinkPropagator().size() );

    RightInputAdapterNode riaNode1 =  ( RightInputAdapterNode ) dNode.getSinkPropagator().getSinks()[0];


    JoinNode eNode = ( JoinNode ) exists1n.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn = ( RuleTerminalNode ) eNode.getSinkPropagator().getSinks()[0];

    SegmentUtilities.createSegmentMemory( exists1n, wm );
    BetaMemory existsBm = ( BetaMemory ) wm.getNodeMemory( exists1n );

    assertEquals( 0, existsBm.getSegmentMemory().getLinkedNodeMask() );

    FactHandle fhc = wm.insert(  new C() );
    FactHandle fhd = wm.insert(  new D() );
    wm.flushPropagations();

    assertEquals( 1, existsBm.getSegmentMemory().getLinkedNodeMask() );  // exists is start of new segment

    wm.retract( fhd );
    wm.flushPropagations();
    assertEquals( 0, existsBm.getSegmentMemory().getLinkedNodeMask() );

    PathMemory rs = (PathMemory) wm.getNodeMemory( rtn );
    assertFalse( rs.isRuleLinked() );

    wm.insert(  new A() );
    wm.flushPropagations();
    assertFalse(rs.isRuleLinked());
    wm.insert(new B());
    wm.flushPropagations();
    assertFalse(rs.isRuleLinked());
    wm.insert(new E());
    wm.flushPropagations();
    assertFalse( rs.isRuleLinked() );

    wm.insert(  new D() );
    wm.flushPropagations();
    assertTrue( rs.isRuleLinked() );

    wm.retract(  fhc );
    wm.flushPropagations();
    assertFalse( rs.isRuleLinked() );

    wm.insert(  new C() );
    wm.flushPropagations();
    assertTrue( rs.isRuleLinked() );
}