org.kie.api.KieBaseConfiguration Java Examples

The following examples show how to use org.kie.api.KieBaseConfiguration. 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: RuleUnlinkingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleSegmentsAllLinkedTestMasks() {
    setUp( JOIN_NODE );

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();

    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl wm = new StatefulKnowledgeSessionImpl( 1L, kBase );

    PathMemory rs = (PathMemory) wm.getNodeMemory( rtn1 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 1, rs.getAllLinkedMaskTest() );

    rs = (PathMemory) wm.getNodeMemory( rtn2 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 3, rs.getAllLinkedMaskTest() );

    rs = (PathMemory) wm.getNodeMemory( rtn3 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 7, rs.getAllLinkedMaskTest() );
}
 
Example #2
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieBase loadKnowledgeBaseFromString( KnowledgeBuilderConfiguration config, KieBaseConfiguration kBaseConfig, NodeFactory nodeFactory, String... drlContentStrings) {
    KnowledgeBuilder kbuilder = config == null ? KnowledgeBuilderFactory.newKnowledgeBuilder() : KnowledgeBuilderFactory.newKnowledgeBuilder(config);
    for (String drlContentString : drlContentStrings) {
        kbuilder.add(ResourceFactory.newByteArrayResource(drlContentString
                .getBytes()), ResourceType.DRL);
    }

    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    if (kBaseConfig == null) {
        kBaseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    }
    InternalKnowledgeBase kbase = kBaseConfig == null ? KnowledgeBaseFactory.newKnowledgeBase() : KnowledgeBaseFactory.newKnowledgeBase(kBaseConfig);
    if (nodeFactory != null) {
        ((KnowledgeBaseImpl) kbase).getConfiguration().getComponentFactory().setNodeFactoryProvider(nodeFactory);
    }
    kbase.addPackages( kbuilder.getKnowledgePackages());
    return kbase;
}
 
Example #3
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromString( String drlString, KieBaseConfiguration kbConf ) {
    KieHelper kieHelper = new KieHelper();
    kieHelper.addContent( drlString, ResourceType.DRL );

    Results res = kieHelper.verify();
    if ( res.hasMessages( Message.Level.ERROR ) ) {
        fail( res.getMessages( Message.Level.ERROR ).toString() );
    }

    if ( kbConf == null ) {
        kbConf = KieServices.Factory.get().newKieBaseConfiguration();
    }
    kbConf.setOption( EqualityBehaviorOption.EQUALITY );
    KieBase kieBase = kieHelper.build( kbConf );


    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );
    return kieBase.newKieSession( ksConf, null );
}
 
Example #4
Source File: RuleUnlinkingWithSegmentMemoryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleSegmentsAllLinkedTestMasks() {
    setUp( JOIN_NODE );

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl wm = new StatefulKnowledgeSessionImpl( 1L, kBase );
    
    PathMemory rs = (PathMemory) wm.getNodeMemory( rtn1 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 1, rs.getAllLinkedMaskTest() );
    
    rs = (PathMemory) wm.getNodeMemory( rtn2 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 3, rs.getAllLinkedMaskTest() );
    
    rs = (PathMemory) wm.getNodeMemory( rtn3 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 7, rs.getAllLinkedMaskTest() );
}
 
Example #5
Source File: FireUntilHaltAccumulateTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
        System.err.println(kbuilder.getErrors().toString());
    }
    final KieBaseConfiguration config =
            KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption( EventProcessingOption.STREAM);

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

    final KieSessionConfiguration sessionConfig =
            KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ));

    this.statefulSession = kbase.newKieSession(sessionConfig, null);
    this.stockFactory = new StockFactory(kbase);
}
 
Example #6
Source File: AbstractKieModule.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public InternalKnowledgeBase createKieBase( KieBaseModelImpl kBaseModel, KieProject kieProject, ResultsImpl messages, KieBaseConfiguration conf ) {
    KnowledgePackagesBuildResult knowledgePackagesBuildResult = buildKnowledgePackages(kBaseModel, kieProject, messages);
    if(knowledgePackagesBuildResult.hasErrors()) {
        return null;
    }

    Collection<KiePackage> pkgs = knowledgePackagesBuildResult.getPkgs();
    checkStreamMode( kBaseModel, conf, pkgs );

    ClassLoader cl = kieProject.getClassLoader();
    if (conf == null) {
        conf = getKnowledgeBaseConfiguration(kBaseModel, cl);
    } else if (conf instanceof RuleBaseConfiguration ) {
        ((RuleBaseConfiguration)conf).setClassLoader(cl);
    }

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase(kBaseModel.getName(), conf );
    kBase.addPackages( pkgs );
    return kBase;
}
 
