Search in sources :

Example 46 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testEventStreamWithEPsAndDefaultPseudo.

@Test
public void testEventStreamWithEPsAndDefaultPseudo() throws InterruptedException {
    // DROOLS-286
    String drl = "\n" + "import java.util.*;\n" + "import org.drools.compiler.integrationtests.CepEspTest.MyEvent; \n" + "" + "declare MyEvent\n" + "    @role(event)\n" + "    @timestamp(timestamp)\n" + "end\n" + "\n" + "" + "global java.util.List list; \n" + "" + "rule \"over 0.3s\"\n" + "salience 1 \n" + "    when\n" + "        $list: List() from collect(MyEvent() over window:time(300ms))\n" + "    then\n" + "        System.out.println(\"Rule: with in 0.3s --> \" + $list);\n" + "        list.add( 'r1:' + $list.size() ); \n" + "end\n" + "\n" + "rule \"over 1s\"\n" + "salience 2 \n" + "    when\n" + "        $list: List() from collect(MyEvent() over window:time(1s))\n" + "    then\n" + "        System.out.println(\"Rule: with in 1s --> \" + $list);\n" + "        list.add( 'r2:' + $list.size() ); \n" + "end\n" + "\n" + "rule \"over 3s\"\n" + "salience 3 \n" + "    when\n" + "        $list: List() from collect(MyEvent() over window:time(3s))\n" + "    then\n" + "        System.out.println(\"Rule: with in 3s --> \" + $list);\n" + "        list.add( 'r3:' + $list.size() ); \n" + "end\n" + "\n" + "rule \"over 0.3s ep\"\n" + "salience 4 \n" + "    when\n" + "        $list: List() from collect(MyEvent() over window:time(300ms) from entry-point \"stream\")\n" + "    then\n" + "        System.out.println(\"Rule: with in 0.3s use ep --> \" + $list);\n" + "        list.add( 'r4:' + $list.size() ); \n" + "end\n" + "\n" + "rule \"over 1s ep\"\n" + "salience 5 \n" + "    when\n" + "        $list: List() from collect(MyEvent() over window:time(1s) from entry-point \"stream\")\n" + "    then\n" + "        System.out.println(\"Rule: with in 1s use ep --> \" + $list);\n" + "        list.add( 'r5:' + $list.size() ); \n" + "end\n" + "\n" + "rule \"over 3s ep\"\n" + "salience 6 \n" + "    when\n" + "        $list: List() from collect(MyEvent() over window:time(3s) from entry-point \"stream\")\n" + "    then\n" + "        System.out.println(\"Rule: with in 3s use ep --> \" + $list);\n" + "        list.add( 'r6:' + $list.size() ); \n" + "end";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    KieBaseConfiguration baseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    baseConfig.setOption(EventProcessingOption.STREAM);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(baseConfig);
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));
    // init stateful knowledge session
    KieSession ksession = kbase.newKieSession(sessionConfig, null);
    SessionPseudoClock clock = ksession.getSessionClock();
    ArrayList list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.fireAllRules();
    list.clear();
    for (int j = 0; j < 5; j++) {
        clock.advanceTime(500, TimeUnit.MILLISECONDS);
        ksession.insert(new MyEvent(clock.getCurrentTime()));
        ksession.getEntryPoint("stream").insert(new MyEvent(clock.getCurrentTime()));
        clock.advanceTime(500, TimeUnit.MILLISECONDS);
        ksession.fireAllRules();
        System.out.println(list);
        switch(j) {
            case 0:
                assertEquals(Arrays.asList("r6:1", "r5:1", "r3:1", "r2:1"), list);
                break;
            case 1:
                assertEquals(Arrays.asList("r6:2", "r5:1", "r3:2", "r2:1"), list);
                break;
            case 2:
            case 3:
            case 4:
                assertEquals(Arrays.asList("r6:3", "r5:1", "r3:3", "r2:1"), list);
                break;
            default:
                fail();
        }
        list.clear();
        System.out.println("-------------- SLEEP ------------");
    }
    ksession.dispose();
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) Test(org.junit.Test)

Example 47 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testExpirationOnModification.

@Test
public void testExpirationOnModification() throws InterruptedException {
    // DROOLS-374
    String drl = "\n" + "import java.util.*;\n" + "global List list; " + "declare SomeEvent\n" + "    @role( event )\n" + "    @expires( 200ms )\n" + "  done : boolean = false \n" + "end\n" + "rule Count \n" + "  no-loop \n " + "    when " + "        $ev : SomeEvent( done == false  ) " + "        accumulate ( SomeEvent() over window:time( 10s )," + "                     $num : count( 1 ) )\n" + "    then\n" + // ok, modifies should never happen. But they are allowed, and if they do happen, the behaviour should be consistent
    "        modify ( $ev ) { setDone( true ); } " + "        list.add( $num ); \n" + "end\n" + "rule Init \n" + "    when\n" + "      $s : String() " + "    then\n" + "      retract( $s ); " + "      insert( new SomeEvent() ); " + "end\n" + "";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    KieBaseConfiguration baseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    baseConfig.setOption(EventProcessingOption.STREAM);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(baseConfig);
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));
    // init stateful knowledge session
    KieSession ksession = kbase.newKieSession(sessionConfig, null);
    SessionPseudoClock clock = ksession.getSessionClock();
    ArrayList list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.insert("go");
    ksession.fireAllRules();
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.insert("go");
    ksession.fireAllRules();
    clock.advanceTime(500, TimeUnit.MILLISECONDS);
    ksession.insert("go");
    ksession.fireAllRules();
    assertEquals(Arrays.asList(1L, 2L, 1L), list);
    ksession.dispose();
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 48 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testIdleTimeAndTimeToNextJob.

