Search in sources :

Example 21 with ExecutorServiceImpl

use of org.jbpm.executor.impl.ExecutorServiceImpl 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 22 with ExecutorServiceImpl

use of org.jbpm.executor.impl.ExecutorServiceImpl 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 23 with ExecutorServiceImpl

use of org.jbpm.executor.impl.ExecutorServiceImpl 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 24 with ExecutorServiceImpl

use of org.jbpm.executor.impl.ExecutorServiceImpl in project jbpm by kiegroup.

the class AsyncWorkItemHandlerTest method testRunProcessWithAsyncHandlerProritizedJobs.

@Test(timeout = 10000)
public void testRunProcessWithAsyncHandlerProritizedJobs() throws Exception {
    CountDownAsyncJobListener countDownListener = new CountDownAsyncJobListener(1);
    ((ExecutorServiceImpl) executorService).addAsyncJobListener(countDownListener);
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("BPMN2-PrioritizedAsyncTasks.bpmn2"), ResourceType.BPMN2).registerableItemsFactory(new DefaultRegisterableItemsFactory() {

        @Override
        public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) {
            Map<String, WorkItemHandler> handlers = super.getWorkItemHandlers(runtime);
            handlers.put("async", new AsyncWorkItemHandler(executorService, "org.jbpm.executor.commands.PrintOutCommand"));
            return handlers;
        }
    }).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("async-examples.priority-jobs");
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    List<RequestInfo> delayedPrintOuts = executorService.getRequestsByCommand("org.jbpm.executor.test.CustomCommand", new QueryContext());
    List<RequestInfo> printOuts = executorService.getRequestsByCommand("org.jbpm.executor.commands.PrintOutCommand", new QueryContext());
    assertEquals(1, delayedPrintOuts.size());
    assertEquals(1, printOuts.size());
    assertEquals(STATUS.QUEUED, delayedPrintOuts.get(0).getStatus());
    assertEquals(STATUS.QUEUED, printOuts.get(0).getStatus());
    countDownListener.waitTillCompleted();
    delayedPrintOuts = executorService.getRequestsByCommand("org.jbpm.executor.test.CustomCommand", new QueryContext());
    printOuts = executorService.getRequestsByCommand("org.jbpm.executor.commands.PrintOutCommand", new QueryContext());
    assertEquals(1, delayedPrintOuts.size());
    assertEquals(1, printOuts.size());
    assertEquals(STATUS.DONE, delayedPrintOuts.get(0).getStatus());
    assertEquals(STATUS.QUEUED, printOuts.get(0).getStatus());
    countDownListener.reset(1);
    countDownListener.waitTillCompleted();
    delayedPrintOuts = executorService.getRequestsByCommand("org.jbpm.executor.test.CustomCommand", new QueryContext());
    printOuts = executorService.getRequestsByCommand("org.jbpm.executor.commands.PrintOutCommand", new QueryContext());
    assertEquals(1, delayedPrintOuts.size());
    assertEquals(1, printOuts.size());
    assertEquals(STATUS.DONE, delayedPrintOuts.get(0).getStatus());
    assertEquals(STATUS.DONE, printOuts.get(0).getStatus());
    processInstance = runtime.getKieSession().getProcessInstance(processInstance.getId());
    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) QueryContext(org.kie.api.runtime.query.QueryContext) RequestInfo(org.kie.api.executor.RequestInfo) WorkItemHandler(org.kie.api.runtime.process.WorkItemHandler) CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) AbstractExecutorBaseTest(org.jbpm.test.util.AbstractExecutorBaseTest) Test(org.junit.Test)

Example 25 with ExecutorServiceImpl

use of org.jbpm.executor.impl.ExecutorServiceImpl in project jbpm by kiegroup.

the class AsyncWorkItemHandlerTest method testRunProcessWithAsyncHandlerRecordExecutionErrorTaskAutoAck.

