Search in sources :

Example 26 with CountDownAsyncJobListener

use of org.jbpm.executor.test.CountDownAsyncJobListener in project jbpm by kiegroup.

the class JmsAvaiableJobExecutorTest method testAsyncAuditProducerNotExistingDeployment.

@Test
public void testAsyncAuditProducerNotExistingDeployment() throws Exception {
    CountDownAsyncJobListener countDownListener = configureListener(1);
    CommandContext ctxCMD = new CommandContext();
    ctxCMD.setData("businessKey", UUID.randomUUID().toString());
    ctxCMD.setData("deploymentId", "not-existing");
    UserTransaction ut = InitialContext.doLookup("java:comp/UserTransaction");
    ut.begin();
    executorService.scheduleRequest("org.jbpm.executor.commands.PrintOutCommand", ctxCMD);
    ut.commit();
    MessageReceiver receiver = new MessageReceiver();
    receiver.receiveAndProcess(queue, countDownListener, 3000);
    List<RequestInfo> inErrorRequests = executorService.getInErrorRequests(new QueryContext());
    assertEquals(0, inErrorRequests.size());
    List<RequestInfo> queuedRequests = executorService.getQueuedRequests(new QueryContext());
    assertEquals(1, queuedRequests.size());
    List<RequestInfo> executedRequests = executorService.getCompletedRequests(new QueryContext());
    assertEquals(0, executedRequests.size());
}
Also used : UserTransaction(javax.transaction.UserTransaction) CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) CommandContext(org.kie.api.executor.CommandContext) QueryContext(org.kie.api.runtime.query.QueryContext) RequestInfo(org.kie.api.executor.RequestInfo) Test(org.junit.Test)

Example 27 with CountDownAsyncJobListener

use of org.jbpm.executor.test.CountDownAsyncJobListener in project jbpm by kiegroup.

the class ParallelAsyncJobsTest method testRunBasicAsync.

/**
 * The tests verifies that async. jobs will be executed in parallel.
 *
 * JobExecutor configuration:
 * - Thread pool size = 4
 * - Pending task scan interval = 1 second
 *
 * The process in this test will create 4 long running tasks (8 seconds) one after another. Then
 * the test will sleep for 4 seconds giving the JobExecutor time to pick up at least 2 tasks.
 *
 * The JobExecutor should be able to pick up all the tasks because one task takes 8 seconds to
 * complete and the scan interval is 1 second. On the other hand a task should not complete in
 * the 4 seconds so pending task count should not be lower than 3 if parallelism does not work.
 */
@Test(timeout = 30000)
@BZ("1146829")
public void testRunBasicAsync() throws Exception {
    ExecutorService executorService = getExecutorService();
    final Set<String> threadExeuctingJobs = new HashSet<>();
    CountDownAsyncJobListener countDownListener = new CountDownAsyncJobListener(4) {

        @Override
        public void afterJobExecuted(AsynchronousJobEvent event) {
            super.afterJobExecuted(event);
            threadExeuctingJobs.add(Thread.currentThread().getName());
        }
    };
    ((ExecutorServiceImpl) executorService).addAsyncJobListener(countDownListener);
    KieSession ks = createKSession(PARENT, SUBPROCESS);
    ks.getWorkItemManager().registerWorkItemHandler("async", new AsyncWorkItemHandler(executorService, "org.jbpm.test.command.LongRunningCommand"));
    List<String> exceptions = new ArrayList<String>();
    exceptions.add("ADRESS_EXCEPTION");
    exceptions.add("ID_EXCEPTION");
    exceptions.add("PHONE_EXCEPTION");
    Map<String, Object> pm = new HashMap<String, Object>();
    pm.put("exceptions", exceptions);
    ProcessInstance pi = ks.startProcess(PARENT_ID, pm);
    // assert that the main process was completed as tasks are executed asynchronously
    assertProcessInstanceCompleted(pi.getId());
    countDownListener.waitTillCompleted();
    // assert that all jobs have where completed.
    Assertions.assertThat(executorService.getCompletedRequests(new QueryContext())).as("All async jobs should have been executed").hasSize(4);
    Assertions.assertThat(threadExeuctingJobs).as("There should be 4 distinct threads as jobs where executed in parallel").hasSize(4);
}
Also used : ExecutorServiceImpl(org.jbpm.executor.impl.ExecutorServiceImpl) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) QueryContext(org.kie.api.runtime.query.QueryContext) AsynchronousJobEvent(org.jbpm.executor.AsynchronousJobEvent) CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) ExecutorService(org.kie.api.executor.ExecutorService) AsyncWorkItemHandler(org.jbpm.executor.impl.wih.AsyncWorkItemHandler) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) HashSet(java.util.HashSet) Test(org.junit.Test) BZ(qa.tools.ikeeper.annotation.BZ)