@Test(timeout = 10000)
public void testIdleTimeAndTimeToNextJob() throws Exception {
    // read in the source
    KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    conf.setOption(EventProcessingOption.STREAM);
    final KieBase kbase = loadKnowledgeBase(conf, "test_CEP_SimpleTimeWindow.drl");
    KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sconf.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));
    StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) createKnowledgeSession(kbase, sconf);
    WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger((WorkingMemory) wm);
    File testTmpDir = new File("target/test-tmp/");
    testTmpDir.mkdirs();
    logger.setFileName("target/test-tmp/testIdleTimeAndTimeToNextJob-audit");
    try {
        List results = new ArrayList();
        wm.setGlobal("results", results);
        // how to initialize the clock?
        // how to configure the clock?
        SessionPseudoClock clock = (SessionPseudoClock) wm.getSessionClock();
        clock.advanceTime(5, // 5 seconds
        TimeUnit.SECONDS);
        // there is no next job, so returns -1
        assertEquals(-1, wm.getTimeToNextJob());
        wm.insert(new OrderEvent("1", "customer A", 70));
        wm.fireAllRules();
        assertEquals(0, wm.getIdleTime());
        // now, there is a next job in 30 seconds: expire the event
        assertEquals(30000, wm.getTimeToNextJob());
        wm.fireAllRules();
        assertEquals(1, results.size());
        assertEquals(70, ((Number) results.get(0)).intValue());
        // advance clock and assert new data
        clock.advanceTime(10, // 10 seconds
        TimeUnit.SECONDS);
        // next job is in 20 seconds: expire the event
        assertEquals(20000, wm.getTimeToNextJob());
        wm.insert(new OrderEvent("2", "customer A", 60));
        wm.fireAllRules();
        assertEquals(2, results.size());
        assertEquals(65, ((Number) results.get(1)).intValue());
        // advance clock and assert new data
        clock.advanceTime(10, // 10 seconds
        TimeUnit.SECONDS);
        // next job is in 10 seconds: expire the event
        assertEquals(10000, wm.getTimeToNextJob());
        wm.insert(new OrderEvent("3", "customer A", 50));
        wm.fireAllRules();
        assertEquals(3, results.size());
        assertEquals(60, ((Number) results.get(2)).intValue());
        // advance clock and assert new data
        clock.advanceTime(10, // 10 seconds
        TimeUnit.SECONDS);
        // advancing clock time will cause events to expire
        assertEquals(0, wm.getIdleTime());
        // next job is in 10 seconds: expire another event
        // assertEquals( 10000, iwm.getTimeToNextJob());
        wm.insert(new OrderEvent("4", "customer A", 25));
        wm.fireAllRules();
        // first event should have expired, making average under the rule threshold, so no additional rule fire
        assertEquals(3, results.size());
        // advance clock and assert new data
        clock.advanceTime(10, // 10 seconds
        TimeUnit.SECONDS);
        wm.insert(new OrderEvent("5", "customer A", 70));
        assertEquals(0, wm.getIdleTime());
        // wm  = SerializationHelper.serializeObject(wm);
        wm.fireAllRules();
        // still under the threshold, so no fire
        assertEquals(3, results.size());
    } finally {
        logger.writeToDisk();
    }
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) WorkingMemoryFileLogger(org.drools.core.audit.WorkingMemoryFileLogger) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) KieBase(org.kie.api.KieBase) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) OrderEvent(org.drools.compiler.OrderEvent) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 49 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method AfterOperatorInCEPQueryTest.

