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

The following examples show how to use org.kie.api.runtime.KieSession#addEventListener() . 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: AgendaFilterTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void testAgendaFilter(final AgendaFilter agendaFilter, final String expectedMatchingRuleName) {
    final String str = "package org.drools.compiler\n" +
            "rule Aaa when then end\n" +
            "rule Bbb when then end\n";

    final KieBase kbase = loadKnowledgeBaseFromString(str);
    final KieSession ksession = createKnowledgeSession(kbase);

    final org.kie.api.event.rule.AgendaEventListener ael = mock(org.kie.api.event.rule.AgendaEventListener.class);
    ksession.addEventListener(ael);

    final int rules = ksession.fireAllRules(agendaFilter);
    assertEquals(1, rules);

    final ArgumentCaptor<org.kie.api.event.rule.AfterMatchFiredEvent> arg = ArgumentCaptor.forClass(org.kie.api.event.rule.AfterMatchFiredEvent.class);
    verify(ael).afterMatchFired(arg.capture());
    assertThat(arg.getValue().getMatch().getRule().getName()).isEqualTo(expectedMatchingRuleName);
}
 
Example 2
Source File: VariableTagsTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessWithCustomVariableTag() throws Exception {
    KieBase kbase = createKnowledgeBase("variable-tags/approval-with-custom-variable-tags.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
    ksession.addEventListener(new DefaultProcessEventListener() {

        @Override
        public void beforeVariableChanged(ProcessVariableChangedEvent event) {
            if (event.hasTag("onlyAdmin")) {
                throw new VariableViolationException(event.getProcessInstance().getId(), event.getVariableId(), "Variable can only be set by admins");
            }
        }
        
    });
    
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("approver", "john");
    
    assertThrows(VariableViolationException.class, () -> ksession.startProcess("approvals", parameters));
    
    ksession.dispose();
}
 
Example 3
Source File: CompensationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void compensationOnlyAfterAssociatedActivityHasCompleted() throws Exception {
    KieSession ksession = createKnowledgeSession("compensation/BPMN2-Compensation-UserTaskBeforeAssociatedActivity.bpmn2");
    ksession.addEventListener(LOGGING_EVENT_LISTENER);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
    
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("x", "0");
    ProcessInstance processInstance = ksession.startProcess("CompensateIntermediateThrowEvent", params);
    
    // should NOT cause compensation since compensated activity has not yet completed (or started)! 
    ksession.signalEvent("Compensation", "_3", processInstance.getId());
    
    // user task -> script task (associated with compensation) --> intermeidate throw compensation event
    ksession.getWorkItemManager().completeWorkItem(workItemHandler.getWorkItem().getId(), null);
    
    // compensation activity (assoc. with script task) signaled *after* to-compensate script task
    assertProcessInstanceCompleted(processInstance.getId(), ksession);
    assertProcessVarValue(processInstance, "x", "1");
}
 
Example 4
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
@Timeout(1000)
public void testTimerStart() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("StartProcess", 5);
    KieBase kbase = createKnowledgeBase("BPMN2-TimerStart.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    ksession.addEventListener(countDownListener);
    final List<String> list = new ArrayList<>();
    ksession.addEventListener(new DefaultProcessEventListener() { 
        
        public void beforeProcessStarted(ProcessStartedEvent event) {
            list.add(event.getProcessInstance().getId());
        }
        
    });

    assertThat(list.size()).isEqualTo(0);
    countDownListener.waitTillCompleted();
    assertThat(list.size()).isEqualTo(5);
}
 
Example 5
Source File: RulesEngineImpl.java    From cia with Apache License 2.0 5 votes vote down vote up
@Override
public List<ComplianceCheck> checkRulesCompliance() {
	final KieSession ksession = rulesContainer.newKieSession();
	final Map<String, ComplianceCheck> complianceChecks = new HashMap<>();
	ksession.addEventListener(new ComplianceCheckAgendaEventListener(complianceChecks));

	insertPoliticians(ksession, dataViewer.getAll(ViewRiksdagenPolitician.class));
	insertParties(ksession, dataViewer.getAll(ViewRiksdagenPartySummary.class));

	ksession.fireAllRules();
	ksession.dispose();

	return new ArrayList<>(complianceChecks.values());
}
 
Example 6
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignalStart() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-SignalStart.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    final List<String> list = new ArrayList<>();
    ksession.addEventListener(new DefaultProcessEventListener() {
        public void afterProcessStarted(ProcessStartedEvent event) {
            list.add(event.getProcessInstance().getId());
        }
    });
    ksession.signalEvent("MySignal", "NewValue");
    assertThat(list.size()).isEqualTo(1);
}
 
