use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.
the class CloseCaseCommand method execute.
@Override
public Void execute(Context context) {
CorrelationKey correlationKey = correlationKeyFactory.newCorrelationKey(caseId);
Collection<ProcessInstanceDesc> caseProcesses = runtimeDataService.getProcessInstancesByCorrelationKey(correlationKey, new QueryContext(0, 1000));
if (caseProcesses.isEmpty()) {
throw new CaseNotFoundException("Case with id " + caseId + " was not found");
}
final List<Long> processInstanceIds = caseProcesses.stream().filter(pi -> pi.getState().equals(ProcessInstance.STATE_ACTIVE)).sorted((ProcessInstanceDesc o1, ProcessInstanceDesc o2) -> {
return Long.valueOf(o2.getParentId()).compareTo(Long.valueOf(o1.getParentId()));
}).map(pi -> pi.getId()).collect(toList());
CaseEventSupport caseEventSupport = getCaseEventSupport(context);
KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
CaseFileInstance caseFile = getCaseFile(ksession, caseId);
caseEventSupport.fireBeforeCaseClosed(caseId, caseFile, comment);
logger.debug("Process instances {} that will be completed as part of the close of the case {}", processInstanceIds, caseId);
processService.execute(deploymentId, CaseContext.get(caseId), new ExecutableCommand<Void>() {
private static final long serialVersionUID = 1L;
@Override
public Void execute(Context context) {
KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
for (Long processInstanceId : processInstanceIds) {
WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
processInstance.setState(ProcessInstance.STATE_COMPLETED, comment);
logger.debug("Process instance {} set to state completed", processInstanceId);
}
return null;
}
});
caseEventSupport.fireAfterCaseClosed(caseId, caseFile, comment);
return null;
}
use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.
the class DynamicUtils method internalAddDynamicSubProcess.
public static long internalAddDynamicSubProcess(final WorkflowProcessInstance processInstance, final DynamicNodeInstance dynamicContext, KieRuntime ksession, final String processId, final Map<String, Object> parameters) {
final SubProcessNodeInstance subProcessNodeInstance = new SubProcessNodeInstance();
subProcessNodeInstance.setNodeInstanceContainer(dynamicContext == null ? processInstance : dynamicContext);
subProcessNodeInstance.setProcessInstance(processInstance);
subProcessNodeInstance.setMetaData("NodeType", "SubProcessNode");
if (ksession instanceof StatefulKnowledgeSessionImpl) {
return executeSubProcess((StatefulKnowledgeSessionImpl) ksession, processId, parameters, processInstance, subProcessNodeInstance);
} else if (ksession instanceof CommandBasedStatefulKnowledgeSession) {
ExecutableRunner commandService = ((CommandBasedStatefulKnowledgeSession) ksession).getRunner();
return commandService.execute(new ExecutableCommand<Long>() {
private static final long serialVersionUID = 5L;
public Long execute(Context context) {
StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) ((RegistryContext) context).lookup(KieSession.class);
WorkflowProcessInstance realProcessInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstance.getId());
subProcessNodeInstance.setProcessInstance(realProcessInstance);
if (dynamicContext == null) {
subProcessNodeInstance.setNodeInstanceContainer(realProcessInstance);
} else {
DynamicNodeInstance realDynamicContext = findDynamicContext(realProcessInstance, dynamicContext.getUniqueId());
subProcessNodeInstance.setNodeInstanceContainer(realDynamicContext);
}
return executeSubProcess((StatefulKnowledgeSessionImpl) ksession, processId, parameters, processInstance, subProcessNodeInstance);
}
});
} else {
throw new IllegalArgumentException("Unsupported ksession: " + ksession == null ? "null" : ksession.getClass().getName());
}
}
use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.
the class MemoryLeakTest method createKnowledgeSessionStartProcessEtc.
private void createKnowledgeSessionStartProcessEtc(KieBase kbase) {
logger.info("session count=" + kbase.getKieSessions().size());
StatefulKnowledgeSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, getKnowledgeSessionConfiguration(), env);
addEventListenersToSession(ksession);
/**
* The following log line caused the memory leak.
* The specific (reverse-ordered) stack trace is the following:
*
* MemoryLeakTest.createKnowledgeSessionStartProcessEtc(KnowledgeBase) calls kbase.getKieSessions()
* ..
* KnowledgeBaseImpl.getStatefulKnowledgeSessions() line: 186
* StatefulKnowledgeSessionImpl.<init>(ReteooWorkingMemory, KnowledgeBase) line: 121
* ReteooStatefulSession(AbstractWorkingMemory).setKnowledgeRuntime(InternalKnowledgeRuntime) line: 1268
* ReteooStatefulSession(AbstractWorkingMemory).createProcessRuntime() line: 342
* ProcessRuntimeFactory.newProcessRuntime(AbstractWorkingMemory) line: 12
* ProcessRuntimeFactoryServiceImpl.newProcessRuntime(AbstractWorkingMemory) line: 1
* ProcessRuntimeFactoryServiceImpl.newProcessRuntime(AbstractWorkingMemory) line: 10
* ProcessRuntimeImpl.<init>(AbstractWorkingMemory) line: 84
* ProcessRuntimeImpl.initProcessEventListeners() line: 215
*
* And ProcessRuntimeImpl.initProcessEventListeners() is what adds a new listener
* to AbstractRuleBase.eventSupport.listeners via this line (235):
* kruntime.getKnowledgeBase().addEventListener(knowledgeBaseListener);
*
* The StatefulKnowledgeSessionImpl instance created in this .getStatefulKnowledgeSessions()
* method is obviously never disposed, which means that the listener is never removed.
* The listener then contains a link to a field (signalManager) of the ProcessRuntimeImpl,
* which contains a link to the StatefulKnowledgeSessionImpl instance created here. etc..
*/
logger.info("session count=" + kbase.getKieSessions().size());
TestWorkItemHandler handler = new TestWorkItemHandler();
ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
try {
// create process instance, insert into session and start process
Map<String, Object> processParams = new HashMap<String, Object>();
String[] fireballVarHolder = new String[1];
processParams.put("fireball", fireballVarHolder);
ProcessInstance processInstance = ksession.createProcessInstance(PROCESS_NAME, processParams);
ksession.insert(processInstance);
ksession.startProcessInstance(processInstance.getId());
// after the log line has been added, the DefaultProcessEventListener registered
// in the addEventListenersToSession() method no longer works?!?
ksession.fireAllRules();
// test process variables
String[] procVar = (String[]) ((WorkflowProcessInstance) processInstance).getVariable("fireball");
assertEquals("Rule task did NOT fire or complete.", "boom!", procVar[0]);
// complete task and process
Map<String, Object> results = new HashMap<String, Object>();
results.put("chaerg", new SerializableResult("zhrini", 302l, "F", "A", "T"));
ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), results);
assertNull(ksession.getProcessInstance(processInstance.getId()));
} finally {
// This should clean up all listeners, but doesn't -> see docs above
ksession.dispose();
}
}
use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.
the class IdentityProviderAwareProcessListenerTest method testUserNotSet.
@Test
public void testUserNotSet() {
final WorkflowProcessInstance processInstance = mock(WorkflowProcessInstance.class);
final HashMap<String, Object> metaData = new HashMap<>();
when(processInstance.getMetaData()).thenReturn(metaData);
final ProcessStartedEvent event = new ProcessStartedEventImpl(processInstance, mock(KieRuntime.class));
listener.beforeProcessStarted(event);
assertTrue(metaData.isEmpty());
verify(processInstance, never()).setVariable(anyString(), anyString());
}
use of org.jbpm.workflow.instance.WorkflowProcessInstance 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