Search in sources :

Example 26 with CommandContext

use of org.kie.api.executor.CommandContext in project jbpm by kiegroup.

the class BasicExecutorIntegrationTest method executorExceptionTest.

@Test
public void executorExceptionTest() throws InterruptedException {
    CommandContext commandContext = new CommandContext();
    commandContext.setData("businessKey", UUID.randomUUID().toString());
    cachedEntities.put((String) commandContext.getData("businessKey"), new AtomicLong(1));
    commandContext.setData("callbacks", "org.jbpm.executor.ejb.impl.test.SimpleIncrementCallback");
    commandContext.setData("retries", 0);
    executorService.scheduleRequest("org.jbpm.executor.ejb.impl.test.ThrowExceptionCommand", commandContext);
    logger.info("{} Sleeping for 10 secs", System.currentTimeMillis());
    Thread.sleep(10000);
    List<RequestInfo> inErrorRequests = executorService.getInErrorRequests(new QueryContext());
    assertEquals(1, inErrorRequests.size());
    logger.info("Error: {}", inErrorRequests.get(0));
    List<ErrorInfo> errors = executorService.getAllErrors(new QueryContext());
    logger.info("Errors: {}", errors);
    assertEquals(1, errors.size());
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) CommandContext(org.kie.api.executor.CommandContext) ErrorInfo(org.kie.api.executor.ErrorInfo) QueryContext(org.kie.api.runtime.query.QueryContext) RequestInfo(org.kie.api.executor.RequestInfo) Test(org.junit.Test)

Example 27 with CommandContext

use of org.kie.api.executor.CommandContext in project jbpm by kiegroup.

the class BasicExecutorIntegrationTest method cleanupLogExcecutionTest.

@Test
public void cleanupLogExcecutionTest() throws InterruptedException {
    CommandContext ctxCMD = new CommandContext();
    ctxCMD.setData("businessKey", UUID.randomUUID().toString());
    Long requestId = executorService.scheduleRequest("org.jbpm.executor.commands.ReoccurringPrintOutCommand", ctxCMD);
    Thread.sleep(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(3, executedRequests.size());
    executorService.cancelRequest(requestId + 3);
    List<RequestInfo> canceled = executorService.getCancelledRequests(new QueryContext());
    ExecutorJPAAuditService auditService = new ExecutorJPAAuditService(emf);
    int resultCount = auditService.requestInfoLogDeleteBuilder().date(canceled.get(0).getTime()).status(STATUS.ERROR).build().execute();
    assertEquals(0, resultCount);
    resultCount = auditService.errorInfoLogDeleteBuilder().date(canceled.get(0).getTime()).build().execute();
    assertEquals(0, resultCount);
    ctxCMD = new CommandContext();
    ctxCMD.setData("businessKey", UUID.randomUUID().toString());
    ctxCMD.setData("SingleRun", "true");
    ctxCMD.setData("EmfName", "org.jbpm.domain");
    ctxCMD.setData("SkipProcessLog", "true");
    ctxCMD.setData("SkipTaskLog", "true");
    executorService.scheduleRequest("org.jbpm.executor.commands.LogCleanupCommand", ctxCMD);
    Thread.sleep(5000);
    inErrorRequests = executorService.getInErrorRequests(new QueryContext());
    assertEquals(0, inErrorRequests.size());
    queuedRequests = executorService.getQueuedRequests(new QueryContext());
    assertEquals(0, queuedRequests.size());
    executedRequests = executorService.getCompletedRequests(new QueryContext());
    assertEquals(1, executedRequests.size());
}
Also used : CommandContext(org.kie.api.executor.CommandContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) QueryContext(org.kie.api.runtime.query.QueryContext) ExecutorJPAAuditService(org.jbpm.executor.impl.jpa.ExecutorJPAAuditService) RequestInfo(org.kie.api.executor.RequestInfo) Test(org.junit.Test)

Example 28 with CommandContext

use of org.kie.api.executor.CommandContext 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)

Example 29 with CommandContext

use of org.kie.api.executor.CommandContext in project jbpm by kiegroup.

the class AsyncWorkItemHandler method executeWorkItem.

@Override
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    if (executorService == null || !executorService.isActive()) {
        throw new IllegalStateException("Executor is not set or is not active");
    }
    boolean autoComplete = false;
    if (workItem.getParameter("AutoComplete") != null) {
        autoComplete = Boolean.parseBoolean(workItem.getParameter("AutoComplete").toString());
    }
    String businessKey = buildBusinessKey(workItem);
    logger.debug("Executing work item {} with built business key {}", workItem, businessKey);
    String cmdClass = (String) workItem.getParameter("CommandClass");
    if (cmdClass == null) {
        cmdClass = this.commandClass;
    }
    logger.debug("Command class for this execution is {}", cmdClass);
    CommandContext ctxCMD = new CommandContext();
    ctxCMD.setData("businessKey", businessKey);
    ctxCMD.setData("workItem", workItem);
    ctxCMD.setData("processInstanceId", getProcessInstanceId(workItem));
    ctxCMD.setData("deploymentId", ((WorkItemImpl) workItem).getDeploymentId());
    // in case auto complete is selected skip callback
    if (!autoComplete) {
        ctxCMD.setData("callbacks", AsyncWorkItemHandlerCmdCallback.class.getName());
    }
    if (workItem.getParameter("Retries") != null) {
        ctxCMD.setData("retries", Integer.parseInt(workItem.getParameter("Retries").toString()));
    }
    if (workItem.getParameter("Owner") != null) {
        ctxCMD.setData("owner", workItem.getParameter("Owner"));
    }
    if (workItem.getParameter("RetryDelay") != null) {
        ctxCMD.setData("retryDelay", workItem.getParameter("RetryDelay"));
    }
    if (workItem.getParameter("Priority") != null) {
        ctxCMD.setData("priority", Integer.parseInt(workItem.getParameter("Priority").toString()));
    }
    Date scheduleDate = null;
    if (workItem.getParameter("Delay") != null) {
        long delayInMillis = TimeUtils.parseTimeString((String) workItem.getParameter("Delay"));
        scheduleDate = new Date(System.currentTimeMillis() + delayInMillis);
    }
    logger.trace("Command context {}", ctxCMD);
    Long requestId = executorService.scheduleRequest(cmdClass, scheduleDate, ctxCMD);
    logger.debug("Request scheduled successfully with id {}", requestId);
    if (autoComplete) {
        logger.debug("Auto completing work item with id {}", workItem.getId());
        manager.completeWorkItem(workItem.getId(), null);
    }
}
Also used : CommandContext(org.kie.api.executor.CommandContext) Date(java.util.Date)

