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

The following examples show how to use org.drools.core.impl.KnowledgeBaseFactory#newKnowledgeSessionConfiguration() . 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: JTMSTest.java    From kogito-runtimes with Apache License 2.0 6 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");
    }

    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 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: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSession( String ruleFile ) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

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


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

    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example 4
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void testEventsExpiredInThePast(final String drl) {
    final KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    final KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    final KieBase kieBase = helper.build( EventProcessingOption.STREAM );
    final KieSession kieSession = kieBase.newKieSession( sessionConfig, null );

    PseudoClockScheduler clock = kieSession.getSessionClock();

    final long currentTime = clock.getCurrentTime();

    clock.advanceTime(100, TimeUnit.MILLISECONDS);

    kieSession.insert(new BasicEvent(new Date(currentTime + 20), 10L, "20ms-30ms"));
    clock.advanceTime(1, TimeUnit.MILLISECONDS);
    kieSession.insert(new BasicEvent(new Date(currentTime + 20), 20L, "20ms-40ms"));

    clock.advanceTime(100, TimeUnit.MILLISECONDS);

    assertThat(kieSession.fireAllRules()).isEqualTo(1);
    clock.advanceTime(10, TimeUnit.MILLISECONDS);
    assertThat(kieSession.getObjects()).isEmpty();
}
 
Example 5
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private KieSession marsallStatefulKnowledgeSession(KieSession ksession) throws IOException,
                                                                                                   ClassNotFoundException {
    Globals globals = ksession.getGlobals();

    KieBase kbase = ksession.getKieBase();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    MarshallerFactory.newMarshaller( kbase ).marshall( out,
                                                       ksession );

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( TimerJobFactoryOption.get("trackable") );
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );

    Environment env = EnvironmentFactory.newEnvironment();
    env.set( EnvironmentName.GLOBALS, globals );
    ksession = MarshallerFactory.newMarshaller( kbase ).unmarshall( new ByteArrayInputStream( out.toByteArray() ), ksconf, env );

    return ksession;
}
 
Example 6
Source File: AbstractBaseTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieSession createKieSession(boolean serializeKbase, KiePackage... pkg) throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(Arrays.asList(pkg));
    if( serializeKbase ) { 
        kbase = JbpmSerializationHelper.serializeObject( kbase );
    }

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( ForceEagerActivationOption.YES );
    return kbase.newKieSession(conf, null);
}
 
Example 7
Source File: ActivationIteratorTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testFilteredEagerEvaluation() throws Exception {
    String str =
            "package org.simple \n" +
            "rule xxx @Propagation(EAGER) \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n" +
            "rule yyy @Propagation(EAGER) \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n";

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( new ForceEagerActivationOption.FILTERED( new ForceEagerActivationFilter() {
        @Override
        public boolean accept(Rule rule) {
            return rule.getName().equals("xxx");
        }
    }));

    KieBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = createKnowledgeSession(kbase, conf);

    final List list = new ArrayList();

    AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {
        public void matchCreated(org.kie.api.event.rule.MatchCreatedEvent event) {
            list.add("activated");
        }
    };
    ksession.addEventListener(agendaEventListener);

    ksession.insert("test");
    ((InternalWorkingMemory) ksession).flushPropagations();

    assertEquals(1, list.size());
}
 
Example 8
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBetaLeftExpired() {
    // DROOLS-1329
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "import " + B.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(11ms) end\n" +
                 "declare B @role( event ) @expires(11ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "  $b: B( id == $Aid )\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \",\" + $b + \"]\");" +
                 "  counter.incrementAndGet();\n" +
                 "end";

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

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();

    AtomicInteger counter = new AtomicInteger( 0 );
    ksession.setGlobal( "counter", counter );

    ksession.insert( new B(1) );

    sessionClock.advanceTime( 20, TimeUnit.MILLISECONDS );
    ksession.insert( new A(1) );

    ksession.fireAllRules();
    assertEquals(0, counter.get());
}
 
Example 9
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;
}
 
