Search in sources :

Example 16 with AgendaEventListener

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

the class ActivateAndDeleteOnListenerTest method testOneLazyAndOneImmediateSubPath.

@Test
public void testOneLazyAndOneImmediateSubPath() throws Exception {
    String str = "package org.simple \n" + "rule xxx \n" + "when \n" + "  $s : String()\n" + "  exists( Integer() or Long() )\n" + "then \n" + "end  \n" + "rule yyy \n" + "when \n" + "  $s : String()\n" + "  exists( Integer() or Long() )\n" + "then \n" + "end  \n";
    KieServices ks = KieServices.Factory.get();
    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(new ForceEagerActivationOption.FILTERED(new ForceEagerActivationFilter() {

        @Override
        public boolean accept(Rule rule) {
            return rule.getName().equals("yyy");
        }
    }));
    KieSession ksession = new KieHelper().addContent(str, ResourceType.DRL).build().newKieSession(conf, null);
    final List list = new ArrayList();
    AgendaEventListener agendaEventListener = new org.kie.api.event.rule.DefaultAgendaEventListener() {

        public void matchCreated(org.kie.api.event.rule.MatchCreatedEvent event) {
            list.add(event.getMatch().getRule().getName());
        }
    };
    ksession.addEventListener(agendaEventListener);
    ksession.insert("test");
    assertEquals(0, list.size());
    ksession.insert(1);
    assertEquals(1, list.size());
    assertEquals("yyy", list.get(0));
}
Also used : ForceEagerActivationOption(org.kie.internal.runtime.conf.ForceEagerActivationOption) ArrayList(java.util.ArrayList) KieHelper(org.kie.internal.utils.KieHelper) DefaultAgendaEventListener(org.drools.core.event.DefaultAgendaEventListener) KieServices(org.kie.api.KieServices) ForceEagerActivationFilter(org.kie.internal.runtime.conf.ForceEagerActivationFilter) DefaultAgendaEventListener(org.drools.core.event.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) Rule(org.kie.api.definition.rule.Rule) MatchCreatedEvent(org.kie.api.event.rule.MatchCreatedEvent) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) Test(org.junit.Test)

Example 17 with AgendaEventListener

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

the class StarImportTest method starImportedFactAlsoDeclaredInDRL.

/**
 * Tests that rule fires if supplied with a fact that is imported using
 * "star" import.
 *
 * See BZ 973264.
 */
@Test
public void starImportedFactAlsoDeclaredInDRL() throws Exception {
    session.setGlobal("LOGGER", LOGGER);
    AgendaEventListener ael = mock(AgendaEventListener.class);
    session.addEventListener(ael);
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(getCommands().newInsert(new TestEvent(1, "event 1", 0)));
    commands.add(getCommands().newFireAllRules());
    session.execute(getCommands().newBatchExecution(commands, null));
    // the rule should have fired exactly once
    try {
        verify(ael, times(1)).afterMatchFired(any(AfterMatchFiredEvent.class));
    } catch (WantedButNotInvoked e) {
        Assertions.fail("The rule does not fire. For more information see BZ 973264", e);
    }
}
Also used : Command(org.kie.api.command.Command) TestEvent(org.drools.testcoverage.common.model.TestEvent) ArrayList(java.util.ArrayList) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) WantedButNotInvoked(org.mockito.exceptions.verification.WantedButNotInvoked) KieSessionTest(org.drools.testcoverage.common.KieSessionTest) Test(org.junit.Test)

Example 18 with AgendaEventListener

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

the class ActivationTest method noDormantCheckOnModifies.

/**
 * Tests improper deactivation of already activated rule on the agenda. See
 * BZ 862325.
 */
@Test
public void noDormantCheckOnModifies() throws Exception {
    AgendaEventListener ael = mock(AgendaEventListener.class);
    session.addEventListener(ael);
    session.setGlobal("LOGGER", LOGGER);
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(getCommands().newInsert(new Person("Bob", 19)));
    commands.add(getCommands().newInsert(new Cheese("brie", 10)));
    commands.add(getCommands().newFireAllRules());
    session.execute(getCommands().newBatchExecution(commands, null));
    // both rules should fire exactly once
    verify(ael, times(2)).afterMatchFired(any(AfterMatchFiredEvent.class));
    // no cancellations should have happened
    verify(ael, never()).matchCancelled(any(MatchCancelledEvent.class));
}
Also used : Command(org.kie.api.command.Command) ArrayList(java.util.ArrayList) MatchCancelledEvent(org.kie.api.event.rule.MatchCancelledEvent) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) Cheese(org.drools.testcoverage.common.model.Cheese) Person(org.drools.testcoverage.common.model.Person) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) KieSessionTest(org.drools.testcoverage.common.KieSessionTest) Test(org.junit.Test)