Example #7
Source File: NodeSegmentUnlinkingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllLinkedInWithExistsNodesOnly() {
    setUp( EXISTS_NODE );

    assertEquals( ExistsNode.class, n3.getClass() ); // make sure it created ExistsNodes

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    DefaultFactHandle f1 = (DefaultFactHandle) ksession.insert( "test1" );
    n3.assertObject( f1, context, ksession );

    BetaMemory bm = (BetaMemory) ksession.getNodeMemory( n3 );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n4.assertObject( f1, context, ksession );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n5.assertObject( f1, context, ksession );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n6.assertObject( f1, context, ksession );
    assertTrue( bm.getSegmentMemory().isSegmentLinked() ); // only after all 4 nodes are populated, is the segment linked in
}
 
Example #8
Source File: NodeSegmentUnlinkingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllLinkedInWithNotNodesOnly() {
    setUp( NOT_NODE );

    assertEquals( NotNode.class, n3.getClass() ); // make sure it created NotNodes

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    BetaMemory bm = (BetaMemory) ksession.getNodeMemory( n3 );
    createSegmentMemory( n3, ksession );
    assertTrue( bm.getSegmentMemory().isSegmentLinked() ); // not nodes start off linked

    DefaultFactHandle f1 = (DefaultFactHandle) ksession.insert( "test1" ); // unlinked after first assertion
    n3.assertObject( f1, context, ksession );
            
    // this doesn't unlink on the assertObject, as the node's memory must be processed. So use the helper method the main network evaluator uses.
    PhreakNotNode.unlinkNotNodeOnRightInsert( (NotNode) n3, bm, ksession );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );                

    n3.retractRightTuple( f1.getFirstRightTuple(), context, ksession );
    assertTrue( bm.getSegmentMemory().isSegmentLinked() ); 
            //assertFalse( bm.getSegmentMemory().isSigmentLinked() ); // check retraction unlinks again         
}
 
Example #9
Source File: NodeSegmentUnlinkingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllLinkedInWithJoinNodesOnly() {
    setUp( JOIN_NODE );

    assertEquals( JoinNode.class, n3.getClass() ); // make sure it created JoinNodes

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    DefaultFactHandle f1 = (DefaultFactHandle) ksession.insert( "test1" );
    n3.assertObject( f1, context, ksession );

    BetaMemory bm = (BetaMemory) ksession.getNodeMemory( n3 );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n4.assertObject( f1, context, ksession );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n5.assertObject( f1, context, ksession );
    assertFalse( bm.getSegmentMemory().isSegmentLinked() );

    n6.assertObject( f1, context, ksession );
    assertTrue( bm.getSegmentMemory().isSegmentLinked() ); // only after all 4 nodes are populated, is the segment linked in
}
 
Example #10
Source File: StatefulSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFactHandleEqualityBehavior() throws Exception {
    final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(EqualityBehaviorOption.EQUALITY);
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc));
    final KieSession ksession = createKnowledgeSession(kbase);

    final CheeseEqual cheese = new CheeseEqual("stilton", 10);
    ksession.insert(cheese);
    final FactHandle fh = ksession.getFactHandle(new CheeseEqual("stilton", 10));
    assertNotNull(fh);
}
 
Example #11
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieBase newKieBase(String kBaseName, KieBaseConfiguration conf) {
    ResultsImpl msgs = new ResultsImpl();
    KieBase kBase = createKieBase(getKieBaseModelImpl(kBaseName), kProject, msgs, conf);
    if ( kBase == null ) {
        // build error, throw runtime exception
        throw new RuntimeException( "Error while creating KieBase" + msgs.filterMessages( Level.ERROR  ) );
    }
    return kBase;
}
 
