Search in sources :

Example 66 with AgendaEventListener

use of org.kie.api.event.rule.AgendaEventListener in project drools by kiegroup.

the class KieLoggersTest method testKieConsoleLoggerStateless.

@Test
public void testKieConsoleLoggerStateless() throws Exception {
    String drl = "package org.drools.integrationtests\n" + "import org.drools.mvel.compiler.Message;\n" + "rule \"Hello World\"\n" + "    when\n" + "        m : Message( myMessage : message )\n" + "    then\n" + "end";
    // get the resource
    Resource dt = ResourceFactory.newByteArrayResource(drl.getBytes()).setTargetPath("org/drools/integrationtests/hello.drl");
    // create the builder
    StatelessKieSession ksession = getStatelessKieSession(dt);
    KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newConsoleLogger(ksession);
    AgendaEventListener ael = mock(AgendaEventListener.class);
    ksession.addEventListener(ael);
    ksession.execute(new Message("Hello World"));
    verify(ael).afterMatchFired(any(AfterMatchFiredEvent.class));
    logger.close();
}
Also used : KieRuntimeLogger(org.kie.api.logger.KieRuntimeLogger) Message(org.drools.mvel.compiler.Message) Resource(org.kie.api.io.Resource) StatelessKieSession(org.kie.api.runtime.StatelessKieSession) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) Test(org.junit.Test)

Example 67 with AgendaEventListener

use of org.kie.api.event.rule.AgendaEventListener in project drools by kiegroup.

the class SequentialTest method testEvents.

