Search in sources :

Example 6 with TaskEvent

use of org.kie.api.task.TaskEvent in project jbpm by kiegroup.

the class JPATaskLifeCycleEventListener method afterTaskForwardedEvent.

@Override
public void afterTaskForwardedEvent(TaskEvent event) {
    String userId = event.getTaskContext().getUserId();
    Task ti = event.getTask();
    TaskPersistenceContext persistenceContext = getPersistenceContext(((TaskContext) event.getTaskContext()).getPersistenceContext());
    try {
        StringBuilder message = new StringBuilder();
        String entitiesAsString = (ti.getPeopleAssignments().getPotentialOwners()).stream().map(oe -> oe.getId()).collect(Collectors.joining(","));
        message.append("Forward to [" + entitiesAsString + "]");
        persistenceContext.persist(new TaskEventImpl(ti.getId(), org.kie.internal.task.api.model.TaskEvent.TaskEventType.FORWARDED, ti.getTaskData().getProcessInstanceId(), ti.getTaskData().getWorkItemId(), userId, message.toString()));
        AuditTaskImpl auditTaskImpl = getAuditTask(event, persistenceContext, ti);
        if (auditTaskImpl == null) {
            logger.warn("Unable find audit task entry for task id {} '{}', skipping audit task update", ti.getId(), ti.getName());
            return;
        }
        auditTaskImpl.setDescription(ti.getDescription());
        auditTaskImpl.setName(ti.getName());
        auditTaskImpl.setActivationTime(ti.getTaskData().getActivationTime());
        auditTaskImpl.setPriority(ti.getPriority());
        auditTaskImpl.setDueDate(ti.getTaskData().getExpirationTime());
        auditTaskImpl.setStatus(ti.getTaskData().getStatus().name());
        auditTaskImpl.setActualOwner(getActualOwner(ti));
        auditTaskImpl.setLastModificationDate(event.getEventDate());
        persistenceContext.merge(auditTaskImpl);
    } finally {
        cleanup(persistenceContext);
    }
}
Also used : PersistableEventListener(org.jbpm.services.task.persistence.PersistableEventListener) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) Task(org.kie.api.task.model.Task) Date(java.util.Date) TaskVariable(org.kie.internal.task.api.TaskVariable) TaskEventImpl(org.jbpm.services.task.audit.impl.model.TaskEventImpl) VariableType(org.kie.internal.task.api.TaskVariable.VariableType) LoggerFactory(org.slf4j.LoggerFactory) AuditTaskImpl(org.jbpm.services.task.audit.impl.model.AuditTaskImpl) HashMap(java.util.HashMap) ClassUtil(org.jbpm.services.task.utils.ClassUtil) Collectors(java.util.stream.Collectors) TaskLifeCycleEventListener(org.jbpm.services.task.lifecycle.listeners.TaskLifeCycleEventListener) TaskEvent(org.kie.api.task.TaskEvent) OrganizationalEntity(org.kie.api.task.model.OrganizationalEntity) TaskIndexerManager(org.jbpm.services.task.audit.variable.TaskIndexerManager) List(java.util.List) TaskContext(org.kie.internal.task.api.TaskContext) EntityManagerFactory(javax.persistence.EntityManagerFactory) Map(java.util.Map) TaskPersistenceContext(org.kie.internal.task.api.TaskPersistenceContext) Task(org.kie.api.task.model.Task) TaskEventImpl(org.jbpm.services.task.audit.impl.model.TaskEventImpl) TaskPersistenceContext(org.kie.internal.task.api.TaskPersistenceContext) AuditTaskImpl(org.jbpm.services.task.audit.impl.model.AuditTaskImpl)

Example 7 with TaskEvent

use of org.kie.api.task.TaskEvent in project jbpm by kiegroup.

the class LifeCycleBaseTest method testCompleteWithMergeOfResultsOverrideAndAddAtCompletion.