@Test
public void AfterOperatorInCEPQueryTest() {
    String drl = "package org.drools;\n" + "import org.drools.compiler.StockTick; \n" + "\n" + "declare StockTick\n" + "    @role( event )\n" + "end\n" + "\n" + "query EventsBeforeNineSeconds\n" + "   $event : StockTick() from entry-point EStream\n" + "   $result : StockTick ( this after [0s, 9s] $event) from entry-point EventStream\n" + "end\n" + "\n" + "query EventsBeforeNineteenSeconds\n" + "   $event : StockTick() from entry-point EStream\n" + "   $result : StockTick ( this after [0s, 19s] $event) from entry-point EventStream\n" + "end\n" + "\n" + "query EventsBeforeHundredSeconds\n" + "   $event : StockTick() from entry-point EStream\n" + "   $result : StockTick ( this after [0s, 100s] $event) from entry-point EventStream\n" + "end\n";
    final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconf.setOption(EventProcessingOption.STREAM);
    final KieBase kbase = loadKnowledgeBaseFromString(kbconf, drl);
    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));
    KieSession ksession = createKnowledgeSession(kbase, ksconf);
    SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock();
    EntryPoint ePoint = ksession.getEntryPoint("EStream");
    EntryPoint entryPoint = ksession.getEntryPoint("EventStream");
    ePoint.insert(new StockTick(0L, "zero", 0.0, 0));
    entryPoint.insert(new StockTick(1L, "one", 0.0, 0));
    clock.advanceTime(10, TimeUnit.SECONDS);
    entryPoint.insert(new StockTick(2L, "two", 0.0, 0));
    clock.advanceTime(10, TimeUnit.SECONDS);
    entryPoint.insert(new StockTick(3L, "three", 0.0, 0));
    QueryResults results = ksession.getQueryResults("EventsBeforeNineSeconds");
    assertEquals(0, results.size());
    results = ksession.getQueryResults("EventsBeforeNineteenSeconds");
    assertEquals(0, results.size());
    results = ksession.getQueryResults("EventsBeforeHundredSeconds");
    assertEquals(1, results.size());
    ksession.dispose();
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) StockTick(org.drools.compiler.StockTick) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) KieBase(org.kie.api.KieBase) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) KieSession(org.kie.api.runtime.KieSession) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) QueryResults(org.kie.api.runtime.rule.QueryResults) Test(org.junit.Test)

Example 50 with SessionPseudoClock

use of org.kie.api.time.SessionPseudoClock in project drools by kiegroup.

the class CepEspTest method testDuplicateFiring2.

@Test
public void testDuplicateFiring2() throws InterruptedException {
    String drl = "package org.test;\n" + "import org.drools.compiler.StockTick;\n " + "" + "global java.util.List list \n" + "" + "declare StockTick @role(event) end \n" + "" + "rule Tick when $s : StockTick() then System.out.println( $s ); end \n" + "" + "rule \"slidingTimeCount\"\n" + "when\n" + "\t$n: Number ( intValue > 0 ) from accumulate ( $e: StockTick() over window:time(3s), count($e))\n" + "then\n" + "  list.add( $n ); \n" + "  System.out.println( \"Events in last 3 seconds: \" + $n );\n" + "end" + "";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    // Check the builder for errors
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    // configure knowledge base
    KieBaseConfiguration baseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    baseConfig.setOption(EventProcessingOption.CLOUD);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(baseConfig);
    kbase.addPackages(kbuilder.getKnowledgePackages());
    // init session clock
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption(ClockTypeOption.get("pseudo"));
    // init stateful knowledge session
    KieSession ksession = kbase.newKieSession(sessionConfig, null);
    SessionPseudoClock clock = ksession.getSessionClock();
    ArrayList list = new ArrayList();
    ksession.setGlobal("list", list);
    // insert events
    for (int i = 1; i < 3; i++) {
        StockTick event = new StockTick((i - 1), "XXX", 1.0, 0);
        clock.advanceTime(1001, TimeUnit.MILLISECONDS);
        ksession.insert(event);
        System.out.println(i + ". rule invocation");
        ksession.fireAllRules();
    }
    clock.advanceTime(3001, TimeUnit.MILLISECONDS);
    StockTick event = new StockTick(3, "XXX", 1.0, 0);
    System.out.println("3. rule invocation");
    ksession.insert(event);
    ksession.fireAllRules();
    clock.advanceTime(3001, TimeUnit.MILLISECONDS);
    StockTick event2 = new StockTick(3, "XXX", 1.0, 0);
    System.out.println("4. rule invocation");
    ksession.insert(event2);
    ksession.fireAllRules();
    ksession.dispose();
    assertEquals(Arrays.asList(1L, 2L, 1L, 1L), list);
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) StockTick(org.drools.compiler.StockTick) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) Test(org.junit.Test)

Aggregations

SessionPseudoClock (org.kie.api.time.SessionPseudoClock)74 Test (org.junit.Test)66 KieSession (org.kie.api.runtime.KieSession)52 KieSessionConfiguration (org.kie.api.runtime.KieSessionConfiguration)39 KieBase (org.kie.api.KieBase)37 ArrayList (java.util.ArrayList)30 KieBaseConfiguration (org.kie.api.KieBaseConfiguration)20 MessageEvent (org.drools.testcoverage.common.model.MessageEvent)15 EntryPoint (org.kie.api.runtime.rule.EntryPoint)15 StockTick (org.drools.compiler.StockTick)14 Message (org.drools.testcoverage.common.model.Message)14 List (java.util.List)13 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)13 NamedEntryPoint (org.drools.core.common.NamedEntryPoint)12 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)11 StockTick (org.drools.modelcompiler.domain.StockTick)10 OrderEvent (org.drools.compiler.OrderEvent)6 QueryResults (org.kie.api.runtime.rule.QueryResults)4 KieHelper (org.kie.internal.utils.KieHelper)4 StockTickInterface (org.drools.compiler.StockTickInterface)3