Example 10
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 11
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMarshallEntryPointsWithNot() throws Exception {
    String str =
            "package org.domain.test \n" +
                    "import " + getClass().getCanonicalName() + ".*\n" +
                    "global java.util.List list\n" +
                    "declare A\n" +
                    " @role( event )\n" +
                    " @expires( 10m )\n" +
                    "end\n" +
                    "declare B\n" +
                    "" +
                    " @role( event )\n" +
                    " @expires( 10m )\n" +
                    "end\n" +
                    "" +
                    "rule a1\n" +
                    "when\n" +
                    "   $a : A() from entry-point 'a-ep'\n" +
                    "   not B( this after[0s, 10s] $a) from entry-point 'a-ep'\n" +
                    "then\n" +
                    "list.add( $a );" +
                    "end\n";

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

    KieBase kBase = loadKnowledgeBaseFromString(config, str);

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );
    ksconf.setOption( TimerJobFactoryOption.get("trackable") );
    KieSession ksession = kBase.newKieSession( ksconf, null );

    List list = new ArrayList();
    ksession.setGlobal( "list", list );
    EntryPoint aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );

    ksession = marsallStatefulKnowledgeSession( ksession );

    PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock> getSessionClock();
    timeService.advanceTime( 3, TimeUnit.SECONDS );

    ksession = marsallStatefulKnowledgeSession( ksession );

    ksession.fireAllRules();

    ksession = marsallStatefulKnowledgeSession( ksession );

    assertEquals( 0,
                  list.size() );
}
 
Example 12
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMarshallEntryPointsWithSlidingLengthWindow() throws Exception {
    String str =
            "package org.domain.test \n" +
                    "import " + getClass().getCanonicalName() + ".*\n" +
                    "import java.util.List\n" +
                    "global java.util.List list\n" +
                    "declare A\n" +
                    " @role( event )\n" +
                    " @expires( 10m )\n" +
                    "end\n" +
                    "declare B\n" +
                    "" +
                    " @role( event )\n" +
                    " @expires( 10m )\n" +
                    "end\n" +
                    "" +
                    "rule a1\n" +
                    "when\n" +
                    "   $l : List() from collect( A()  over window:length(3) from entry-point 'a-ep') \n" +
                    "then\n" +
                    "   list.add( $l );" +
                    "end\n";

    KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    conf.setOption( EventProcessingOption.STREAM );
    final KieBase kbase = loadKnowledgeBaseFromString( conf, str );

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );
    ksconf.setOption( TimerJobFactoryOption.get("trackable") );
    KieSession ksession = createKnowledgeSession(kbase, ksconf);

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

    EntryPoint aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );
    ksession = marsallStatefulKnowledgeSession( ksession );

    aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );
    ksession = marsallStatefulKnowledgeSession( ksession );

    list.clear();
    ksession.fireAllRules();
    ksession = marsallStatefulKnowledgeSession( ksession );
    assertEquals( 2, ((List) list.get( 0 )).size() );

    aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );
    ksession = marsallStatefulKnowledgeSession( ksession );

    aep = ksession.getEntryPoint( "a-ep" );
    aep.insert( new A() );
    ksession = marsallStatefulKnowledgeSession( ksession );

    list.clear();
    ksession.fireAllRules();
    ksession = marsallStatefulKnowledgeSession( ksession );
    assertEquals( 3, ((List) list.get( 0 )).size() );
}
 
Example 13
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testBetaLeftExpired2() {
    // DROOLS-1329
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "import " + B.class.getCanonicalName() + "\n" +
                 "import " + C.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(31ms) end\n" +
                 "declare B @role( event ) @expires(11ms) end\n" +
                 "declare C @role( event ) @expires(31ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "  $b: B( $Bid: id == $Aid )\n" +
                 "  $c: C( id == $Bid )\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \",\" + $b + \",\" + $c + \"]\");" +
                 "  counter.incrementAndGet();\n" +
                 "end";

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

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();

    AtomicInteger counter = new AtomicInteger( 0 );
    ksession.setGlobal( "counter", counter );

    ksession.insert( new A(1) );
    ksession.insert( new B(1) );

    sessionClock.advanceTime( 20, TimeUnit.MILLISECONDS );
    ksession.insert( new C(1) );

    ksession.fireAllRules();
    assertEquals(0, counter.get());
}
 