Example 19 with AgendaEventListener

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

the class GlobalTimerServiceBaseTest method testTimerRule.

@Test
@Ignore
public void testTimerRule() throws Exception {
    int badNumTimers = 6;
    final CountDownLatch timerCompleted = new CountDownLatch(badNumTimers);
    // prepare listener to assert results
    final List<String> timerExporations = new ArrayList<String>();
    AgendaEventListener listener = new DefaultAgendaEventListener() {

        @Override
        public void beforeMatchFired(BeforeMatchFiredEvent event) {
            timerExporations.add(event.getMatch().getRule().getId());
            timerCompleted.countDown();
        }
    };
    environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).addAsset(ResourceFactory.newClassPathResource("org/jbpm/test/functional/timer/timer-rules.drl"), ResourceType.DRL).schedulerService(globalScheduler).registerableItemsFactory(new TestRegisterableItemsFactory(listener)).get();
    manager = getManager(environment, true);
    RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get());
    assertEquals(0, timerExporations.size());
    boolean didNotWait = timerCompleted.await(6, TimeUnit.SECONDS);
    assertTrue("Too many timers elapsed: " + (badNumTimers - timerCompleted.getCount()), !didNotWait);
    manager.disposeRuntimeEngine(runtime);
    assertEquals(5, timerExporations.size());
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) ArrayList(java.util.ArrayList) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) DefaultAgendaEventListener(org.kie.api.event.rule.DefaultAgendaEventListener) BeforeMatchFiredEvent(org.kie.api.event.rule.BeforeMatchFiredEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 20 with AgendaEventListener

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

the class JbpmJUnitBaseTestCase method createRuntimeManager.

/**
 * Creates default configuration of <code>RuntimeManager</code> with given <code>strategy</code> and all
 * <code>resources</code> being added to knowledge base.
 * <br/>
 * There should be only one <code>RuntimeManager</code> created during single test.
 * @param strategy - selected strategy of those that are supported
 * @param resources - resources that shall be added to knowledge base
 * @param identifier - identifies the runtime manager
 * @return new instance of RuntimeManager
 */
protected RuntimeManager createRuntimeManager(Strategy strategy, Map<String, ResourceType> resources, String identifier) {
    if (manager != null) {
        throw new IllegalStateException("There is already one RuntimeManager active");
    }
    RuntimeEnvironmentBuilder builder = null;
    if (!setupDataSource) {
        builder = RuntimeEnvironmentBuilder.Factory.get().newEmptyBuilder().addConfiguration("drools.processSignalManagerFactory", DefaultSignalManagerFactory.class.getName()).addConfiguration("drools.processInstanceManagerFactory", DefaultProcessInstanceManagerFactory.class.getName()).registerableItemsFactory(new SimpleRegisterableItemsFactory() {

            @Override
            public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) {
                Map<String, WorkItemHandler> handlers = new HashMap<String, WorkItemHandler>();
                handlers.putAll(super.getWorkItemHandlers(runtime));
                handlers.putAll(customHandlers);
                return handlers;
            }

            @Override
            public List<ProcessEventListener> getProcessEventListeners(RuntimeEngine runtime) {
                List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime);
                listeners.addAll(customProcessListeners);
                return listeners;
            }

            @Override
            public List<AgendaEventListener> getAgendaEventListeners(RuntimeEngine runtime) {
                List<AgendaEventListener> listeners = super.getAgendaEventListeners(runtime);
                listeners.addAll(customAgendaListeners);
                return listeners;
            }

            @Override
            public List<TaskLifeCycleEventListener> getTaskListeners() {
                List<TaskLifeCycleEventListener> listeners = super.getTaskListeners();
                listeners.addAll(customTaskListeners);
                return listeners;
            }
        });
    } else if (sessionPersistence) {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).registerableItemsFactory(new DefaultRegisterableItemsFactory() {

            @Override
            public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) {
                Map<String, WorkItemHandler> handlers = new HashMap<String, WorkItemHandler>();
                handlers.putAll(super.getWorkItemHandlers(runtime));
                handlers.putAll(customHandlers);
                return handlers;
            }

            @Override
            public List<ProcessEventListener> getProcessEventListeners(RuntimeEngine runtime) {
                List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime);
                listeners.addAll(customProcessListeners);
                return listeners;
            }

            @Override
            public List<AgendaEventListener> getAgendaEventListeners(RuntimeEngine runtime) {
                List<AgendaEventListener> listeners = super.getAgendaEventListeners(runtime);
                listeners.addAll(customAgendaListeners);
                return listeners;
            }

            @Override
            public List<TaskLifeCycleEventListener> getTaskListeners() {
                List<TaskLifeCycleEventListener> listeners = super.getTaskListeners();
                listeners.addAll(customTaskListeners);
                return listeners;
            }
        });
    } else {
        builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder().entityManagerFactory(emf).registerableItemsFactory(new DefaultRegisterableItemsFactory() {

            @Override
            public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) {
                Map<String, WorkItemHandler> handlers = new HashMap<String, WorkItemHandler>();
                handlers.putAll(super.getWorkItemHandlers(runtime));
                handlers.putAll(customHandlers);
                return handlers;
            }

            @Override
            public List<ProcessEventListener> getProcessEventListeners(RuntimeEngine runtime) {
                List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime);
                listeners.addAll(customProcessListeners);
                return listeners;
            }

            @Override
            public List<AgendaEventListener> getAgendaEventListeners(RuntimeEngine runtime) {
                List<AgendaEventListener> listeners = super.getAgendaEventListeners(runtime);
                listeners.addAll(customAgendaListeners);
                return listeners;
            }

            @Override
            public List<TaskLifeCycleEventListener> getTaskListeners() {
                List<TaskLifeCycleEventListener> listeners = super.getTaskListeners();
                listeners.addAll(customTaskListeners);
                return listeners;
            }
        });
    }
    builder.userGroupCallback(userGroupCallback);
    for (Entry<String, Object> envEntry : customEnvironmentEntries.entrySet()) {
        builder.addEnvironmentEntry(envEntry.getKey(), envEntry.getValue());
    }
    for (Map.Entry<String, ResourceType> entry : resources.entrySet()) {
        builder.addAsset(ResourceFactory.newClassPathResource(entry.getKey()), entry.getValue());
    }
    return createRuntimeManager(strategy, resources, builder.get(), identifier);
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) DefaultRegisterableItemsFactory(org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory) HashMap(java.util.HashMap) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) ResourceType(org.kie.api.io.ResourceType) DefaultProcessInstanceManagerFactory(org.jbpm.process.instance.impl.DefaultProcessInstanceManagerFactory) RuntimeEnvironmentBuilder(org.kie.api.runtime.manager.RuntimeEnvironmentBuilder) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) SimpleRegisterableItemsFactory(org.jbpm.runtime.manager.impl.SimpleRegisterableItemsFactory) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) TaskLifeCycleEventListener(org.kie.api.task.TaskLifeCycleEventListener)