@Test
public void testEvents() throws Exception {
    String str = "";
    str += "package org.drools.mvel.compiler.test\n";
    str += "import org.drools.mvel.compiler.Message\n";
    str += "rule \"Hello World\"\n";
    str += "when\n";
    str += "    Message( )\n";
    str += "then\n";
    str += "    System.out.println( drools.getKieRuntime() );\n";
    str += "end\n";
    final KieModule kieModule = KieUtil.getKieModuleFromDrls("test", kieBaseTestConfiguration, str);
    final KieBase kbase = KieBaseUtil.newKieBaseFromKieModuleWithAdditionalOptions(kieModule, kieBaseTestConfiguration, SequentialOption.YES);
    StatelessKieSession ksession = kbase.newStatelessKieSession();
    final List list = new ArrayList();
    ksession.addEventListener(new AgendaEventListener() {

        public void matchCancelled(MatchCancelledEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void matchCreated(MatchCreatedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void afterMatchFired(AfterMatchFiredEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void agendaGroupPopped(AgendaGroupPoppedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void agendaGroupPushed(AgendaGroupPushedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void beforeMatchFired(BeforeMatchFiredEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void beforeRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void afterRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void beforeRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }
    });
    ksession.addEventListener(new RuleRuntimeEventListener() {

        public void objectInserted(ObjectInsertedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void objectDeleted(ObjectDeletedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }

        public void objectUpdated(ObjectUpdatedEvent event) {
            assertNotNull(event.getKieRuntime());
            list.add(event);
        }
    });
    ksession.execute(new Message("help"));
    assertEquals(4, list.size());
}
Also used : Message(org.drools.mvel.compiler.Message) ArrayList(java.util.ArrayList) ObjectUpdatedEvent(org.kie.api.event.rule.ObjectUpdatedEvent) RuleFlowGroupDeactivatedEvent(org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent) ObjectInsertedEvent(org.kie.api.event.rule.ObjectInsertedEvent) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) AgendaGroupPoppedEvent(org.kie.api.event.rule.AgendaGroupPoppedEvent) ObjectDeletedEvent(org.kie.api.event.rule.ObjectDeletedEvent) RuleFlowGroupActivatedEvent(org.kie.api.event.rule.RuleFlowGroupActivatedEvent) RuleRuntimeEventListener(org.kie.api.event.rule.RuleRuntimeEventListener) KieBase(org.kie.api.KieBase) MatchCancelledEvent(org.kie.api.event.rule.MatchCancelledEvent) StatelessKieSession(org.kie.api.runtime.StatelessKieSession) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) BeforeMatchFiredEvent(org.kie.api.event.rule.BeforeMatchFiredEvent) ArrayList(java.util.ArrayList) List(java.util.List) AgendaGroupPushedEvent(org.kie.api.event.rule.AgendaGroupPushedEvent) MatchCreatedEvent(org.kie.api.event.rule.MatchCreatedEvent) KieModule(org.kie.api.builder.KieModule) DynamicRulesTest(org.drools.mvel.integrationtests.DynamicRulesTest) Test(org.junit.Test)

Example 68 with AgendaEventListener

use of org.kie.api.event.rule.AgendaEventListener in project drools by kiegroup.

the class TimerAndCalendarWithPseudoTimeTest method testRaceConditionWithTimedRuleExectionOption.

@Test(timeout = 10000)
@Ignore("the listener callback holds some locks so blocking in it is not safe")
public void testRaceConditionWithTimedRuleExectionOption() throws Exception {
    // BZ-1073880
    final String drl = "package org.simple \n" + "global java.util.List list \n" + "rule xxx @Propagation(EAGER)\n" + "  timer (int:30s 10s) " + "when \n" + "  $s: String()\n" + "then \n" + "  list.add($s); \n" + "end  \n";
    final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("timer-and-calendar-test", kieBaseTestConfiguration, drl);
    final KieSessionConfiguration kieSessionConfiguration = KieSessionTestConfiguration.STATEFUL_PSEUDO.getKieSessionConfiguration();
    kieSessionConfiguration.setOption(TimedRuleExecutionOption.YES);
    final KieSession ksession = kbase.newKieSession(kieSessionConfiguration, null);
    try {
        final CyclicBarrier barrier = new CyclicBarrier(2);
        final AtomicBoolean aBool = new AtomicBoolean(true);
        final AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {

            @Override
            public void afterMatchFired(final org.kie.api.event.rule.AfterMatchFiredEvent event) {
                try {
                    if (aBool.get()) {
                        barrier.await();
                        aBool.set(false);
                    }
                } catch (final Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
        ksession.addEventListener(agendaEventListener);
        final List list = new ArrayList();
        ksession.setGlobal("list", list);
        // Using the Pseudo Clock.
        final SessionClock clock = ksession.getSessionClock();
        final SessionPseudoClock pseudoClock = (SessionPseudoClock) clock;
        // Insert the event.
        final String eventOne = "one";
        ksession.insert(eventOne);
        // Advance the time .... so the timer will fire.
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        // Rule doesn't fire in PHREAK. This is because you need to call 'fireAllRules' after you've inserted the fact, otherwise the timer
        // job is not created.
        ksession.fireAllRules();
        // Rule still doesn't fire, because the DefaultTimerJob is created now, and now we need to advance the timer again.
        pseudoClock.advanceTime(30000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);
        final String eventTwo = "two";
        ksession.insert(eventTwo);
        ksession.fireAllRules();
        // 60
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);
        // 70
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);
        // From here, the second rule should fire.
        // phaser.register();
        pseudoClock.advanceTime(10000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        aBool.set(true);
        // Now 2 rules have fired, and those will now fire every 10 seconds.
        pseudoClock.advanceTime(20000, TimeUnit.MILLISECONDS);
        barrier.await();
        barrier.reset();
        pseudoClock.advanceTime(20000, TimeUnit.MILLISECONDS);
        aBool.set(true);
        barrier.await();
        barrier.reset();
        pseudoClock.advanceTime(20000, TimeUnit.MILLISECONDS);
        aBool.set(true);
        barrier.await();
        barrier.reset();
    } finally {
        ksession.dispose();
    }
}
Also used : SessionPseudoClock(org.kie.api.time.SessionPseudoClock) ArrayList(java.util.ArrayList) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) SessionClock(org.kie.api.time.SessionClock) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) KieBase(org.kie.api.KieBase) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) List(java.util.List) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 69 with AgendaEventListener

use of org.kie.api.event.rule.AgendaEventListener in project drools by kiegroup.

the class StreamsTest method testWindowDeclaration.

@Test
public void testWindowDeclaration() {
    final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + "    @role(event)\n" + "end\n" + "declare window RedHatTicks\n" + "    StockTick( company == 'RHT' )\n" + "               over window:length(5)\n" + "               from entry-point ticks\n" + "end\n" + "rule X\n" + "when\n" + "    accumulate( $s : StockTick( price > 20 ) from window RedHatTicks,\n" + "                $sum : sum( $s.getPrice() ),\n" + "                $cnt : count( $s ) )\n" + "then\n" + "end\n";
    final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("stream-test", kieBaseTestConfiguration, drl);
    final KieSession ksession = kbase.newKieSession();
    try {
        final AgendaEventListener ael = mock(AgendaEventListener.class);
        ksession.addEventListener(ael);
        final EntryPoint ep = ksession.getEntryPoint("ticks");
        // not in the window
        ep.insert(new StockTick(1, "ACME", 20, 1000));
        // not > 20
        ep.insert(new StockTick(2, "RHT", 20, 1000));
        ep.insert(new StockTick(3, "RHT", 30, 1000));
        // not in the window
        ep.insert(new StockTick(4, "ACME", 30, 1000));
        ep.insert(new StockTick(5, "RHT", 25, 1000));
        // not in the window
        ep.insert(new StockTick(6, "ACME", 10, 1000));
        // not > 20
        ep.insert(new StockTick(7, "RHT", 10, 1000));
        ep.insert(new StockTick(8, "RHT", 40, 1000));
        ksession.fireAllRules();
        final ArgumentCaptor<org.kie.api.event.rule.AfterMatchFiredEvent> captor = ArgumentCaptor.forClass(org.kie.api.event.rule.AfterMatchFiredEvent.class);
        verify(ael, times(1)).afterMatchFired(captor.capture());
        final AfterMatchFiredEvent aafe = captor.getValue();
        assertThat(((Number) aafe.getMatch().getDeclarationValue("$sum")).intValue(), is(95));
        assertThat(((Number) aafe.getMatch().getDeclarationValue("$cnt")).intValue(), is(3));
    } finally {
        ksession.dispose();
    }
}
Also used : EntryPoint(org.kie.api.runtime.rule.EntryPoint) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) StockTick(org.drools.testcoverage.common.model.StockTick) KieBase(org.kie.api.KieBase) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) KieSession(org.kie.api.runtime.KieSession) Test(org.junit.Test)

Example 70 with AgendaEventListener

use of org.kie.api.event.rule.AgendaEventListener in project drools by kiegroup.

the class CepEspTest method testSalienceWithEventsRealtimeClock.

@Test(timeout = 10000)
public void testSalienceWithEventsRealtimeClock() throws InterruptedException {
    final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getName() + "\n" + "declare StockTick\n" + "        @role ( event )\n" + "end\n" + "rule R1 salience 1000\n" + "    when\n" + "        $s1 : StockTick( company == 'RHT' )\n" + "        $s2 : StockTick( company == 'ACME', this after[0s,1m] $s1 )\n" + "    then\n" + "end\n" + "rule R2 salience 1000\n" + "    when\n" + "        $s1 : StockTick( company == 'RHT' )\n" + "        not StockTick( company == 'ACME', this after[0s,1m] $s1 )\n" + "    then\n" + "end\n" + "rule R3 salience 100\n" + "    when\n" + "        $s2 : StockTick( company == 'ACME' )\n" + "    then\n" + "end\n";
    final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("cep-esp-test", kieBaseTestConfiguration, drl);
    final KieSession ksession = kbase.newKieSession();
    try {
        final AgendaEventListener ael = mock(AgendaEventListener.class);
        ksession.addEventListener(ael);
        ksession.insert(new StockTick(1, "RHT", 10, 1000));
        ksession.insert(new StockTick(2, "RHT", 10, 1000));
        ksession.insert(new StockTick(3, "RHT", 10, 1000));
        // sleep for 2 secs
        Thread.sleep(2000);
        ksession.insert(new StockTick(4, "ACME", 10, 1000));
        // sleep for 1 sec
        Thread.sleep(1000);
        final int rulesFired = ksession.fireAllRules();
        assertEquals(4, rulesFired);
        final ArgumentCaptor<AfterMatchFiredEvent> captor = ArgumentCaptor.forClass(AfterMatchFiredEvent.class);
        verify(ael, times(4)).afterMatchFired(captor.capture());
        final List<AfterMatchFiredEvent> aafe = captor.getAllValues();
        assertThat(aafe.get(0).getMatch().getRule().getName(), is("R1"));
        assertThat(aafe.get(1).getMatch().getRule().getName(), is("R1"));
        assertThat(aafe.get(2).getMatch().getRule().getName(), is("R1"));
        assertThat(aafe.get(3).getMatch().getRule().getName(), is("R3"));
    } finally {
        ksession.dispose();
    }
}
Also used : StockTick(org.drools.testcoverage.common.model.StockTick) KieBase(org.kie.api.KieBase) DebugAgendaEventListener(org.kie.api.event.rule.DebugAgendaEventListener) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) KieSession(org.kie.api.runtime.KieSession) EntryPoint(org.kie.api.runtime.rule.EntryPoint) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) Test(org.junit.Test)

