Search in sources :

Example 51 with AgendaEventListener

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

the class StrictAnnotationTest method testEagerEvaluation.

@Test
public void testEagerEvaluation() throws Exception {
    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);
    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());
}
Also used : ArrayList(java.util.ArrayList) KieHelper(org.kie.internal.utils.KieHelper) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) KieServices(org.kie.api.KieServices) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 52 with AgendaEventListener

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

the class ActivationIteratorTest method testEagerEvaluation.

@Test(timeout = 10000)
public void testEagerEvaluation() 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(ForceEagerActivationOption.YES);
    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");
    assertEquals(2, list.size());
}
Also used : KieBase(org.kie.api.KieBase) ArrayList(java.util.ArrayList) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 53 with AgendaEventListener

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

the class AgendaEventSupportTest method testAgendaEventListener.

// public void testIsSerializable() {
// assertTrue( Serializable.class.isAssignableFrom( AgendaEventSupport.class ) );
// }
@Test
@Ignore
public void testAgendaEventListener() throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    // create a simple package with one rule to test the events
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools.test");
    final RuleImpl rule = new RuleImpl("test1");
    rule.setEager(true);
    rule.setAgendaGroup("test group");
    final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjectType);
    pkg.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg.getClassFieldAccessorStore().setEagerWire(true);
    final ClassFieldReader extractor = pkg.getClassFieldAccessorStore().getReader(Cheese.class, "type");
    final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");
    final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);
    pattern.addConstraint(constraint);
    rule.addPattern(pattern);
    rule.setConsequence(new Consequence() {

        public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        }

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            // TODO Auto-generated method stub
            return null;
        }
    });
    pkg.addRule(rule);
    kbase.addPackages(Collections.singleton(pkg));
    // create a new working memory and add an AgendaEventListener
    KieSession ksession = kbase.newKieSession();
    final List agendaList = new ArrayList();
    final AgendaEventListener agendaEventListener = new AgendaEventListener() {

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

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

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

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

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

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

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

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

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

        public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }
    };
    ksession.addEventListener(agendaEventListener);
    assertEquals(1, ksession.getAgendaEventListeners().size());
    // assert the cheese fact
    final Cheese cheddar = new Cheese("cheddar", 15);
    FactHandle cheddarHandle = ksession.insert(cheddar);
    InternalAgenda agenda = (InternalAgenda) ksession.getAgenda();
    agenda.evaluateEagerList();
    // should be one MatchCreatedEvent
    assertEquals(1, agendaList.size());
    MatchCreatedEvent createdEvent = (MatchCreatedEvent) agendaList.get(0);
    assertSame(cheddarHandle, createdEvent.getMatch().getFactHandles().toArray()[0]);
    // clear the agenda to check CLEAR events occur
    ksession.getAgenda().clear();
    MatchCancelledEvent cancelledEvent = (MatchCancelledEvent) agendaList.get(1);
    assertEquals(MatchCancelledCause.CLEAR, cancelledEvent.getCause());
    agendaList.clear();
    // update results in an MatchCreatedEvent
    cheddar.setPrice(14);
    ksession.update(cheddarHandle, cheddar);
    agenda.evaluateEagerList();
    assertEquals(1, agendaList.size());
    createdEvent = (MatchCreatedEvent) agendaList.get(0);
    assertSame(cheddarHandle, createdEvent.getMatch().getFactHandles().toArray()[0]);
    agendaList.clear();
    // update should not result in cancelation+activation events
    cheddar.setPrice(14);
    ksession.update(cheddarHandle, cheddar);
    assertEquals(0, agendaList.size());
    // cancelledEvent = (ActivationCancelledEvent) agendaList.get( 0 );
    // assertEquals( ActivationCancelledCause.WME_MODIFY, cancelledEvent.getCause() );
    // assertSame( cheddarHandle,
    // cancelledEvent.getActivation().toFactHandles().toArray()[0] );
    // createdEvent = (ActivationCreatedEvent) agendaList.get( 1 );
    // assertSame( cheddarHandle,
    // createdEvent.getActivation().toFactHandles().toArray()[0] );
    // agendaList.clear();
    // retract results in a ActivationCancelledEvent, note the object is not resolveable now as it no longer exists
    ksession.retract(cheddarHandle);
    assertEquals(1, agendaList.size());
    cancelledEvent = (MatchCancelledEvent) agendaList.get(0);
    // invalidated handles no longer set the object to null
    assertNotNull(((InternalFactHandle) cancelledEvent.getMatch().getFactHandles().toArray()[0]).getObject());
    // re-assert the fact so we can test the agenda group events
    cheddarHandle = ksession.insert(cheddar);
    agendaList.clear();
    // setFocus results in an AgendaGroupPushedEvent
    ksession.getAgenda().getAgendaGroup("test group").setFocus();
    assertEquals(1, agendaList.size());
    final AgendaGroupPushedEvent pushedEvent = (AgendaGroupPushedEvent) agendaList.get(0);
    assertEquals("test group", pushedEvent.getAgendaGroup().getName());
    agendaList.clear();
    // fireAllRules results in a BeforeActivationFiredEvent and an AfterActivationFiredEvent
    // the AgendaGroup becomes empty, which results in a popped event.
    ksession.fireAllRules();
    assertEquals(3, agendaList.size());
    final BeforeMatchFiredEvent beforeEvent = (BeforeMatchFiredEvent) agendaList.get(0);
    assertSame(cheddarHandle, beforeEvent.getMatch().getFactHandles().toArray()[0]);
    final AfterMatchFiredEvent afterEvent = (AfterMatchFiredEvent) agendaList.get(1);
    assertSame(cheddarHandle, afterEvent.getMatch().getFactHandles().toArray()[0]);
    final AgendaGroupPoppedEvent poppedEvent = (AgendaGroupPoppedEvent) agendaList.get(2);
    assertEquals("test group", poppedEvent.getAgendaGroup().getName());
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) WorkingMemory(org.drools.core.WorkingMemory) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) ArrayList(java.util.ArrayList) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) Cheese(org.drools.core.test.model.Cheese) RuleFlowGroupDeactivatedEvent(org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent) MvelConstraintTestUtil(org.drools.core.rule.MvelConstraintTestUtil) InternalAgenda(org.drools.core.common.InternalAgenda) ClassFieldReader(org.drools.core.base.ClassFieldReader) MatchCancelledEvent(org.kie.api.event.rule.MatchCancelledEvent) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) BeforeMatchFiredEvent(org.kie.api.event.rule.BeforeMatchFiredEvent) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) FieldValue(org.drools.core.spi.FieldValue) MatchCreatedEvent(org.kie.api.event.rule.MatchCreatedEvent) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Pattern(org.drools.core.rule.Pattern) ObjectOutput(java.io.ObjectOutput) Consequence(org.drools.core.spi.Consequence) IOException(java.io.IOException) IOException(java.io.IOException) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) ClassFieldAccessorCache(org.drools.core.base.ClassFieldAccessorCache) AgendaGroupPoppedEvent(org.kie.api.event.rule.AgendaGroupPoppedEvent) RuleFlowGroupActivatedEvent(org.kie.api.event.rule.RuleFlowGroupActivatedEvent) AgendaGroupPushedEvent(org.kie.api.event.rule.AgendaGroupPushedEvent) ObjectInput(java.io.ObjectInput) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 54 with AgendaEventListener

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