Example #12
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected KieBase loadKnowledgeBase(KnowledgeBuilderConfiguration kbuilderConf, KieBaseConfiguration kbaseConf, String... classPathResources) {
    Collection<KiePackage> knowledgePackages = loadKnowledgePackages(kbuilderConf, classPathResources);

    if (kbaseConf == null) {
        kbaseConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbaseConf);
    kbase.addPackages(knowledgePackages);
    try {
        kbase = SerializationHelper.serializeObject(kbase);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return kbase;
}
 
Example #13
Source File: AbstractKieModule.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static void checkStreamMode( KieBaseModelImpl kBaseModel, KieBaseConfiguration conf, Collection<? extends KiePackage> pkgs ) {
    if ( kBaseModel.getEventProcessingMode() == EventProcessingOption.CLOUD &&
         (conf == null || conf.getOption(EventProcessingOption.class) == EventProcessingOption.CLOUD ) ) {
        for (KiePackage kpkg : pkgs) {
            if ( ((KnowledgePackageImpl ) kpkg).needsStreamMode() ) {
                throw new RuntimeException( "The requested KieBase \"" + kBaseModel.getName() + "\" has been set to run in CLOUD mode but requires features only available in STREAM mode" );
            }
        }
    }
}
 
Example #14
Source File: KnowledgeBuilderImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieBase newKnowledgeBase(KieBaseConfiguration conf) {
    KnowledgeBuilderErrors errors = getErrors();
    if (!errors.isEmpty()) {
        for (KnowledgeBuilderError error : errors) {
            logger.error(error.toString());
        }
        throw new IllegalArgumentException("Could not parse knowledge. See the logs for details.");
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(conf);
    kbase.addPackages(Arrays.asList(getPackages()));
    return kbase;
}
 
Example #15
Source File: AbstractKieModule.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBaseConfiguration getKnowledgeBaseConfiguration(KieBaseModelImpl kBaseModel, ClassLoader cl) {
    KieBaseConfiguration kbConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(null, cl);
    kbConf.setOption(kBaseModel.getEqualsBehavior());
    kbConf.setOption(kBaseModel.getEventProcessingMode());
    kbConf.setOption(kBaseModel.getDeclarativeAgenda());
    kbConf.setOption(kBaseModel.getSequential());
    kbConf.setOption(kBaseModel.getSessionsPool());
    return kbConf;
}
 
Example #16
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected KieSession getSessionFromString( String drlString) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    try {
        System.setProperty("drools.negatable", "on");
        kBuilder.add(ResourceFactory.newByteArrayResource(drlString.getBytes()),
                     ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
            fail();
        }
    } finally {
        System.setProperty("drools.negatable", "off");
    }

    KieBaseConfiguration kieBaseConfiguration = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieBaseConfiguration.setOption( EqualityBehaviorOption.EQUALITY );

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

    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );

    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #17
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieBase newKieBase(KieBaseConfiguration conf) {
    KieBaseModel defaultKieBaseModel = kProject.getDefaultKieBaseModel();
    if (defaultKieBaseModel == null) {
        throw new RuntimeException("Cannot find a default KieBase");
    }
    return newKieBase(defaultKieBaseModel.getName(), conf);
}
 
Example #18
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected KieBase loadKnowledgeBase(KnowledgeBuilderConfiguration kbuilderConf,KieBaseConfiguration kbaseConf, PackageDescr descr) {
    Collection<KiePackage> knowledgePackages = loadKnowledgePackages(kbuilderConf, descr);

    if (kbaseConf == null) {
        kbaseConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbaseConf);
    kbase.addPackages(knowledgePackages);
    try {
        kbase = SerializationHelper.serializeObject(kbase);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return kbase;
}
 
Example #19
Source File: KieHelper.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieBase build(KieBaseOption... options) {
    KieContainer kieContainer = getKieContainer();
    if (options == null || options.length == 0) {
        return kieContainer.getKieBase();
    }
    KieBaseConfiguration kieBaseConf = ks.newKieBaseConfiguration();
    for (KieBaseOption option : options) {
        kieBaseConf.setOption(option);
    }

    return kieContainer.newKieBase(kieBaseConf);
}
 
Example #20
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected KieBase getKnowledgeBase(KieBaseConfiguration kBaseConfig) {
    KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kBaseConfig);
    try {
        kbase = SerializationHelper.serializeObject(kbase, ((InternalKnowledgeBase) kbase).getRootClassLoader());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return kbase;
}
 
Example #21
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
     public void testLogicalWithDeleteException() {
    String droolsSource =
            "package org.drools.tms.test; \n" +

            "global java.util.List list; \n" +

            "rule Justify \n" +
            "when \n" +
            "    String( this == 'go1' ) " +
            "then \n" +
            "    insertLogical( 'f1' ); \n" +
            "end \n" +
            ""
            ;

    KieBaseConfiguration kieConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieConf.setOption( EqualityBehaviorOption.IDENTITY );
    KieBase kbase = loadKnowledgeBaseFromString( kieConf, droolsSource );
    KieSession session = kbase.newKieSession();
    try {
        List list = new ArrayList();
        session.setGlobal("list", list);

        session.insert( "go1" );
        session.fireAllRules();

        TruthMaintenanceSystem tms = ((StatefulKnowledgeSessionImpl)session).getTruthMaintenanceSystem();
        InternalFactHandle jfh1 = tms.get( "f1" ).getLogicalFactHandle();

        assertSame( jfh1, session.getFactHandle( "f1" ) );
    } finally {
        session.dispose();
    }
}
 
Example #22
Source File: FailureOnRemovalTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBaseConfiguration createKnowledgeBaseConfiguration(boolean shareBetaNodes) {
    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( SequentialOption.NO );
    kconf.setOption( ShareAlphaNodesOption.YES );
    kconf.setOption( shareBetaNodes ? ShareBetaNodesOption.YES : ShareBetaNodesOption.NO );
    return kconf;
}
 
Example #23
Source File: StatefulSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFactHandleIdentityBehavior() throws Exception {
    final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(EqualityBehaviorOption.IDENTITY);
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc));
    final KieSession ksession = createKnowledgeSession(kbase);

    final CheeseEqual cheese = new CheeseEqual("stilton", 10);
    ksession.insert(cheese);
    final FactHandle fh1 = ksession.getFactHandle(new Cheese("stilton", 10));
    assertNull(fh1);
    final FactHandle fh2 = ksession.getFactHandle(cheese);
    assertNotNull(fh2);
}
 