Aggregations

AgendaEventListener (org.kie.api.event.rule.AgendaEventListener)78 Test (org.junit.Test)72 KieSession (org.kie.api.runtime.KieSession)59 AfterMatchFiredEvent (org.kie.api.event.rule.AfterMatchFiredEvent)49 KieBase (org.kie.api.KieBase)38 ArrayList (java.util.ArrayList)33 MatchCreatedEvent (org.kie.api.event.rule.MatchCreatedEvent)25 DefaultAgendaEventListener (org.kie.api.event.rule.DefaultAgendaEventListener)22 List (java.util.List)21 MatchCancelledEvent (org.kie.api.event.rule.MatchCancelledEvent)18 FactHandle (org.kie.api.runtime.rule.FactHandle)17 DebugAgendaEventListener (org.kie.api.event.rule.DebugAgendaEventListener)14 KieSessionConfiguration (org.kie.api.runtime.KieSessionConfiguration)12 EntryPoint (org.kie.api.runtime.rule.EntryPoint)11 StatelessKieSession (org.kie.api.runtime.StatelessKieSession)10 DefaultAgendaEventListener (org.drools.core.event.DefaultAgendaEventListener)9 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)7 StockTick (org.drools.testcoverage.common.model.StockTick)7 BeforeMatchFiredEvent (org.kie.api.event.rule.BeforeMatchFiredEvent)7 Arrays.asList (java.util.Arrays.asList)6