Java Code Examples for org.kie.api.runtime.KieSession#getSessionClock()

The following examples show how to use org.kie.api.runtime.KieSession#getSessionClock() . 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: 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 2
Source File: AdvanceSessionTimeCommand.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public Long execute(Context context ) {
    KieSession ksession = ((RegistryContext)context).lookup( KieSession.class );
    SessionPseudoClock sessionClock = ksession.<SessionPseudoClock>getSessionClock();

    sessionClock.advanceTime( amount, unit );
    long result = sessionClock.getCurrentTime();

    ExecutionResultImpl results = ((RegistryContext)context).lookup( ExecutionResultImpl.class );
    if ( results != null ) {
        results.getResults().put( this.outIdentifier, result );
    }
    return result;
}
 
Example 3
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBetaRightExpired() {
    // 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 A(1) );

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

    ksession.fireAllRules();
    assertEquals(0, counter.get());
}
 
Example 4
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 5
Source File: PseudoClockRunner.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void updateKieSessionTime(long timeNow, long distance, KieSession ksession) {
    SessionPseudoClock clock = ksession.getSessionClock();

    if (clock.getCurrentTime() != timeNow) {
        long newTime = startTime + distance;
        long currentTime = clock.getCurrentTime();
        clock.advanceTime(newTime - currentTime,
                          TimeUnit.MILLISECONDS);
    }
}
 
Example 6
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 7
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAlpha() {
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(11ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \"]\");" +
                 "  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) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
    ksession.insert( new A(2) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
    ksession.fireAllRules();
    assertEquals(2, counter.get());
}
 
Example 8
Source File: KieSessionUtils.java    From hacep with Apache License 2.0 5 votes vote down vote up
public static void advanceClock(KieSession kieSession, Fact fact) {
    SessionPseudoClock clock = kieSession.getSessionClock();
    long gts = fact.getInstant().toEpochMilli();
    long current = clock.getCurrentTime();
    if (gts < current) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(String.format("Moving clock backwards. New Clock is [%s], current was [%s]", gts, current));
        }
    }
    clock.advanceTime(gts - current, TimeUnit.MILLISECONDS);
}
 
Example 9
Source File: FirstOrderLogicTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testForallWithSlidingWindow() throws Exception {
    final KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    KieBase kbase = loadKnowledgeBase( "test_ForallSlidingWindow.drl");
    KieSession ksession = createKnowledgeSession(kbase, conf);

    final SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock();
    List<String> results = new ArrayList<String>();
    ksession.setGlobal( "results",
                        results );

    // advance time... no events, so forall should fire 
    clock.advanceTime( 60,
                       TimeUnit.SECONDS );
    ksession.fireAllRules();
    assertEquals( 1,
                  results.size() );

    int seq = 1;
    // advance time... there are matching events now, but forall still not fire 
    ksession.insert( new StockTick( seq++,
                                    "RHT",
                                    10,
                                    clock.getCurrentTime() ) ); // 60 
    clock.advanceTime( 5,
                       TimeUnit.SECONDS );
    ksession.fireAllRules();
    assertEquals( 1,
                  results.size() );
    ksession.insert( new StockTick( seq++,
                                    "RHT",
                                    10,
                                    clock.getCurrentTime() ) ); // 65 
    clock.advanceTime( 5,
                       TimeUnit.SECONDS );
    ksession.fireAllRules();
    assertEquals( 1,
                  results.size() );

    // advance time... there are non-matching events now, so forall de-activates 
    ksession.insert( new StockTick( seq++,
                                    "IBM",
                                    10,
                                    clock.getCurrentTime() ) ); // 70 
    clock.advanceTime( 10,
                       TimeUnit.SECONDS );
    ksession.fireAllRules();
    assertEquals( 1,
                  results.size() );

    // advance time... there are non-matching events now, so forall is still deactivated 
    ksession.insert( new StockTick( seq++,
                                    "RHT",
                                    10,
                                    clock.getCurrentTime() ) ); // 80 
    clock.advanceTime( 10,
                       TimeUnit.SECONDS );
    ksession.fireAllRules();
    assertEquals( 1,
                  results.size() );

    // advance time... non-matching event expires now, so forall should fire 
    ksession.insert( new StockTick( seq++,
                                    "RHT",
                                    10,
                                    clock.getCurrentTime() ) ); // 90 
    clock.advanceTime( 10,
                       TimeUnit.SECONDS );
    ksession.fireAllRules();
    assertEquals( 2,
                  results.size() );

    // advance time... forall still matches and should not fire 
    ksession.insert( new StockTick( seq++,
                                    "RHT",
                                    10,
                                    clock.getCurrentTime() ) ); // 100 
    clock.advanceTime( 10,
                       TimeUnit.SECONDS );
    ksession.fireAllRules();
    assertEquals( 2,  
                  results.size() );

    // advance time... forall still matches and should not fire 
    clock.advanceTime( 60,
                       TimeUnit.SECONDS );
    ksession.fireAllRules();
    assertEquals( 2,  
                  results.size() );

}
 