Example #24
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotInStatelessSession() throws Exception {
    final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(SequentialOption.YES);
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc, "test_NotInStatelessSession.drl"));
    final StatelessKieSession session = kbase.newStatelessKieSession();

    final List list = new ArrayList();
    session.setGlobal("list", list);
    session.execute("not integer");
    assertEquals("not integer", list.get(0));
}
 
Example #25
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMarshallWithNot() throws Exception {
    String str =
            "import " + getClass().getCanonicalName() + ".*\n" +
                    "rule one\n" +
                    "when\n" +
                    "   A()\n" +
                    "   not(B())\n" +
                    "then\n" +
                    "System.out.println(\"a\");\n" +
                    "end\n" +
                    "\n" +
                    "rule two\n" +
                    "when\n" +
                    "   A()\n" +
                    "then\n" +
                    "System.out.println(\"b\");\n" +
                    "end\n";

    KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption( EventProcessingOption.STREAM );

    KieBase kBase = loadKnowledgeBaseFromString(config, str);
    KieSession ksession = kBase.newKieSession();
    ksession.insert( new A() );
    MarshallerFactory.newMarshaller( kBase ).marshall( new ByteArrayOutputStream(), ksession );
}
 
Example #26
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testJBRULES_2206() {
    KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    ((RuleBaseConfiguration) config).setRuleBaseUpdateHandler( null );
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) getKnowledgeBase( config );
    KieSession session = createKnowledgeSession( kbase );

    AgendaEventListener ael = mock( AgendaEventListener.class );
    session.addEventListener( ael );

    for ( int i = 0; i < 5; i++ ) {
        session.insert( new Cheese() );
    }

    kbase.addPackages( loadKnowledgePackages( "test_JBRULES_2206_1.drl" ));
    ((InternalAgenda) session.getAgenda()).evaluateEagerList();

    // two matching rules were added, so 2 activations should have been created 
    verify( ael, times( 2 ) ).matchCreated(any(MatchCreatedEvent.class));
    int fireCount = session.fireAllRules();
    // both should have fired
    assertEquals( 2, fireCount );

    kbase.addPackages( loadKnowledgePackages( "test_JBRULES_2206_2.drl" ));
    ((InternalAgenda) session.getAgenda()).evaluateEagerList();

    // one rule was overridden and should activate 
    verify( ael, times( 3 ) ).matchCreated(any(MatchCreatedEvent.class));
    fireCount = session.fireAllRules();
    // that rule should fire again
    assertEquals( 1, fireCount );

    session.dispose();
}
 