Example 14
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSoftExpiration() {
    // DROOLS-1483
    String drl = "import " + ExpiringEventA.class.getCanonicalName() + "\n" +
                 "import " + ExpiringEventB.class.getCanonicalName() + "\n" +
                 "import " + ExpiringEventC.class.getCanonicalName() + "\n" +
                 "rule Ra when\n" +
                 "  $e : ExpiringEventA() over window:time(20s)\n" +
                 "then end\n " +
                 "rule Rb when\n" +
                 "  $e : ExpiringEventB() over window:time(20s)\n" +
                 "then end\n " +
                 "rule Rc when\n" +
                 "  $e : ExpiringEventC()\n" +
                 "then end\n";

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

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler clock = ksession.getSessionClock();

    ksession.insert( new ExpiringEventA() );
    ksession.insert( new ExpiringEventB() );
    ksession.insert( new ExpiringEventC() );
    ksession.fireAllRules();

    clock.advanceTime( 5, TimeUnit.SECONDS );
    ksession.fireAllRules();

    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventA.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventB.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventC.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=15 -> hard expiration of A
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventA.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventB.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventC.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=25 -> implicit expiration of B
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventA.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventB.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( ExpiringEventC.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=35 -> soft expiration of C
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventA.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventB.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( ExpiringEventC.class ) ).size() );
}
 