Example 10
Source File: GetSessionClockCommand.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public SessionClock execute(Context context) {
    KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
    return ksession.<SessionClock>getSessionClock();
}
 
Example 11
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSnapshotRecoveryScheduledRulesPlain() throws Exception {
    // DROOLS-1537
    String drl = "package com.drools.restore.reproducer\n" +
                 "global java.util.List list;\n" +
                 "global java.util.List list2;\n" +
                 "rule R1\n" +
                 " timer (int: 20s)\n" +
                 " when\n" +
                 "   $m : String( this == \"Hello World1\" )\n" +
                 " then\n" +
                 "   list.add( $m );\n" +
                 "   retract( $m );\n" +
                 "end\n" +
                 "rule R2\n" +
                 " timer (int: 30s)\n" +
                 " when\n" +
                 "   $m : String( this == \"Hello World2\" )\n" +
                 " then\n" +
                 "   list2.add( $m );\n" +
                 "   retract( $m );\n" +
                 "end\n";

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );
    ksconf.setOption( TimedRuleExecutionOption.YES );
    ksconf.setOption(TimerJobFactoryOption.get("trackable"));
    ksconf.setOption(ClockTypeOption.get("pseudo"));

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

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

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

    ksession.insert("Hello World1");
    ksession.insert("Hello World2");

    ksession.fireAllRules();
    timeService.advanceTime(10500, TimeUnit.MILLISECONDS);

    KieBase kbase2 = new KieHelper().addContent( drl, ResourceType.DRL )
                                    .build( EventProcessingOption.STREAM );

    ksession = marshallAndUnmarshall( kbase1, kbase2, ksession, ksconf );
    ksession.setGlobal("list", list);
    ksession.setGlobal("list2", list2);

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

    ksession.fireAllRules();

    long accumulatedSleepTime = 0;
    for (int i = 0; i < 6; i++) {
        timeService2.advanceTime(5050, TimeUnit.MILLISECONDS);
        accumulatedSleepTime += 5050;
        assertEquals( i < 1 ? 0 : 1, list.size() );
        assertEquals( i < 3 ? 0 : 1, list2.size() );
    }
}
 
Example 12
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testMarshallWithTimedRule() {
    // DROOLS-795
    String drl = "rule \"Rule A Timeout\"\n" +
                 "when\n" +
                 "    String( this == \"ATrigger\" )\n" +
                 "then\n" +
                 "   insert (new String( \"A-Timer\") );\n" +
                 "end\n" +
                 "\n" +
                 "rule \"Timer For rule A Timeout\"\n" +
                 "    timer ( int: 5s )\n" +
                 "when\n" +
                 "   String( this == \"A-Timer\")\n" +
                 "then\n" +
                 "   delete ( \"A-Timer\" );\n" +
                 "   delete ( \"ATrigger\" );\n" +
                 "end\n";

    KieBase kbase = new KieHelper().addContent( drl, ResourceType.DRL )
                                   .build( EqualityBehaviorOption.EQUALITY,
                                           DeclarativeAgendaOption.ENABLED,
                                           EventProcessingOption.STREAM );

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( "pseudo" ) );
    KieSession ksession = kbase.newKieSession(sessionConfig, null);

    ksession.insert( "ATrigger" );

    assertEquals( 1, ksession.getFactCount() );
    ksession.fireAllRules();
    assertEquals( 2, ksession.getFactCount() );

    SessionPseudoClock clock = ksession.getSessionClock();
    clock.advanceTime( 4, TimeUnit.SECONDS );

    assertEquals( 2, ksession.getFactCount() );
    ksession.fireAllRules();
    assertEquals( 2, ksession.getFactCount() );

    ksession = marshallAndUnmarshall( kbase, ksession, sessionConfig);
    clock = ksession.getSessionClock();

    clock.advanceTime( 4, TimeUnit.SECONDS );

    assertEquals( 2, ksession.getFactCount() );
    ksession.fireAllRules();
    assertEquals( 0, ksession.getFactCount() );
}
 