Example #27
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleBlockingUsingForall() {
    String str = "";
    str += "package org.domain.test \n";
    str += "import " + Match.class.getName() + "\n";
    str += "global java.util.List list \n";
    str += "dialect 'mvel' \n";
    str += "rule rule1 @department(sales) salience -100 \n";
    str += "when \n";
    str += "     $s : String( this == 'go1' ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";
    str += "rule rule2 salience 200\n";
    str += "when \n";        
    str += "     $s : String( this == 'go1' ) \n";
    str += "     exists  Match( department == 'sales' ) \n";  
    str += "     forall ( $a : Match( department == 'sales' ) Match( this == $a, active == false ) ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( DeclarativeAgendaOption.ENABLED );
    KieBase kbase = loadKnowledgeBaseFromString( kconf, str );
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );
    ksession.insert( "go1" );
    ksession.fireAllRules();

    assertEquals( 2,
                  list.size() );
    assertTrue( list.contains("rule1:go1") );
    assertTrue( list.contains("rule2:go1") );

    ksession.dispose();
}
 
Example #28
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieSession getStatefulKnowledgeSession() {
    String str = "";
    str += "package org.domain.test \n";
    str += "import " + Match.class.getName() + "\n";
    str += "global java.util.List list \n";
    str += "dialect 'mvel' \n";

    str += "rule rule1 @department(sales) \n";
    str += "when \n";
    str += "     $s : String( this == 'go1' ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";

    str += "rule blockerAllSalesRules @activationListener('direct') \n";
    str += "when \n";
    str += "     $s : String( this == 'go2' ) \n";
    str += "     $i : Match( department == 'sales' ) \n";
    str += "then \n";
    str += "    list.add( $i.rule.name + ':' + $s  ); \n";
    str += "    kcontext.blockMatch( $i ); \n";
    str += "end \n";

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( DeclarativeAgendaOption.ENABLED );
    KieBase kbase = loadKnowledgeBaseFromString( kconf, str );
    KieSession ksession = createKnowledgeSession(kbase);

    return ksession;
}
 
Example #29
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 #30
Source File: PseudoClockEventsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private int processStocks(int stockCount, AgendaEventListener agendaEventListener, String drlContentString)
        throws Exception {
    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(EventProcessingOption.STREAM);
    KieBase kbase = loadKnowledgeBaseFromString(kconf, drlContentString);

    KieSessionConfiguration ksessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksessionConfig.setOption(ClockTypeOption.get("pseudo"));
    ksessionConfig.setProperty("keep.reference", "true");
    final KieSession ksession = kbase.newKieSession(ksessionConfig, null);
    ksession.addEventListener(agendaEventListener);

    PseudoClockScheduler clock = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock();

    Thread fireUntilHaltThread = new Thread(ksession::fireUntilHalt, "Engine's thread");
    fireUntilHaltThread.start();
    try {
        Thread.currentThread().setName("Feeding thread");

        for (int stIndex = 1; stIndex <= stockCount; stIndex++) {
            clock.advanceTime(20, TimeUnit.SECONDS);
            Thread.sleep( 100 );
            final StockTickInterface st = new StockTick(stIndex,
                                                        "RHT",
                                                        100 * stIndex,
                                                        100 * stIndex);
            ksession.insert(st);
            Thread.sleep( 100 );
        }

        Thread.sleep(100);
    } finally {
        ksession.halt();
        ksession.dispose();
    }
    
    fireUntilHaltThread.join(5000);

    return stockCount;
}