@Test
public void testCompleteWithMergeOfResultsOverrideAndAddAtCompletion() {
    final Map<String, Object> outputsAfterCompletion = new HashMap<String, Object>();
    // One potential owner, should go straight to state Reserved
    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { } ), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) { potentialOwners = [new User('Bobba Fet'), new User('Darth Vader') ], businessAdministrators = [ new User('Administrator') ],}),";
    str += "name = 'This is my task name' })";
    ((EventService<TaskLifeCycleEventListener>) taskService).registerTaskEventListener(new DefaultTaskEventListener() {

        @Override
        public void afterTaskCompletedEvent(TaskEvent event) {
            outputsAfterCompletion.putAll(event.getTask().getTaskData().getTaskOutputVariables());
        }
    });
    Task task = TaskFactory.evalTask(new StringReader(str));
    taskService.addTask(task, new HashMap<String, Object>());
    long taskId = task.getId();
    taskService.start(taskId, "Darth Vader");
    Task task1 = taskService.getTaskById(taskId);
    assertEquals(Status.InProgress, task1.getTaskData().getStatus());
    assertEquals("Darth Vader", task1.getTaskData().getActualOwner().getId());
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("response", "not sure");
    taskService.addContent(taskId, params);
    task1 = taskService.getTaskById(taskId);
    Map<String, Object> outputs = getTaskOutput(task1);
    assertEquals(1, outputs.size());
    assertEquals("not sure", outputs.get("response"));
    params.clear();
    params.put("response", "let's do it");
    params.put("feedback", "ok");
    taskService.complete(taskId, "Darth Vader", params);
    task1 = taskService.getTaskById(taskId);
    assertEquals(Status.Completed, task1.getTaskData().getStatus());
    assertEquals("Darth Vader", task1.getTaskData().getActualOwner().getId());
    outputs = getTaskOutput(task1);
    assertEquals(2, outputs.size());
    assertEquals("let's do it", outputs.get("response"));
    assertEquals("ok", outputs.get("feedback"));
    // now let's check what was actually given to listeners
    assertEquals(2, outputsAfterCompletion.size());
    assertEquals("let's do it", outputsAfterCompletion.get("response"));
    assertEquals("ok", outputsAfterCompletion.get("feedback"));
}
Also used : Task(org.kie.api.task.model.Task) InternalTask(org.kie.internal.task.api.model.InternalTask) HashMap(java.util.HashMap) TaskEvent(org.kie.api.task.TaskEvent) StringReader(java.io.StringReader) EventService(org.kie.internal.task.api.EventService) DefaultTaskEventListener(org.jbpm.services.task.events.DefaultTaskEventListener) Test(org.junit.Test)

Example 8 with TaskEvent

use of org.kie.api.task.TaskEvent in project jbpm by kiegroup.

the class LifeCycleBaseTest method testCompleteWithMergeOfResultsOverrideAtCompletion.

@Test
public void testCompleteWithMergeOfResultsOverrideAtCompletion() {
    final Map<String, Object> outputsAfterCompletion = new HashMap<String, Object>();
    // One potential owner, should go straight to state Reserved
    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { } ), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) { potentialOwners = [new User('Bobba Fet'), new User('Darth Vader') ], businessAdministrators = [ new User('Administrator') ],}),";
    str += "name = 'This is my task name' })";
    ((EventService<TaskLifeCycleEventListener>) taskService).registerTaskEventListener(new DefaultTaskEventListener() {

        @Override
        public void afterTaskCompletedEvent(TaskEvent event) {
            outputsAfterCompletion.putAll(event.getTask().getTaskData().getTaskOutputVariables());
        }
    });
    Task task = TaskFactory.evalTask(new StringReader(str));
    taskService.addTask(task, new HashMap<String, Object>());
    long taskId = task.getId();
    taskService.start(taskId, "Darth Vader");
    Task task1 = taskService.getTaskById(taskId);
    assertEquals(Status.InProgress, task1.getTaskData().getStatus());
    assertEquals("Darth Vader", task1.getTaskData().getActualOwner().getId());
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("response", "not sure");
    taskService.addContent(taskId, params);
    task1 = taskService.getTaskById(taskId);
    Map<String, Object> outputs = getTaskOutput(task1);
    assertEquals(1, outputs.size());
    assertEquals("not sure", outputs.get("response"));
    params.clear();
    params.put("response", "let's do it");
    taskService.complete(taskId, "Darth Vader", params);
    task1 = taskService.getTaskById(taskId);
    assertEquals(Status.Completed, task1.getTaskData().getStatus());
    assertEquals("Darth Vader", task1.getTaskData().getActualOwner().getId());
    outputs = getTaskOutput(task1);
    assertEquals(1, outputs.size());
    assertEquals("let's do it", outputs.get("response"));
    // now let's check what was actually given to listeners
    assertEquals(1, outputsAfterCompletion.size());
    assertEquals("let's do it", outputsAfterCompletion.get("response"));
}
Also used : Task(org.kie.api.task.model.Task) InternalTask(org.kie.internal.task.api.model.InternalTask) HashMap(java.util.HashMap) TaskEvent(org.kie.api.task.TaskEvent) StringReader(java.io.StringReader) EventService(org.kie.internal.task.api.EventService) DefaultTaskEventListener(org.jbpm.services.task.events.DefaultTaskEventListener) Test(org.junit.Test)