Example 7
Source File: HelloWorldExample.java    From drools-examples with Apache License 2.0 5 votes vote down vote up
public static void execute( KieContainer kc ) {
    // From the container, a session is created based on
    // its definition and configuration in the META-INF/kmodule.xml file
    KieSession ksession = kc.newKieSession("HelloWorldKS");

    // Once the session is created, the application can interact with it
    // In this case it is setting a global as defined in the
    // org/drools/examples/helloworld/HelloWorld.drl file
    ksession.setGlobal( "list",
                        new ArrayList<Object>() );

    // The application can also setup listeners
    ksession.addEventListener( new DebugAgendaEventListener() );
    ksession.addEventListener( new DebugRuleRuntimeEventListener() );

    // To setup a file based audit logger, uncomment the next line
    // KieRuntimeLogger logger = ks.getLoggers().newFileLogger( ksession, "./helloworld" );

    // To setup a ThreadedFileLogger, so that the audit view reflects events whilst debugging,
    // uncomment the next line
    // KieRuntimeLogger logger = ks.getLoggers().newThreadedFileLogger( ksession, "./helloworld", 1000 );

    // The application can insert facts into the session
    final Message message = new Message();
    message.setMessage( "Hello World" );
    message.setStatus( Message.HELLO );
    ksession.insert( message );

    // and fire the rules
    ksession.fireAllRules();

    // Remove comment if using logging
    // logger.close();

    // and then dispose the session
    ksession.dispose();
}
 
Example 8
Source File: HelloWorldExample.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public static void execute(KieContainer kc) {
    // From the container, a session is created based on
    // its definition and configuration in the META-INF/kmodule.xml file
    KieSession ksession = kc.newKieSession("HelloWorldKS");

    // Once the session is created, the application can interact with it
    // In this case it is setting a global as defined in the
    // org/drools/examples/helloworld/HelloWorld.drl file
    ksession.setGlobal("list",
            new ArrayList<>());

    // The application can also setup listeners
    ksession.addEventListener(new DebugAgendaEventListener());
    ksession.addEventListener(new DebugRuleRuntimeEventListener());

    // To setup a file based audit logger, uncomment the next line
    // KieRuntimeLogger logger = ks.getLoggers().newFileLogger( ksession, "./helloworld" );

    // To setup a ThreadedFileLogger, so that the audit view reflects events whilst debugging,
    // uncomment the next line
    // KieRuntimeLogger logger = ks.getLoggers().newThreadedFileLogger( ksession, "./helloworld", 1000 );

    // The application can insert facts into the session
    final Message message = new Message();
    message.setMessage("Hello World");
    message.setStatus(Message.HELLO);
    ksession.insert(message);

    // and fire the rules
    ksession.fireAllRules();

    // Remove comment if using logging
    // logger.close();

    // and then dispose the session
    ksession.dispose();
}
 
Example 9
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageStart() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-MessageStart.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    final List<String> list = new ArrayList<>();
    ksession.addEventListener(new DefaultProcessEventListener() {
        public void afterProcessStarted(ProcessStartedEvent event) {
            list.add(event.getProcessInstance().getId());
        }
    });
    ksession.signalEvent("Message-HelloMessage", "NewValue");
    assertThat(list.size()).isEqualTo(1);
}
 
Example 10
Source File: SLAComplianceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSLAonCatchEventNotViolated() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final ProcessEventListener listener = new DefaultProcessEventListener(){

        @Override
        public void afterSLAViolated(SLAViolatedEvent event) {
            latch.countDown();
        }
        
    };
    KieBase kbase = createKnowledgeBase("BPMN2-IntermediateCatchEventSignalWithSLAOnEvent.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    ksession.addEventListener(listener);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler());
    
    ProcessInstance processInstance = ksession.startProcess("IntermediateCatchEvent");
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    Collection<NodeInstance> active = ((WorkflowProcessInstance)processInstance).getNodeInstances();
    assertEquals(1, active.size());
    
    NodeInstance eventNode = active.iterator().next();
    
    ksession.signalEvent("MyMessage", null, processInstance.getId());
    
    assertProcessInstanceFinished(processInstance, ksession);        
    
    int slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_NA, slaCompliance);

    slaCompliance = getSLAComplianceForNodeInstance(processInstance.getId(), (org.jbpm.workflow.instance.NodeInstance) eventNode, 1);
    assertEquals(ProcessInstance.SLA_MET, slaCompliance);
    

    boolean slaViolated = latch.await(3, TimeUnit.SECONDS);
    assertFalse(slaViolated, "SLA should not violated by timer");

    ksession.dispose();
}
 
Example 11
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(10)
public void testTimerBoundaryEvent() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("TimerEvent", 1);
    KieBase kbase = createKnowledgeBase("BPMN2-TimerBoundaryEventDuration.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    ksession.addEventListener(countDownListener);
    ksession.getWorkItemManager().registerWorkItemHandler("MyTask", new DoNothingWorkItemHandler());
    ProcessInstance processInstance = ksession.startProcess("TimerBoundaryEvent");
    assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_ACTIVE);
    countDownListener.waitTillCompleted();
    assertProcessInstanceCompleted(processInstance.getId(), ksession);
}
 