@SuppressWarnings("unchecked")
@Test(timeout = 20000)
public void testRunProcessWithAsyncHandlerRecordExecutionErrorTaskAutoAck() throws Exception {
    CountDownAsyncJobListener countDownListener = new CountDownAsyncJobListener(1);
    ((ExecutorServiceImpl) executorService).addAsyncJobListener(countDownListener);
    ((ExecutorServiceImpl) executorService).setRetries(0);
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().userGroupCallback(userGroupCallback).addAsset(ResourceFactory.newClassPathResource("BPMN2-UserTaskWithRollback.bpmn2"), ResourceType.BPMN2).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("UserTaskWithRollback");
    assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    processInstance = runtime.getKieSession().getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);
    manager.disposeRuntimeEngine(runtime);
    runtime = manager.getRuntimeEngine(EmptyContext.get());
    TaskService taskService = runtime.getTaskService();
    List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(1, tasks.size());
    long taskId = tasks.get(0).getId();
    TaskLifeCycleEventListener listener = new DefaultTaskEventListener() {

        @Override
        public void afterTaskStartedEvent(TaskEvent event) {
            throw new TaskExecutionException("On purpose");
        }
    };
    try {
        ((EventService<TaskLifeCycleEventListener>) taskService).registerTaskEventListener(listener);
        taskService.start(taskId, "john");
        fail("Start task should fail due to broken script");
    } catch (Throwable e) {
    // expected
    }
    manager.disposeRuntimeEngine(runtime);
    ExecutionErrorManager errorManager = ((AbstractRuntimeManager) manager).getExecutionErrorManager();
    assertNotNull("ErrorManager is null", errorManager);
    ExecutionErrorStorage errorStorage = errorManager.getStorage();
    assertNotNull("ErrorStorage is null", errorStorage);
    List<ExecutionError> errors = errorStorage.list(0, 10);
    assertEquals(1, errors.size());
    ExecutionError error = errors.get(0);
    assertNotNull(error);
    assertEquals("Task", error.getType());
    assertEquals("UserTaskWithRollback", error.getProcessId());
    assertEquals("Hello", error.getActivityName());
    assertEquals(manager.getIdentifier(), error.getDeploymentId());
    assertNotNull(error.getError());
    assertNotNull(error.getErrorMessage());
    assertNotNull(error.getActivityId());
    assertNotNull(error.getProcessInstanceId());
    assertNull(error.getAcknowledgedAt());
    assertNull(error.getAcknowledgedBy());
    assertFalse(error.isAcknowledged());
    countDownListener.reset(1);
    // first run should not ack the job as it's in error state
    CommandContext ctx = new CommandContext();
    ctx.setData("SingleRun", "true");
    ctx.setData("EmfName", "org.jbpm.persistence.complete");
    executorService.scheduleRequest(TaskAutoAckErrorCommand.class.getName(), ctx);
    countDownListener.waitTillCompleted();
    errors = errorStorage.list(0, 10);
    assertEquals(1, errors.size());
    error = errors.get(0);
    assertNotNull(error);
    assertFalse(error.isAcknowledged());
    runtime = manager.getRuntimeEngine(EmptyContext.get());
    tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals(1, tasks.size());
    taskId = tasks.get(0).getId();
    ((EventService<TaskLifeCycleEventListener>) taskService).removeTaskEventListener(listener);
    taskService.start(taskId, "john");
    Map<String, Object> results = new HashMap<>();
    results.put("output1", "ok");
    taskService.complete(taskId, "john", results);
    manager.disposeRuntimeEngine(runtime);
    countDownListener.reset(1);
    // since task was completed auto ack should work
    executorService.scheduleRequest(TaskAutoAckErrorCommand.class.getName(), ctx);
    countDownListener.waitTillCompleted();
    errors = errorStorage.list(0, 10);
    assertEquals(1, errors.size());
    error = errors.get(0);
    assertNotNull(error);
    assertTrue(error.isAcknowledged());
}
Also used : ExecutionError(org.kie.internal.runtime.error.ExecutionError) CommandContext(org.kie.api.executor.CommandContext) HashMap(java.util.HashMap) AbstractRuntimeManager(org.jbpm.runtime.manager.impl.AbstractRuntimeManager) TaskAutoAckErrorCommand(org.jbpm.executor.commands.error.TaskAutoAckErrorCommand) DefaultTaskEventListener(org.jbpm.services.task.events.DefaultTaskEventListener) CountDownAsyncJobListener(org.jbpm.executor.test.CountDownAsyncJobListener) ExecutionErrorManager(org.kie.internal.runtime.error.ExecutionErrorManager) ExecutionErrorStorage(org.kie.internal.runtime.error.ExecutionErrorStorage) KieSession(org.kie.api.runtime.KieSession) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) ExecutorServiceImpl(org.jbpm.executor.impl.ExecutorServiceImpl) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) TaskService(org.kie.api.task.TaskService) EventService(org.kie.internal.task.api.EventService) TaskExecutionException(org.jbpm.services.task.exception.TaskExecutionException) TaskSummary(org.kie.api.task.model.TaskSummary) TaskEvent(org.kie.api.task.TaskEvent) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) TaskLifeCycleEventListener(org.kie.api.task.TaskLifeCycleEventListener) AbstractExecutorBaseTest(org.jbpm.test.util.AbstractExecutorBaseTest) Test(org.junit.Test)

Aggregations

ExecutorServiceImpl (org.jbpm.executor.impl.ExecutorServiceImpl)32 Test (org.junit.Test)24 KieSession (org.kie.api.runtime.KieSession)18 CountDownAsyncJobListener (org.jbpm.executor.test.CountDownAsyncJobListener)17 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)16 HashMap (java.util.HashMap)13 CountDownAsyncJobListener (org.jbpm.test.listener.CountDownAsyncJobListener)13 QueryContext (org.kie.api.runtime.query.QueryContext)12 AbstractExecutorBaseTest (org.jbpm.test.util.AbstractExecutorBaseTest)8 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)8 RuntimeEnvironment (org.kie.api.runtime.manager.RuntimeEnvironment)8 DefaultRegisterableItemsFactory (org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory)6 WorkItemHandler (org.kie.api.runtime.process.WorkItemHandler)6 AsyncWorkItemHandler (org.jbpm.executor.impl.wih.AsyncWorkItemHandler)5 AbstractRuntimeManager (org.jbpm.runtime.manager.impl.AbstractRuntimeManager)5 RequestInfo (org.kie.api.executor.RequestInfo)5 NodeLeftCountDownProcessEventListener (org.jbpm.test.listener.NodeLeftCountDownProcessEventListener)4 CommandContext (org.kie.api.executor.CommandContext)4 WorkItemManager (org.kie.api.runtime.process.WorkItemManager)4 TaskSummary (org.kie.api.task.model.TaskSummary)4