Example 13
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test @Disabled("beta4 phreak")
public void testMarshallEntryPointsWithSlidingTimeWindow() 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:time(30s) 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() );

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

    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( 4, ((List) list.get( 0 )).size() );

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

    list.clear();
    ksession.fireAllRules();
    assertEquals( 2, ((List) list.get( 0 )).size() );
}
 
Example 14
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test @Disabled("This test is suspicious to say the least...")
public void testScheduledActivation() {
    KnowledgeBaseImpl knowledgeBase = (KnowledgeBaseImpl) KnowledgeBaseFactory.newKnowledgeBase();
    KnowledgePackageImpl impl = new KnowledgePackageImpl( "test" );

    BuildContext buildContext = new BuildContext( knowledgeBase );
    //simple rule that fires after 10 seconds
    final RuleImpl rule = new RuleImpl( "test-rule" );
    new RuleTerminalNode( 1, new MockTupleSource( 2 ), rule, rule.getLhs(), 0, buildContext );

    final List<String> fired = new ArrayList<String>();

    rule.setConsequence( new Consequence() {
        public void evaluate(KnowledgeHelper knowledgeHelper,
                             WorkingMemory workingMemory) throws Exception {
            fired.add( "a" );
        }

        public String getName() {
            return "default";
        }
    } );

    rule.setTimer( new DurationTimer( 10000 ) );
    rule.setPackage( "test" );
    impl.addRule( rule );

    knowledgeBase.addPackages( Collections.singleton( impl ) );
    SessionConfiguration config = SessionConfiguration.newInstance();
    config.setClockType( ClockType.PSEUDO_CLOCK );
    KieSession ksession = knowledgeBase.newKieSession( config, KieServices.get().newEnvironment() );
    PseudoClockScheduler scheduler = (PseudoClockScheduler) ksession.<SessionClock> getSessionClock();
    Marshaller marshaller = MarshallerFactory.newMarshaller( knowledgeBase );

    ksession.insert( "cheese" );
    assertTrue( fired.isEmpty() );
    //marshall, then unmarshall session
    readWrite( knowledgeBase, ksession, config );
    //the activations should fire after 10 seconds
    assertTrue( fired.isEmpty() );
    scheduler.advanceTime( 12, TimeUnit.SECONDS );
    assertFalse( fired.isEmpty() );

}
 
Example 15
Source File: ParallelEvaluationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testFireUntilHaltWithExpiration2() throws InterruptedException {
    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" +
            "global java.util.concurrent.CountDownLatch fireLatch;\n" +
            "rule R0 when\n" +
            "  $A: A( $Aid : value > 0 )\n" +
            "  $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" +
            "then\n" +
            "  counter.incrementAndGet();\n" +
            "  fireLatch.countDown();" +
            "end\n" +
            "rule R1 when\n" +
            "  $A: A( $Aid: value > 1 )\n" +
            "  $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" +
            "then\n" +
            "  counter.incrementAndGet();\n" +
            "  fireLatch.countDown();" +
            "end\n" +
            "rule R2 when\n" +
            "  $A: A( $Aid: value > 2 )\n" +
            "  $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" +
            "then\n" +
            "  counter.incrementAndGet();\n" +
            "  fireLatch.countDown();" +
            "end\n" +
            "rule R3 when\n" +
            "  $A: A( $Aid: value > 3 )\n" +
            "  $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" +
            "then\n" +
            "  counter.incrementAndGet();\n" +
            "  fireLatch.countDown();" +
            "end";

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

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

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

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

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

        new Thread( () -> ksession.fireUntilHalt() ).start();

        int eventsNr = 5;
        final CountDownLatch fireLatch = new CountDownLatch(eventsNr * 4);
        ksession.setGlobal("fireLatch", fireLatch);
        for ( int i = 0; i < eventsNr; i++ ) {
            ksession.insert( new A( i + 4 ) );
            ksession.insert( new B( i + 4 ) );
            sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
        }

        fireLatch.await();
        assertEquals( eventsNr * 4, counter.get() );
    } finally {
        ksession.halt();
        ksession.dispose();
    }
}
 
Example 16
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 17
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 18
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 19
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 20
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testBeta() {
    // 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( ($Bid: id <= $Aid) && (id > ($Aid - 1 )))\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 A(1) );
    ksession.insert( new B(1) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
    ksession.insert( new A(2) );
    ksession.insert( new B(2) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );

    ksession.fireAllRules();
    assertEquals(2, counter.get());
}