Example 12
Source File: MapConstraintTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMapNullConstraint() throws Exception {
    final KieBase kbase = loadKnowledgeBase("test_mapNullConstraints.drl");
    final KieSession ksession = createKnowledgeSession(kbase);

    final org.kie.api.event.rule.AgendaEventListener ael = mock(org.kie.api.event.rule.AgendaEventListener.class);
    ksession.addEventListener(ael);
    new WorkingMemoryConsoleLogger((WorkingMemory) ksession);

    final Map addresses = new HashMap();
    addresses.put("home", new Address("home street"));
    final Person bob = new Person("Bob");
    bob.setNamedAddresses(addresses);

    ksession.insert(bob);
    ksession.fireAllRules();

    final ArgumentCaptor<AfterMatchFiredEvent> arg = ArgumentCaptor.forClass(org.kie.api.event.rule.AfterMatchFiredEvent.class);
    verify(ael, times(4)).afterMatchFired(arg.capture());
    org.kie.api.event.rule.AfterMatchFiredEvent aaf = arg.getAllValues().get(0);
    assertThat(aaf.getMatch().getRule().getName()).isEqualTo("1. home != null");
    aaf = arg.getAllValues().get(1);
    assertThat(aaf.getMatch().getRule().getName()).isEqualTo("2. not home == null");

    aaf = arg.getAllValues().get(2);
    assertThat(aaf.getMatch().getRule().getName()).isEqualTo("7. work == null");
    aaf = arg.getAllValues().get(3);
    assertThat(aaf.getMatch().getRule().getName()).isEqualTo("8. not work != null");
}
 
Example 13
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 14
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testDynamicRulesWithTypeDeclarations() {
    String type = "package com.sample\n" +
                  "declare type Foo\n" +
                  "  id : int\n" +
                  "end\n";

    String r1 = "package com.sample\n" +
                "rule R1 when\n" +
                "  not Foo()\n" +
                "then\n" +
                "  insert( new Foo(1) );\n" +
                "end\n";

    String r2 = "package com.sample\n" +
            "rule R2 when\n" +
            "  $f : Foo()\n" +
            "then\n" +
            "  $f.setId( 2 );\n" +
            "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( type.getBytes() ), ResourceType.DRL );
    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

    InternalKnowledgeBase kbase = (InternalKnowledgeBase) getKnowledgeBase( );
    kbase.addPackages( kbuilder.getKnowledgePackages() );

    KieSession ksession = kbase.newKieSession();

    AgendaEventListener ael = mock( AgendaEventListener.class );
    ksession.addEventListener( ael );
    
    ksession.fireAllRules();
    verify( ael, never() ).afterMatchFired( any( AfterMatchFiredEvent.class ) );
    
    kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( kbase );
    kbuilder.add( ResourceFactory.newByteArrayResource( r1.getBytes() ), ResourceType.DRL );
    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());
    
    ksession.fireAllRules();
    ArgumentCaptor<AfterMatchFiredEvent> capt = ArgumentCaptor.forClass( AfterMatchFiredEvent.class );
    verify( ael, times(1) ).afterMatchFired( capt.capture() );
    assertThat( "R1").isEqualTo(capt.getValue().getMatch().getRule().getName());
    
    kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( kbase );
    kbuilder.add( ResourceFactory.newByteArrayResource( r2.getBytes() ), ResourceType.DRL );
    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());
    
    ksession.fireAllRules();
    verify( ael, times(2) ).afterMatchFired( capt.capture() );
    assertThat( "R2").isEqualTo(capt.getAllValues().get( 2 ).getMatch().getRule().getName());
    
    ksession.dispose();
    
}
 
Example 15
Source File: SLAComplianceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSLAonProcessViolatedWithExpression() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final ProcessEventListener listener = new DefaultProcessEventListener(){

        @Override
        public void afterSLAViolated(SLAViolatedEvent event) {
            latch.countDown();
        }
        
    };
    KieBase kbase = createKnowledgeBase("BPMN2-UserTaskWithSLAExpr.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
    ksession.addEventListener(listener);
    
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("s", "3s");
    
    ProcessInstance processInstance = ksession.startProcess("UserTask", parameters);
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    WorkItem workItem = workItemHandler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("john", workItem.getParameter("ActorId"));
    
    boolean slaViolated = latch.await(10, TimeUnit.SECONDS);
    assertTrue(slaViolated, "SLA was not violated while it is expected");

    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    int slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);
    
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    assertProcessInstanceFinished(processInstance, ksession);        
    
    slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);
    
    ksession.dispose();
}
 