Example 15
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSoftExpirationWithDeclaration() {
    // DROOLS-1483
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "import " + B.class.getCanonicalName() + "\n" +
                 "import " + C.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(10s) end\n" +
                 "declare B @role( event ) @expires(value = 30s, policy = TIME_SOFT) end\n" +
                 "declare C @role( event ) @expires(value = 30s, policy = TIME_SOFT) end\n" +
                 "rule Ra when\n" +
                 "  $e : A() over window:time(20s)\n" +
                 "then end\n " +
                 "rule Rb when\n" +
                 "  $e : B() over window:time(20s)\n" +
                 "then end\n " +
                 "rule Rc when\n" +
                 "  $e : C()\n" +
                 "then end\n";

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

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler clock = ksession.getSessionClock();

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

    clock.advanceTime( 5, TimeUnit.SECONDS );
    ksession.fireAllRules();

    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( A.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( B.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( C.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=15 -> hard expiration of A
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( A.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( B.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( C.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=25 -> implicit expiration of B
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( A.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( B.class ) ).size() );
    assertEquals( 1, ksession.getObjects( new ClassObjectFilter( C.class ) ).size() );

    clock.advanceTime( 10, TimeUnit.SECONDS );
    ksession.fireAllRules();

    // t=35 -> soft expiration of C
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( A.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( B.class ) ).size() );
    assertEquals( 0, ksession.getObjects( new ClassObjectFilter( C.class ) ).size() );
}
 
Example 16
Source File: CommonTestMethodBase.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
protected KieSession createKieSession(KieBase kbase, KieSessionOption option) {
    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption(option);
    return kbase.newKieSession(ksconf, null);
}
 
Example 17
Source File: MultithreadTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled
public void testConcurrencyWithChronThreads() throws InterruptedException {

    final String drl = "package it.intext.drools.fusion.bug;\n" +
            "\n" +
            "import " + MyFact.class.getCanonicalName() + ";\n " +
            " global java.util.List list; \n" +
            "\n" +
            "declare MyFact\n" +
            "\t@role( event )\n" +
            "\t@expires( 1s )\n" +
            "end\n" +
            "\n" +
            "rule \"Dummy\"\n" +
            "timer( cron: 0/1 * * * * ? )\n" +
            "when\n" +
            "  Number( $count : intValue ) from accumulate( MyFact( ) over window:time(1s); sum(1) )\n" +
            "then\n" +
            "    System.out.println($count+\" myfact(s) seen in the last 1 seconds\");\n" +
            "    list.add( $count ); \n" +
            "end";

    final KieBaseConfiguration kbconfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconfig.setOption(EventProcessingOption.STREAM);

    final KieBase kbase = loadKnowledgeBaseFromString(kbconfig, drl);

    final KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ClockTypeOption.get("REALTIME"));
    final KieSession ksession = kbase.newKieSession(conf, null);

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

    ksession.fireAllRules();

    final Runner t = new Runner(ksession);
    t.start();
    try {
        final int FACTS_PER_POLL = 1000;
        final int POLL_INTERVAL = 500;

        final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        try {
            executor.scheduleAtFixedRate(
                    () -> {
                        for (int j = 0; j < FACTS_PER_POLL; j++) {
                            ksession.insert(new MyFact());
                        }
                    },
                    0,
                    POLL_INTERVAL,
                    TimeUnit.MILLISECONDS);

            Thread.sleep(10200);
        } finally {
            executor.shutdownNow();
        }
    } finally {
        ksession.halt();
        ksession.dispose();
    }

    t.join();

    if (t.getError() != null) {
        Assertions.fail(t.getError().getMessage());
    }

    System.out.println("Final size " + ksession.getObjects().size());

    ksession.dispose();
}
 
Example 18
Source File: ParallelEvaluationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testEventsExpiration() {
    StringBuilder sb = new StringBuilder( 400 );
    sb.append( "global java.util.List list;\n" );
    sb.append( "import " + MyEvent.class.getCanonicalName() + ";\n" );
    sb.append( "declare MyEvent @role( event ) @expires( 20ms ) @timestamp( timestamp ) end\n" );
    for (int i = 0; i < 10; i++) {
        sb.append( getRuleWithEvent( i ) );
    }

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

    KieSession ksession = new KieHelper().addContent( sb.toString(), ResourceType.DRL )
                                         .build( EventProcessingOption.STREAM, MultithreadEvaluationOption.YES )
                                         .newKieSession( sessionConfig, null );

    assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();
    sessionClock.setStartupTime(0);

    List<Integer> list = new DebugList<Integer>();
    ksession.setGlobal( "list", list );

    for (int i = 0; i < 10; i++) {
        ksession.insert( new MyEvent( i, i*2L ) );
    }

    ksession.fireAllRules();

    assertEquals(10, list.size());
    assertEquals( 10L, ksession.getFactCount() );

    sessionClock.advanceTime( 29, TimeUnit.MILLISECONDS );
    ksession.fireAllRules();
    assertEquals( 5L, ksession.getFactCount() );

    sessionClock.advanceTime( 12, TimeUnit.MILLISECONDS );
    ksession.fireAllRules();
    assertEquals( 0L, ksession.getFactCount() );
}
 
Example 19
Source File: StrictAnnotationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testEagerEvaluation() {
    String str =
            "package org.simple \n" +
            "@Propagation(EAGER) rule xxx \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n" +
            "@Propagation(EAGER) rule yyy \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n";

    KieServices ks = KieServices.Factory.get();

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ForceEagerActivationOption.YES);

    KieSession ksession = new KieHelper()
            .setKieModuleModel(ks.newKieModuleModel()
                                 .setConfigurationProperty(LanguageLevelOption.PROPERTY_NAME,
                                                           LanguageLevelOption.DRL6_STRICT.toString()))
            .addContent(str, ResourceType.DRL)
            .build()
            .newKieSession(conf, null);
    try {
        final List list = new ArrayList();

        AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {
            public void matchCreated(org.kie.api.event.rule.MatchCreatedEvent event) {
                list.add("activated");
            }
        };
        ksession.addEventListener(agendaEventListener);

        ksession.insert("test");
        assertEquals(2, list.size());
    } finally {
        ksession.dispose();
    }
}
 
Example 20
Source File: WindowTest.java    From kogito-runtimes with Apache License 2.0 3 votes vote down vote up
@BeforeEach
public void initialization() {
    KieFileSystem kfs = KieServices.Factory.get().newKieFileSystem();

    kfs.write("src/main/resources/kbase1/window_test.drl", drl);

    KieBuilder kbuilder = KieServices.Factory.get().newKieBuilder(kfs);

    kbuilder.buildAll();

    List<Message> res = kbuilder.getResults().getMessages(Level.ERROR);

    assertEquals(0, res.size(), res.toString());

    KieBaseConfiguration kbconf = KnowledgeBaseFactory
            .newKnowledgeBaseConfiguration();

    kbconf.setOption(EventProcessingOption.STREAM);

    KieBase kbase = KieServices.Factory.get()
                               .newKieContainer(kbuilder.getKieModule().getReleaseId())
                               .newKieBase(kbconf);

    KieSessionConfiguration ksconfig = KnowledgeBaseFactory
            .newKnowledgeSessionConfiguration();
    ksconfig.setOption(ClockTypeOption.get("pseudo"));

    ksession = kbase.newKieSession(ksconfig, null);

    clock = ksession.getSessionClock();
}