Example 30 with CommandContext

use of org.kie.api.executor.CommandContext in project jbpm by kiegroup.

the class AsyncWorkItemHandlerCmdCallback method onCommandError.

@Override
public void onCommandError(CommandContext ctx, final Throwable exception) {
    final Long processInstanceId = (Long) ctx.getData("processInstanceId");
    final WorkItem workItem = (WorkItem) ctx.getData("workItem");
    // find the right runtime to do the complete
    RuntimeManager manager = getRuntimeManager(ctx);
    RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
    final ExecutionErrorHandler errorHandler = getExecutionErrorHandler(manager);
    try {
        boolean isErrorHandled = engine.getKieSession().execute(new ExecutableCommand<Boolean>() {

            private static final long serialVersionUID = 1L;

            @Override
            public Boolean execute(Context context) {
                KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
                WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
                NodeInstance nodeInstance = getNodeInstance(workItem, processInstance);
                Throwable actualException = exception;
                if (actualException instanceof AsyncJobException) {
                    actualException = exception.getCause();
                }
                String exceptionName = actualException.getClass().getName();
                ExceptionScopeInstance exceptionScopeInstance = (ExceptionScopeInstance) ((org.jbpm.workflow.instance.NodeInstance) nodeInstance).resolveContextInstance(ExceptionScope.EXCEPTION_SCOPE, exceptionName);
                if (exceptionScopeInstance != null) {
                    logger.debug("Handling job error '{}' via process error handling", actualException.getMessage());
                    exceptionScopeInstance.handleException(exceptionName, actualException);
                    return true;
                } else {
                    logger.debug("No process level error handling for '{}' letting it to be handled by execution errors", exception.getMessage());
                    errorHandler.processing(nodeInstance);
                    return false;
                }
            }
        });
        if (!isErrorHandled) {
            logger.debug("Error '{}' was not handled on process level, handling it via execution errors mechanism", exception.getMessage());
            errorHandler.handle(exception);
        }
    } catch (Exception e) {
        logger.error("Error when handling callback from executor", e);
    } finally {
        manager.disposeRuntimeEngine(engine);
        closeErrorHandler(manager);
    }
}
Also used : ProcessInstanceIdContext(org.kie.internal.runtime.manager.context.ProcessInstanceIdContext) CommandContext(org.kie.api.executor.CommandContext) RegistryContext(org.drools.core.command.impl.RegistryContext) Context(org.kie.api.runtime.Context) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) AbstractRuntimeManager(org.jbpm.runtime.manager.impl.AbstractRuntimeManager) WorkItem(org.kie.api.runtime.process.WorkItem) AsyncJobException(org.jbpm.executor.AsyncJobException) ExecutionErrorHandler(org.kie.internal.runtime.error.ExecutionErrorHandler) NoOpExecutionErrorHandler(org.jbpm.process.instance.impl.NoOpExecutionErrorHandler) AsyncJobException(org.jbpm.executor.AsyncJobException) KieSession(org.kie.api.runtime.KieSession) NodeInstance(org.kie.api.runtime.process.NodeInstance) WorkItemNodeInstance(org.jbpm.workflow.instance.node.WorkItemNodeInstance) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) ExceptionScopeInstance(org.jbpm.process.instance.context.exception.ExceptionScopeInstance)

Aggregations

CommandContext (org.kie.api.executor.CommandContext)52 Test (org.junit.Test)43 RequestInfo (org.kie.api.executor.RequestInfo)39 QueryContext (org.kie.api.runtime.query.QueryContext)39 CountDownAsyncJobListener (org.jbpm.executor.test.CountDownAsyncJobListener)25 AtomicLong (java.util.concurrent.atomic.AtomicLong)22 Date (java.util.Date)10 ErrorInfo (org.kie.api.executor.ErrorInfo)9 KieSession (org.kie.api.runtime.KieSession)6 HashMap (java.util.HashMap)5 RuntimeManager (org.kie.api.runtime.manager.RuntimeManager)5 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 IOException (java.io.IOException)4 ObjectInputStream (java.io.ObjectInputStream)4 ExecutorServiceImpl (org.jbpm.executor.impl.ExecutorServiceImpl)4 AsyncSignalEventCommand (org.jbpm.process.core.async.AsyncSignalEventCommand)4 AbstractRuntimeManager (org.jbpm.runtime.manager.impl.AbstractRuntimeManager)4 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)4 UserTransaction (javax.transaction.UserTransaction)3