Example 16
Source File: SLAComplianceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSLAonCatchEventViolated() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final ProcessEventListener listener = new DefaultProcessEventListener(){

        @Override
        public void afterSLAViolated(SLAViolatedEvent event) {
            latch.countDown();
        }
        
    };
    KieBase kbase = createKnowledgeBase("BPMN2-IntermediateCatchEventSignalWithSLAOnEvent.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    ksession.addEventListener(listener);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler());
    
    ProcessInstance processInstance = ksession.startProcess("IntermediateCatchEvent");
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    boolean slaViolated = latch.await(5, TimeUnit.SECONDS);
    assertTrue(slaViolated, "SLA should be violated by timer");

    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    Collection<NodeInstance> active = ((WorkflowProcessInstance)processInstance).getNodeInstances();
    assertEquals(1, active.size());
    
    NodeInstance eventNode = active.iterator().next();
    
    ksession.signalEvent("MyMessage", null, processInstance.getId());
    
    assertProcessInstanceFinished(processInstance, ksession);        
    
    int slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_NA, slaCompliance);

    slaCompliance = getSLAComplianceForNodeInstance(processInstance.getId(), (org.jbpm.workflow.instance.NodeInstance) eventNode, 0);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);

    slaCompliance = getSLAComplianceForNodeInstance(processInstance.getId(), (org.jbpm.workflow.instance.NodeInstance) eventNode, 1);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);
    
    ksession.dispose();
}
 
Example 17
Source File: SLAComplianceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSLAonProcessViolatedNoTracking() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final ProcessEventListener listener = new DefaultProcessEventListener(){

        @Override
        public void afterSLAViolated(SLAViolatedEvent event) {
            latch.countDown();
        }
        
    };
    KieBase kbase = createKnowledgeBase("BPMN2-UserTaskWithSLA.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
    ksession.addEventListener(listener);
    ksession.getEnvironment().set("SLATimerMode", "false");
    
    ProcessInstance processInstance = ksession.startProcess("UserTask");
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    WorkItem workItem = workItemHandler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("john", workItem.getParameter("ActorId"));
    
 
    boolean slaViolated = latch.await(5, TimeUnit.SECONDS);
    assertFalse(slaViolated, "SLA should not violated by timer");

    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    int slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_PENDING, slaCompliance);
    
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    assertProcessInstanceFinished(processInstance, ksession);        
    
    slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);
    
    ksession.dispose();
}
 
Example 18
Source File: SLAComplianceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSLAonProcessViolated() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final ProcessEventListener listener = new DefaultProcessEventListener(){

        @Override
        public void afterSLAViolated(SLAViolatedEvent event) {
            latch.countDown();
        }
        
    };
    KieBase kbase = createKnowledgeBase("BPMN2-UserTaskWithSLA.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
    ksession.addEventListener(listener);
    
    ProcessInstance processInstance = ksession.startProcess("UserTask");
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    WorkItem workItem = workItemHandler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("john", workItem.getParameter("ActorId"));
    
    boolean slaViolated = latch.await(10, TimeUnit.SECONDS);
    assertTrue(slaViolated, "SLA was not violated while it is expected");

    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    int slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);
    
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    assertProcessInstanceFinished(processInstance, ksession);        
    
    slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);
    
    ksession.dispose();
}
 
Example 19
Source File: StrictAnnotationTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testEagerEvaluation() {
    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);
    try {
        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());
    } finally {
        ksession.dispose();
    }
}
 
Example 20
Source File: SLAComplianceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSLAonProcessViolatedExternalTracking() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final ProcessEventListener listener = new DefaultProcessEventListener(){

        @Override
        public void afterSLAViolated(SLAViolatedEvent event) {
            latch.countDown();
        }
        
    };
    KieBase kbase = createKnowledgeBase("BPMN2-UserTaskWithSLA.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
    ksession.addEventListener(listener);
    ksession.getEnvironment().set("SLATimerMode", "false");
    
    ProcessInstance processInstance = ksession.startProcess("UserTask");
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    WorkItem workItem = workItemHandler.getWorkItem();
    assertNotNull(workItem);
    assertEquals("john", workItem.getParameter("ActorId"));
    
 
    boolean slaViolated = latch.await(5, TimeUnit.SECONDS);
    assertFalse(slaViolated, "SLA should not violated by timer");

    // simulate external tracking of sla
    ksession.signalEvent("slaViolation", null, processInstance.getId());
    
    slaViolated = latch.await(10, TimeUnit.SECONDS);
    assertTrue(slaViolated, "SLA was not violated while it is expected");

    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);

    int slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);
    
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    assertProcessInstanceFinished(processInstance, ksession);        
    
    slaCompliance = getSLAComplianceForProcessInstance(processInstance);
    assertEquals(ProcessInstance.SLA_VIOLATED, slaCompliance);
    
    ksession.dispose();
}