Example 28 with CountDownAsyncJobListener

use of org.jbpm.executor.test.CountDownAsyncJobListener in project jbpm by kiegroup.

the class CarInsuranceClaimCaseTest method testCarInsuranceClaimCaseCloseCaseFromAsyncCommand.

@Test(timeout = 20000)
public void testCarInsuranceClaimCaseCloseCaseFromAsyncCommand() {
    executorService = ExecutorServiceFactory.newExecutorService(emf);
    executorService.init();
    CountDownAsyncJobListener countDownListener = new CountDownAsyncJobListener(1);
    ((ExecutorServiceImpl) executorService).addAsyncJobListener(countDownListener);
    // let's assign users to roles so they can be participants in the case
    String caseId = startAndAssertCaseInstance(deploymentUnit.getIdentifier(), "john", "mary");
    try {
        // let's verify case is created
        assertCaseInstance(deploymentUnit.getIdentifier(), CAR_INS_CASE_ID);
        // let's look at what stages are active
        assertBuildClaimReportStage();
        // since the first task assigned to insured is with auto start it should be already active
        // the same task can be claimed by insuranceRepresentative in case claim is reported over phone
        long taskId = assertBuildClaimReportAvailableForBothRoles();
        // let's provide claim report with initial data
        // claim report should be stored in case file data
        provideAndAssertClaimReport(taskId);
        // now we have another task for insured to provide property damage report
        taskId = assertPropertyDamageReportAvailableForBothRoles();
        // let's provide the property damage report
        provideAndAssertPropertyDamageReport(taskId);
        // let's complete the stage by explicitly stating that claimReport is done
        caseService.addDataToCaseFile(CAR_INS_CASE_ID, "claimReportDone", true);
        // we should be in another stage - Claim assessment
        assertClaimAssesmentStage();
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("CaseId", CAR_INS_CASE_ID);
        parameters.put("CommandClass", AsyncCloseCaseCommand.class.getName());
        caseService.addDynamicTask(CAR_INS_CASE_ID, caseService.newTaskSpec("async", "CloseCaseAsync", parameters));
        countDownListener.waitTillCompleted();
        // there should be no process instances for the case
        Collection<ProcessInstanceDesc> caseProcesInstances = caseRuntimeDataService.getProcessInstancesForCase(CAR_INS_CASE_ID, Arrays.asList(ProcessInstance.STATE_ACTIVE), new QueryContext());
        assertEquals(0, caseProcesInstances.size());
        CaseInstance cInstance = caseRuntimeDataService.getCaseInstanceById(caseId);
        assertNotNull(cInstance);
        assertEquals(deploymentUnit.getIdentifier(), cInstance.getDeploymentId());
        assertEquals("Closing case from async command", cInstance.getCompletionMessage());
        caseId = null;
    } catch (Exception e) {
        logger.error("Unexpected error {}", e.getMessage(), e);
        fail("Unexpected exception " + e.getMessage());
    } finally {
        if (caseId != null) {
            caseService.cancelCase(caseId);
        }
    }
}
Also used : ExecutorServiceImpl(org.jbpm.executor.impl.ExecutorServiceImpl) HashMap(java.util.HashMap) ProcessInstanceDesc(org.jbpm.services.api.model.ProcessInstanceDesc) QueryContext(org.kie.api.runtime.query.QueryContext) CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) AsyncCloseCaseCommand(org.jbpm.casemgmt.impl.objects.AsyncCloseCaseCommand) CaseInstance(org.jbpm.casemgmt.api.model.instance.CaseInstance) AbstractCaseServicesBaseTest(org.jbpm.casemgmt.impl.util.AbstractCaseServicesBaseTest) Test(org.junit.Test)

Example 29 with CountDownAsyncJobListener

use of org.jbpm.executor.test.CountDownAsyncJobListener in project jbpm by kiegroup.

the class AsyncContinuationSupportTest method testAsyncModeWithSignal.