Example 9 with TaskEvent

use of org.kie.api.task.TaskEvent in project jbpm by kiegroup.

the class LifeCycleBaseTest method testCompleteWithMergeOfResultsEmptyAtCompletion.

@Test
public void testCompleteWithMergeOfResultsEmptyAtCompletion() {
    final Map<String, Object> outputsAfterCompletion = new HashMap<String, Object>();
    // One potential owner, should go straight to state Reserved
    String str = "(with (new Task()) { priority = 55, taskData = (with( new TaskData()) { } ), ";
    str += "peopleAssignments = (with ( new PeopleAssignments() ) { potentialOwners = [new User('Bobba Fet'), new User('Darth Vader') ], businessAdministrators = [ new User('Administrator') ],}),";
    str += "name = 'This is my task name' })";
    ((EventService<TaskLifeCycleEventListener>) taskService).registerTaskEventListener(new DefaultTaskEventListener() {

        @Override
        public void afterTaskCompletedEvent(TaskEvent event) {
            outputsAfterCompletion.putAll(event.getTask().getTaskData().getTaskOutputVariables());
        }
    });
    Task task = TaskFactory.evalTask(new StringReader(str));
    taskService.addTask(task, new HashMap<String, Object>());
    long taskId = task.getId();
    taskService.start(taskId, "Darth Vader");
    Task task1 = taskService.getTaskById(taskId);
    assertEquals(Status.InProgress, task1.getTaskData().getStatus());
    assertEquals("Darth Vader", task1.getTaskData().getActualOwner().getId());
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("response", "not sure");
    taskService.addContent(taskId, params);
    task1 = taskService.getTaskById(taskId);
    Map<String, Object> outputs = getTaskOutput(task1);
    assertEquals(1, outputs.size());
    assertEquals("not sure", outputs.get("response"));
    params.clear();
    taskService.complete(taskId, "Darth Vader", params);
    task1 = taskService.getTaskById(taskId);
    assertEquals(Status.Completed, task1.getTaskData().getStatus());
    assertEquals("Darth Vader", task1.getTaskData().getActualOwner().getId());
    outputs = getTaskOutput(task1);
    assertEquals(1, outputs.size());
    assertEquals("not sure", outputs.get("response"));
    // now let's check what was actually given to listeners
    assertEquals(1, outputsAfterCompletion.size());
    assertEquals("not sure", outputsAfterCompletion.get("response"));
}
Also used : Task(org.kie.api.task.model.Task) InternalTask(org.kie.internal.task.api.model.InternalTask) HashMap(java.util.HashMap) TaskEvent(org.kie.api.task.TaskEvent) StringReader(java.io.StringReader) EventService(org.kie.internal.task.api.EventService) DefaultTaskEventListener(org.jbpm.services.task.events.DefaultTaskEventListener) Test(org.junit.Test)

Example 10 with TaskEvent

use of org.kie.api.task.TaskEvent 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

TaskEvent (org.kie.api.task.TaskEvent)10 HashMap (java.util.HashMap)8 DefaultTaskEventListener (org.jbpm.services.task.events.DefaultTaskEventListener)8 Test (org.junit.Test)8 Task (org.kie.api.task.model.Task)7 EventService (org.kie.internal.task.api.EventService)7 StringReader (java.io.StringReader)5 InternalTask (org.kie.internal.task.api.model.InternalTask)5 Map (java.util.Map)3 KieSession (org.kie.api.runtime.KieSession)3 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)3 Arrays (java.util.Arrays)2 Date (java.util.Date)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 EntityManagerFactory (javax.persistence.EntityManagerFactory)2 AbstractRuntimeManager (org.jbpm.runtime.manager.impl.AbstractRuntimeManager)2 AuditTaskImpl (org.jbpm.services.task.audit.impl.model.AuditTaskImpl)2 TaskEventImpl (org.jbpm.services.task.audit.impl.model.TaskEventImpl)2 TaskIndexerManager (org.jbpm.services.task.audit.variable.TaskIndexerManager)2