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());
}
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());
}
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());
}
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);
}
}
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);
}
}
Aggregations