@Test(timeout = 10000)
public void testAsyncModeWithSignal() throws Exception {
    CountDownAsyncJobListener initialJob = new CountDownAsyncJobListener(1);
    ((ExecutorServiceImpl) executorService).addAsyncJobListener(initialJob);
    final NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("SignalEnd", 1);
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("ProbAsync.bpmn2"), ResourceType.BPMN2).addEnvironmentEntry("ExecutorService", executorService).addEnvironmentEntry("AsyncMode", "true").registerableItemsFactory(new DefaultRegisterableItemsFactory() {

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

        @Override
        public List<ProcessEventListener> getProcessEventListeners(RuntimeEngine runtime) {
            List<ProcessEventListener> listeners = super.getProcessEventListeners(runtime);
            listeners.add(countDownListener);
            return listeners;
        }
    }).get();
    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);
    RuntimeEngine runtime = manager.getRuntimeEngine(EmptyContext.get());
    KieSession ksession = runtime.getKieSession();
    assertNotNull(ksession);
    Map<String, Object> params = new HashMap<>();
    params.put("timer1", "20s");
    params.put("timer2", "10s");
    ProcessInstance processInstance = ksession.startProcess("ProbAsync", params);
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    long processInstanceId = processInstance.getId();
    initialJob.waitTillCompleted();
    List<TaskSummary> tasks = runtime.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(1, tasks.size());
    long taskId = tasks.get(0).getId();
    runtime.getTaskService().start(taskId, "john");
    runtime.getTaskService().complete(taskId, "john", null);
    runtime.getKieSession().signalEvent("signal1", null, processInstanceId);
    countDownListener.waitTillCompleted();
    processInstance = runtime.getKieSession().getProcessInstance(processInstanceId);
    assertNull(processInstance);
}
Also used : DefaultRegisterableItemsFactory(org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) ExecutorServiceImpl(org.jbpm.executor.impl.ExecutorServiceImpl) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) HashMap(java.util.HashMap) NodeTriggeredCountDownProcessEventListener(org.jbpm.test.listener.NodeTriggeredCountDownProcessEventListener) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) SystemOutWorkItemHandler(org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler) CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) TaskSummary(org.kie.api.task.model.TaskSummary) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) AbstractExecutorBaseTest(org.jbpm.test.util.AbstractExecutorBaseTest) Test(org.junit.Test)

Example 30 with CountDownAsyncJobListener

use of org.jbpm.executor.test.CountDownAsyncJobListener in project jbpm by kiegroup.

the class AsyncThrowSignalEventTest method testAsyncThrowIntermediateEvent.

@Test(timeout = 10000)
public void testAsyncThrowIntermediateEvent() throws Exception {
    CountDownAsyncJobListener countDownListener = configureListener(1);
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("BPMN2-WaitForEvent.bpmn2"), ResourceType.BPMN2).addAsset(ResourceFactory.newClassPathResource("BPMN2-ThrowEventIntermediate.bpmn2"), ResourceType.BPMN2).addEnvironmentEntry("ExecutorService", executorService).get();
    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);
    RuntimeEngine runtime = manager.getRuntimeEngine(EmptyContext.get());
    KieSession ksession = runtime.getKieSession();
    assertNotNull(ksession);
    ProcessInstance processInstance = ksession.startProcess("WaitForEvent");
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    ProcessInstance processInstanceThrow = ksession.startProcess("SendIntermediateEvent");
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstanceThrow.getState());
    countDownListener.waitTillCompleted();
    processInstance = runtime.getKieSession().getProcessInstance(processInstance.getId());
    assertNull(processInstance);
}
Also used : CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) Test(org.junit.Test) AbstractExecutorBaseTest(org.jbpm.test.util.AbstractExecutorBaseTest)

Aggregations

CountDownAsyncJobListener (org.jbpm.executor.test.CountDownAsyncJobListener)50 Test (org.junit.Test)43 QueryContext (org.kie.api.runtime.query.QueryContext)27 CommandContext (org.kie.api.executor.CommandContext)25 RequestInfo (org.kie.api.executor.RequestInfo)25 KieSession (org.kie.api.runtime.KieSession)20 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)20 AbstractExecutorBaseTest (org.jbpm.test.util.AbstractExecutorBaseTest)19 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)19 RuntimeEnvironment (org.kie.api.runtime.manager.RuntimeEnvironment)19 ExecutorServiceImpl (org.jbpm.executor.impl.ExecutorServiceImpl)17 AtomicLong (java.util.concurrent.atomic.AtomicLong)9 HashMap (java.util.HashMap)8 DefaultRegisterableItemsFactory (org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory)7 WorkItemHandler (org.kie.api.runtime.process.WorkItemHandler)7 TaskSummary (org.kie.api.task.model.TaskSummary)7 ExecutionError (org.kie.internal.runtime.error.ExecutionError)7 ExecutionErrorStorage (org.kie.internal.runtime.error.ExecutionErrorStorage)7 ErrorInfo (org.kie.api.executor.ErrorInfo)6 Date (java.util.Date)5