Aggregations

AgendaEventListener (org.kie.api.event.rule.AgendaEventListener)50 Test (org.junit.Test)45 KieSession (org.kie.api.runtime.KieSession)37 AfterMatchFiredEvent (org.kie.api.event.rule.AfterMatchFiredEvent)32 ArrayList (java.util.ArrayList)21 KieBase (org.kie.api.KieBase)20 List (java.util.List)15 DefaultAgendaEventListener (org.kie.api.event.rule.DefaultAgendaEventListener)15 MatchCreatedEvent (org.kie.api.event.rule.MatchCreatedEvent)15 KieBaseConfiguration (org.kie.api.KieBaseConfiguration)13 KieSessionConfiguration (org.kie.api.runtime.KieSessionConfiguration)13 DebugAgendaEventListener (org.kie.api.event.rule.DebugAgendaEventListener)11 MatchCancelledEvent (org.kie.api.event.rule.MatchCancelledEvent)10 StockTick (org.drools.compiler.StockTick)9 KieServices (org.kie.api.KieServices)9 FactHandle (org.kie.api.runtime.rule.FactHandle)9 EntryPoint (org.kie.api.runtime.rule.EntryPoint)8 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)7 Person (org.drools.compiler.Person)6 KieHelper (org.kie.internal.utils.KieHelper)6