the class DescrBuilderTest method testTopLevelAccumulate.

@Test
public void testTopLevelAccumulate() throws InstantiationException, IllegalAccessException {
    PackageDescr pkg = DescrFactory.newPackage().name("org.drools.compiler").newRule().name("r1").lhs().accumulate().source().pattern("StockTick").constraint("company == \"RHT\"").bind("$p", "price", false).end().end().function("sum", "$sum", false, "$p").function("count", "$cnt", false, "$p").end().end().rhs("// some comment").end().getDescr();
    KiePackage kpkg = compilePkgDescr(pkg);
    assertEquals("org.drools.compiler", kpkg.getName());
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(Collections.singletonList(kpkg));
    KieSession ksession = kbase.newKieSession();
    AgendaEventListener ael = mock(AgendaEventListener.class);
    ksession.addEventListener(ael);
    ksession.insert(new StockTick(1, "RHT", 80, 1));
    ksession.insert(new StockTick(2, "RHT", 100, 10));
    int rules = ksession.fireAllRules();
    assertEquals(1, rules);
    ArgumentCaptor<AfterMatchFiredEvent> cap = ArgumentCaptor.forClass(AfterMatchFiredEvent.class);
    verify(ael).afterMatchFired(cap.capture());
    assertThat(((Number) cap.getValue().getMatch().getDeclarationValue("$sum")).intValue(), is(180));
    assertThat(((Number) cap.getValue().getMatch().getDeclarationValue("$cnt")).intValue(), is(2));
}
Also used : StockTick(org.drools.compiler.StockTick) KiePackage(org.kie.api.definition.KiePackage) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) KieSession(org.kie.api.runtime.KieSession) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) EntryPoint(org.kie.api.runtime.rule.EntryPoint) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) Test(org.junit.Test)

Example 55 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.compiler.test\n";
    str += "import org.drools.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";
    KieBase kbase = loadKnowledgeBaseFromString(kconf, str);
    StatelessKieSession ksession = createStatelessKnowledgeSession(kbase);
    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.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) DynamicRulesTest(org.drools.compiler.integrationtests.DynamicRulesTest) 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