Search in sources :

Example 11 with WorkflowProcessInstance

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());
    }
}
Also used : RegistryContext(org.drools.core.command.impl.RegistryContext) Context(org.kie.api.runtime.Context) Matcher(java.util.regex.Matcher) CommandBasedStatefulKnowledgeSession(org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) CommandBasedStatefulKnowledgeSession(org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession) ExecutableRunner(org.kie.api.runtime.ExecutableRunner) ProcessInstanceResolverFactory(org.jbpm.workflow.instance.impl.ProcessInstanceResolverFactory) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) WorkItemImpl(org.drools.core.process.instance.impl.WorkItemImpl) ExecutableCommand(org.drools.core.command.impl.ExecutableCommand) KieSession(org.kie.api.runtime.KieSession) Map(java.util.Map) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance)

Example 12 with WorkflowProcessInstance

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);
}
Also used : WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance)

Example 13 with WorkflowProcessInstance

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);
}
Also used : HashMap(java.util.HashMap) KieRuntime(org.kie.api.runtime.KieRuntime) ProcessStartedEvent(org.kie.api.event.process.ProcessStartedEvent) IdentityProvider(org.kie.internal.identity.IdentityProvider) ProcessStartedEventImpl(org.drools.core.event.ProcessStartedEventImpl) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) Test(org.junit.Test)

Example 14 with WorkflowProcessInstance

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);
}
Also used : InitialContext(javax.naming.InitialContext) RegistryContext(org.drools.core.command.impl.RegistryContext) Context(org.kie.api.runtime.Context) ProcessInstanceIdContext(org.kie.internal.runtime.manager.context.ProcessInstanceIdContext) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) HashMap(java.util.HashMap) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) AbstractRuntimeManager(org.jbpm.runtime.manager.impl.AbstractRuntimeManager) ArrayList(java.util.ArrayList) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) ProcessNodeTriggeredEvent(org.kie.api.event.process.ProcessNodeTriggeredEvent) KieSession(org.kie.api.runtime.KieSession) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) SessionNotFoundException(org.kie.internal.runtime.manager.SessionNotFoundException) Test(org.junit.Test)

Example 15 with WorkflowProcessInstance

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"));
}
Also used : HashMap(java.util.HashMap) Date(java.util.Date) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance) Test(org.junit.Test)

Aggregations

WorkflowProcessInstance (org.jbpm.workflow.instance.WorkflowProcessInstance)24 HashMap (java.util.HashMap)16 Test (org.junit.Test)15 KieSession (org.kie.api.runtime.KieSession)8 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)8 Date (java.util.Date)6 RegistryContext (org.drools.core.command.impl.RegistryContext)5 Context (org.kie.api.runtime.Context)5 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)5 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 ExecutableCommand (org.drools.core.command.impl.ExecutableCommand)3 NodeInstance (org.kie.api.runtime.process.NodeInstance)3 Matcher (java.util.regex.Matcher)2 CommandBasedStatefulKnowledgeSession (org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession)2 ProcessStartedEventImpl (org.drools.core.event.ProcessStartedEventImpl)2 StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)2 SignallingTaskHandlerDecorator (org.jbpm.bpmn2.handler.SignallingTaskHandlerDecorator)2 SystemOutWorkItemHandler (org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler)2 AbstractRuntimeManager (org.jbpm.runtime.manager.impl.AbstractRuntimeManager)2