use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.
the class DynamicUtils method internalAddDynamicWorkItem.
private static void internalAddDynamicWorkItem(final WorkflowProcessInstance processInstance, final DynamicNodeInstance dynamicContext, KieRuntime ksession, String workItemName, Map<String, Object> parameters) {
final WorkItemImpl workItem = new WorkItemImpl();
workItem.setState(WorkItem.ACTIVE);
workItem.setProcessInstanceId(processInstance.getId());
workItem.setDeploymentId((String) ksession.getEnvironment().get(EnvironmentName.DEPLOYMENT_ID));
workItem.setName(workItemName);
workItem.setParameters(parameters);
for (Map.Entry<String, Object> entry : workItem.getParameters().entrySet()) {
if (entry.getValue() instanceof String) {
String s = (String) entry.getValue();
Object variableValue = null;
Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(s);
while (matcher.find()) {
String paramName = matcher.group(1);
variableValue = processInstance.getVariable(paramName);
if (variableValue == null) {
try {
variableValue = MVELSafeHelper.getEvaluator().eval(paramName, new ProcessInstanceResolverFactory(processInstance));
} catch (Throwable t) {
logger.error("Could not find variable scope for variable {}", paramName);
logger.error("when trying to replace variable in string for Dynamic Work Item {}", workItemName);
logger.error("Continuing without setting parameter.");
}
}
}
if (variableValue != null) {
workItem.setParameter(entry.getKey(), variableValue);
}
}
}
final WorkItemNodeInstance workItemNodeInstance = new WorkItemNodeInstance();
workItemNodeInstance.internalSetWorkItem(workItem);
workItemNodeInstance.setMetaData("NodeType", workItemName);
workItem.setNodeInstanceId(workItemNodeInstance.getId());
if (ksession instanceof StatefulKnowledgeSessionImpl) {
workItemNodeInstance.setProcessInstance(processInstance);
workItemNodeInstance.setNodeInstanceContainer(dynamicContext == null ? processInstance : dynamicContext);
workItemNodeInstance.addEventListeners();
executeWorkItem((StatefulKnowledgeSessionImpl) ksession, workItem, workItemNodeInstance);
} else if (ksession instanceof CommandBasedStatefulKnowledgeSession) {
ExecutableRunner runner = ((CommandBasedStatefulKnowledgeSession) ksession).getRunner();
runner.execute(new ExecutableCommand<Void>() {
private static final long serialVersionUID = 5L;
public Void execute(Context context) {
StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) ((RegistryContext) context).lookup(KieSession.class);
WorkflowProcessInstance realProcessInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstance.getId());
workItemNodeInstance.setProcessInstance(realProcessInstance);
if (dynamicContext == null) {
workItemNodeInstance.setNodeInstanceContainer(realProcessInstance);
} else {
DynamicNodeInstance realDynamicContext = findDynamicContext(realProcessInstance, dynamicContext.getUniqueId());
workItemNodeInstance.setNodeInstanceContainer(realDynamicContext);
}
workItemNodeInstance.addEventListeners();
executeWorkItem((StatefulKnowledgeSessionImpl) ksession, workItem, workItemNodeInstance);
return null;
}
});
} 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 DynamicUtils method addDynamicWorkItem.
public static void addDynamicWorkItem(final DynamicNodeInstance dynamicContext, KieRuntime ksession, String workItemName, Map<String, Object> parameters) {
final WorkflowProcessInstance processInstance = dynamicContext.getProcessInstance();
internalAddDynamicWorkItem(processInstance, dynamicContext, ksession, workItemName, parameters);
}
use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.
the class IdentityProviderAwareProcessListenerTest method testSetUser.
@Test
public void testSetUser() {
final IdentityProvider identityProvider = mock(IdentityProvider.class);
final String userId = "userId";
when(identityProvider.getName()).thenReturn(userId);
when(environment.get("IdentityProvider")).thenReturn(identityProvider);
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);
assertEquals(userId, metaData.get("OwnerId"));
verify(processInstance).setVariable("initiator", userId);
}
use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jbpm by kiegroup.
the class GlobalTimerServiceBaseTest method testTimerFailureAndRetrigger.
@Test(timeout = 20000)
public void testTimerFailureAndRetrigger() throws Exception {
NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("Timer_1m", 3);
final List<Long> timerExporations = new ArrayList<Long>();
ProcessEventListener listener = new DefaultProcessEventListener() {
@Override
public void afterNodeTriggered(ProcessNodeTriggeredEvent event) {
if (event.getNodeInstance().getNodeName().equals("Timer_1m")) {
timerExporations.add(event.getNodeInstance().getId());
}
}
};
environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).addAsset(ResourceFactory.newClassPathResource("org/jbpm/test/functional/timer/helloretrigger.bpmn2"), ResourceType.BPMN2).schedulerService(globalScheduler).registerableItemsFactory(new TestRegisterableItemsFactory(listener, countDownListener)).get();
manager = getManager(environment, false);
RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get());
KieSession ksession = runtime.getKieSession();
Map<String, Object> params = new HashMap<>();
ProcessInstance pi = ksession.startProcess("rescheduletimer.helloretrigger", params);
assertEquals("Process instance should be active", ProcessInstance.STATE_ACTIVE, pi.getState());
manager.disposeRuntimeEngine(runtime);
final long processInstanceId = pi.getId();
// let the timer (every 2 sec) fire three times as third will fail on gateway
countDownListener.waitTillCompleted(8000);
assertEquals("There should be only 3 nodes as there third is failing", 3, timerExporations.size());
runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
ksession = runtime.getKieSession();
ksession.execute(new ExecutableCommand<Void>() {
@Override
public Void execute(Context context) {
KieSession ksession = ((RegistryContext) context).lookup(KieSession.class);
ProcessInstance pi = (ProcessInstance) ksession.getProcessInstance(processInstanceId);
((WorkflowProcessInstance) pi).setVariable("fixed", true);
return null;
}
});
manager.disposeRuntimeEngine(runtime);
countDownListener.reset(1);
countDownListener.waitTillCompleted(5000);
assertEquals("There should be 3 expirations as the failing one should finally proceed", 3, timerExporations.size());
try {
runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId));
ksession = runtime.getKieSession();
pi = ksession.getProcessInstance(processInstanceId);
assertNull(pi);
} catch (SessionNotFoundException e) {
// expected for PerProcessInstanceManagers since process instance is completed
}
((AbstractRuntimeManager) manager).close(true);
}
use of org.jbpm.workflow.instance.WorkflowProcessInstance in project jBPM5-Developer-Guide by Salaboy.
the class EmergencyBedRequestV2Test method testHappyPath.
@Test
public void testHappyPath() {
//prepare input parameters for the process:
String date = DateFormat.getDateInstance().format(new Date());
String entity = "911";
String patientAge = "21";
String patientGender = "F";
String patientStatus = "Critical";
Map<String, Object> inputVariables = new HashMap<String, Object>();
inputVariables.put("bedrequest_date", date);
inputVariables.put("bedrequest_entity", entity);
inputVariables.put("bedrequest_patientage", patientAge);
inputVariables.put("bedrequest_patientgender", patientGender);
inputVariables.put("bedrequest_patientstatus", patientStatus);
//Start the process using its ID and pass the input variables
WorkflowProcessInstance processInstance = (WorkflowProcessInstance) session.startProcess("hospitalEmergencyV2", inputVariables);
//************** Coordinate Staff **************//
//The process must be in the 'Coordinate Staff' task. Let's check the
//input parameters received by the handler associated to that task.
Assert.assertEquals("Coordinate Staff", processInstance.getNodeInstances().iterator().next().getNodeName());
Assert.assertEquals(date, mockWorkItemHandler.getInputParameter("bedrequest_date"));
Assert.assertEquals(entity, mockWorkItemHandler.getInputParameter("bedrequest_entity"));
Assert.assertEquals(patientAge, mockWorkItemHandler.getInputParameter("bedrequest_patientage"));
Assert.assertEquals(patientGender, mockWorkItemHandler.getInputParameter("bedrequest_patientgender"));
Assert.assertEquals(patientStatus, mockWorkItemHandler.getInputParameter("bedrequest_patientstatus"));
//let's complete the task emulating the results of this task.
Map<String, Object> taskResults = new HashMap<String, Object>();
taskResults.put("checkinresults_gate", "3C");
mockWorkItemHandler.completeWorkItem(taskResults);
//************** Notify Gate to Ambulance **************//
//Now we are at 'Notify Gate to Ambulance' task. Let's check that the input
//parameters configured for this tasks arrived as expected.
Assert.assertEquals("Notify Gate to Ambulance", processInstance.getNodeInstances().iterator().next().getNodeName());
Assert.assertEquals("3C", mockWorkItemHandler.getInputParameter("checkinresults_gate"));
//let's complete the task with a mocked resource
taskResults = new HashMap<String, Object>();
taskResults.put("checkinresults_notified", "true");
mockWorkItemHandler.completeWorkItem(taskResults);
//************** Check In Patient **************//
//In 'Check In Patient' task we are expecting a 'checkinresults_notified'
//parameter containing the value returned by the last task
Assert.assertEquals("Check In Patient", processInstance.getNodeInstances().iterator().next().getNodeName());
Assert.assertEquals("true", mockWorkItemHandler.getInputParameter("checkinresults_notified"));
//let's complete the task passing the mocked results
taskResults = new HashMap<String, Object>();
String checkinDate = DateFormat.getTimeInstance().format(new Date());
taskResults.put("checkinresults_checkedin", "true");
taskResults.put("checkinresults_time", checkinDate);
mockWorkItemHandler.completeWorkItem(taskResults);
//The process should be completed now. Let's check the 2 output
//parameters of the last task: they should be mapped to process variables.
Assert.assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
Assert.assertEquals("true", processInstance.getVariable("checkinresults_checkedin"));
Assert.assertEquals(checkinDate, processInstance.getVariable("checkinresults_time"));
}
Aggregations