Search in sources :

Example 11 with TimerInstance

use of org.jbpm.process.instance.timer.TimerInstance in project jbpm by kiegroup.

the class WorkflowProcessInstanceImpl method signalEvent.

@SuppressWarnings("unchecked")
public void signalEvent(String type, Object event) {
    logger.debug("Signal {} received with data {} in process instance {}", type, event, getId());
    synchronized (this) {
        if (getState() != ProcessInstance.STATE_ACTIVE) {
            return;
        }
        if ("timerTriggered".equals(type)) {
            TimerInstance timer = (TimerInstance) event;
            if (timer.getId() == slaTimerId) {
                handleSLAViolation();
                // no need to pass the event along as it was purely for SLA tracking
                return;
            }
        }
        if ("slaViolation".equals(type)) {
            handleSLAViolation();
            // no need to pass the event along as it was purely for SLA tracking
            return;
        }
        List<NodeInstance> currentView = new ArrayList<NodeInstance>(this.nodeInstances);
        try {
            this.activatingNodeIds = new ArrayList<String>();
            List<EventListener> listeners = eventListeners.get(type);
            if (listeners != null) {
                for (EventListener listener : listeners) {
                    listener.signalEvent(type, event);
                }
            }
            listeners = externalEventListeners.get(type);
            if (listeners != null) {
                for (EventListener listener : listeners) {
                    listener.signalEvent(type, event);
                }
            }
            for (Node node : getWorkflowProcess().getNodes()) {
                if (node instanceof EventNodeInterface) {
                    if (((EventNodeInterface) node).acceptsEvent(type, event, (e) -> resolveVariable(e))) {
                        if (node instanceof EventNode && ((EventNode) node).getFrom() == null) {
                            EventNodeInstance eventNodeInstance = (EventNodeInstance) getNodeInstance(node);
                            eventNodeInstance.signalEvent(type, event);
                        } else {
                            if (node instanceof EventSubProcessNode && ((resolveVariables(((EventSubProcessNode) node).getEvents()).contains(type)))) {
                                EventSubProcessNodeInstance eventNodeInstance = (EventSubProcessNodeInstance) getNodeInstance(node);
                                eventNodeInstance.signalEvent(type, event);
                            }
                            if (node instanceof DynamicNode && type.equals(((DynamicNode) node).getActivationEventName())) {
                                DynamicNodeInstance dynamicNodeInstance = (DynamicNodeInstance) getNodeInstance(node);
                                dynamicNodeInstance.signalEvent(type, event);
                            } else {
                                List<NodeInstance> nodeInstances = getNodeInstances(node.getId(), currentView);
                                if (nodeInstances != null && !nodeInstances.isEmpty()) {
                                    for (NodeInstance nodeInstance : nodeInstances) {
                                        ((EventNodeInstanceInterface) nodeInstance).signalEvent(type, event);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (((org.jbpm.workflow.core.WorkflowProcess) getWorkflowProcess()).isDynamic()) {
                for (Node node : getWorkflowProcess().getNodes()) {
                    if (type.equals(node.getName()) && node.getIncomingConnections().isEmpty()) {
                        NodeInstance nodeInstance = getNodeInstance(node);
                        if (event != null) {
                            Map<String, Object> dynamicParams = new HashMap<>();
                            if (event instanceof Map) {
                                dynamicParams.putAll((Map<String, Object>) event);
                            } else {
                                dynamicParams.put("Data", event);
                            }
                            ((org.jbpm.workflow.instance.NodeInstance) nodeInstance).setDynamicParameters(dynamicParams);
                        }
                        ((org.jbpm.workflow.instance.NodeInstance) nodeInstance).trigger(null, NodeImpl.CONNECTION_DEFAULT_TYPE);
                    }
                }
            }
        } finally {
            if (this.activatingNodeIds != null) {
                this.activatingNodeIds.clear();
                this.activatingNodeIds = null;
            }
        }
    }
}
Also used : DynamicNodeInstance(org.jbpm.workflow.instance.node.DynamicNodeInstance) TimerInstance(org.jbpm.process.instance.timer.TimerInstance) HashMap(java.util.HashMap) EventNodeInterface(org.jbpm.workflow.core.node.EventNodeInterface) EventSubProcessNode(org.jbpm.workflow.core.node.EventSubProcessNode) DynamicNode(org.jbpm.workflow.core.node.DynamicNode) AsyncEventNode(org.jbpm.workflow.core.node.AsyncEventNode) StateBasedNode(org.jbpm.workflow.core.node.StateBasedNode) EventSubProcessNode(org.jbpm.workflow.core.node.EventSubProcessNode) ActionNode(org.jbpm.workflow.core.node.ActionNode) EndNode(org.jbpm.workflow.core.node.EndNode) EventNode(org.jbpm.workflow.core.node.EventNode) Node(org.kie.api.definition.process.Node) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) EventSubProcessNodeInstance(org.jbpm.workflow.instance.node.EventSubProcessNodeInstance) AsyncEventNode(org.jbpm.workflow.core.node.AsyncEventNode) EventNode(org.jbpm.workflow.core.node.EventNode) EventNodeInstanceInterface(org.jbpm.workflow.instance.node.EventNodeInstanceInterface) DynamicNode(org.jbpm.workflow.core.node.DynamicNode) EventListener(org.kie.api.runtime.process.EventListener) EventSubProcessNodeInstance(org.jbpm.workflow.instance.node.EventSubProcessNodeInstance) DynamicNodeInstance(org.jbpm.workflow.instance.node.DynamicNodeInstance) EndNodeInstance(org.jbpm.workflow.instance.node.EndNodeInstance) NodeInstance(org.jbpm.workflow.instance.NodeInstance) EventNodeInstance(org.jbpm.workflow.instance.node.EventNodeInstance) CompositeNodeInstance(org.jbpm.workflow.instance.node.CompositeNodeInstance) EventNodeInstance(org.jbpm.workflow.instance.node.EventNodeInstance) WorkflowProcess(org.kie.api.definition.process.WorkflowProcess) Map(java.util.Map) HashMap(java.util.HashMap)

Example 12 with TimerInstance

use of org.jbpm.process.instance.timer.TimerInstance in project jbpm by kiegroup.

the class UpdateTimerCommand method rescheduleTimer.

protected TimerInstance rescheduleTimer(TimerInstance timer, TimerManager tm) {
    logger.debug("Found timer {} that is going to be canceled", timer);
    tm.cancelTimer(timer.getTimerId());
    logger.debug("Timer {} canceled successfully", timer);
    TimerInstance newTimer = new TimerInstance();
    if (delay != 0) {
        newTimer.setDelay(calculateDelay(delay, timer));
    }
    newTimer.setPeriod(period);
    newTimer.setRepeatLimit(repeatLimit);
    newTimer.setTimerId(timer.getTimerId());
    return newTimer;
}
Also used : TimerInstance(org.jbpm.process.instance.timer.TimerInstance)

Example 13 with TimerInstance

use of org.jbpm.process.instance.timer.TimerInstance in project jbpm by kiegroup.

the class IntermediateEventTest method testTimerBoundaryEventInterruptingOnTaskCancelTimer.

@Test
public void testTimerBoundaryEventInterruptingOnTaskCancelTimer() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-TimerBoundaryEventInterruptingOnTaskCancelTimer.bpmn2");
    ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    ProcessInstance processInstance = ksession.startProcess("TimerBoundaryEvent");
    assertProcessInstanceActive(processInstance);
    Collection<TimerInstance> timers = getTimerManager(ksession).getTimers();
    assertThat(timers.size()).isEqualTo(1);
    ksession = restoreSession(ksession, true);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    timers = getTimerManager(ksession).getTimers();
    assertThat(timers.size()).isEqualTo(1);
    ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null);
    ksession = restoreSession(ksession, true);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    timers = getTimerManager(ksession).getTimers();
    assertThat(timers).isNullOrEmpty();
    WorkItem workItem = handler.getWorkItem();
    if (workItem != null) {
        ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    }
    assertProcessInstanceFinished(processInstance, ksession);
}
Also used : TestWorkItemHandler(org.jbpm.bpmn2.objects.TestWorkItemHandler) TimerInstance(org.jbpm.process.instance.timer.TimerInstance) KieBase(org.kie.api.KieBase) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) WorkflowProcessInstance(org.kie.api.runtime.process.WorkflowProcessInstance) WorkItem(org.kie.api.runtime.process.WorkItem) Test(org.junit.Test)

Example 14 with TimerInstance

use of org.jbpm.process.instance.timer.TimerInstance in project jbpm by kiegroup.

the class SerializedTimerRollbackTest method testSerizliableTestsWithEngineRollback.

@Test
public void testSerizliableTestsWithEngineRollback() {
    try {
        createRuntimeManager("org/jbpm/test/functional/timer/HumanTaskWithBoundaryTimer.bpmn");
        RuntimeEngine runtimeEngine = getRuntimeEngine();
        KieSession ksession = runtimeEngine.getKieSession();
        logger.debug("Created knowledge session");
        TaskService taskService = runtimeEngine.getTaskService();
        logger.debug("Task service created");
        List<Long> committedProcessInstanceIds = new ArrayList<Long>();
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("test", "john");
                logger.debug("Creating process instance: {}", i);
                ProcessInstance pi = ksession.startProcess("PROCESS_1", params);
                committedProcessInstanceIds.add(pi.getId());
            } else {
                try {
                    Map<String, Object> params = new HashMap<String, Object>();
                    // set test variable to null so engine will rollback
                    params.put("test", null);
                    logger.debug("Creating process instance: {}", i);
                    ksession.startProcess("PROCESS_1", params);
                } catch (Exception e) {
                    logger.debug("Process rolled back");
                }
            }
        }
        Connection c = getDs().getConnection();
        Statement st = c.createStatement();
        ResultSet rs = st.executeQuery("select rulesbytearray from sessioninfo");
        rs.next();
        Blob b = rs.getBlob("rulesbytearray");
        assertNotNull(b);
        KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        ProtobufMarshaller marshaller = new ProtobufMarshaller(builder.newKieBase(), new MarshallingConfigurationImpl());
        StatefulKnowledgeSession session = marshaller.unmarshall(b.getBinaryStream());
        assertNotNull(session);
        TimerManager timerManager = ((InternalProcessRuntime) ((InternalKnowledgeRuntime) session).getProcessRuntime()).getTimerManager();
        assertNotNull(timerManager);
        Collection<TimerInstance> timers = timerManager.getTimers();
        assertNotNull(timers);
        assertEquals(5, timers.size());
        for (TimerInstance timerInstance : timers) {
            assertTrue(committedProcessInstanceIds.contains(timerInstance.getProcessInstanceId()));
            ksession.abortProcessInstance(timerInstance.getProcessInstanceId());
        }
        List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
        assertEquals(0, tasks.size());
    } catch (Exception e) {
        e.printStackTrace();
        fail("Exception thrown");
    }
}
Also used : ProtobufMarshaller(org.drools.core.marshalling.impl.ProtobufMarshaller) HashMap(java.util.HashMap) TimerInstance(org.jbpm.process.instance.timer.TimerInstance) ArrayList(java.util.ArrayList) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) ResultSet(java.sql.ResultSet) KieSession(org.kie.api.runtime.KieSession) MarshallingConfigurationImpl(org.drools.core.marshalling.impl.MarshallingConfigurationImpl) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) Blob(java.sql.Blob) TaskService(org.kie.api.task.TaskService) Statement(java.sql.Statement) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) Connection(java.sql.Connection) TimerManager(org.jbpm.process.instance.timer.TimerManager) TaskSummary(org.kie.api.task.model.TaskSummary) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) InternalProcessRuntime(org.jbpm.process.instance.InternalProcessRuntime) Test(org.junit.Test)

Example 15 with TimerInstance

use of org.jbpm.process.instance.timer.TimerInstance in project jbpm by kiegroup.

the class MigrationManager method cancelActiveTimersBeforeMigration.

protected Map<Long, List<TimerInstance>> cancelActiveTimersBeforeMigration(RuntimeManager manager) {
    RuntimeEngine engineBefore = manager.getRuntimeEngine(ProcessInstanceIdContext.get(migrationSpec.getProcessInstanceId()));
    try {
        Map<Long, List<TimerInstance>> timerMigrated = engineBefore.getKieSession().execute(new ExecutableCommand<Map<Long, List<TimerInstance>>>() {

            private static final long serialVersionUID = 7144271692067781976L;

            @Override
            public Map<Long, List<TimerInstance>> execute(Context context) {
                Map<Long, List<TimerInstance>> result = new LinkedHashMap<>();
                KieSession kieSession = ((RegistryContext) context).lookup(KieSession.class);
                TimerManager timerManager = getTimerManager(kieSession);
                WorkflowProcessInstanceImpl processInstance = (WorkflowProcessInstanceImpl) kieSession.getProcessInstance(migrationSpec.getProcessInstanceId());
                Collection<org.jbpm.workflow.instance.NodeInstance> activeInstances = processInstance.getNodeInstances(true);
                for (org.jbpm.workflow.instance.NodeInstance active : activeInstances) {
                    if (active instanceof TimerNodeInstance) {
                        TimerInstance timerInstance = timerManager.getTimerMap().get(((TimerNodeInstance) active).getTimerId());
                        timerManager.cancelTimer(timerInstance.getId());
                        result.put(active.getId(), Arrays.asList(timerInstance));
                    } else if (active instanceof StateBasedNodeInstance) {
                        List<Long> timers = ((StateBasedNodeInstance) active).getTimerInstances();
                        if (timers != null && !timers.isEmpty()) {
                            List<TimerInstance> collected = new ArrayList<>();
                            for (Long timerId : timers) {
                                TimerInstance timerInstance = timerManager.getTimerMap().get(timerId);
                                timerManager.cancelTimer(timerInstance.getId());
                                collected.add(timerInstance);
                            }
                            result.put(active.getId(), collected);
                        }
                    }
                }
                return result;
            }
        });
        return timerMigrated;
    } finally {
        manager.disposeRuntimeEngine(engineBefore);
    }
}
Also used : TimerInstance(org.jbpm.process.instance.timer.TimerInstance) WorkflowProcessInstanceImpl(org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) 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) StateBasedNodeInstance(org.jbpm.workflow.instance.node.StateBasedNodeInstance) TimerManager(org.jbpm.process.instance.timer.TimerManager) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TimerNodeInstance(org.jbpm.workflow.instance.node.TimerNodeInstance) StateBasedNodeInstance(org.jbpm.workflow.instance.node.StateBasedNodeInstance) NodeInstance(org.kie.api.runtime.process.NodeInstance) HumanTaskNodeInstance(org.jbpm.workflow.instance.node.HumanTaskNodeInstance) TimerNodeInstance(org.jbpm.workflow.instance.node.TimerNodeInstance)

Aggregations

TimerInstance (org.jbpm.process.instance.timer.TimerInstance)16 TimerManager (org.jbpm.process.instance.timer.TimerManager)7 KieSession (org.kie.api.runtime.KieSession)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)4 InternalProcessRuntime (org.jbpm.process.instance.InternalProcessRuntime)4 WorkflowProcessInstanceImpl (org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl)4 Test (org.junit.Test)4 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)4 Date (java.util.Date)3 RegistryContext (org.drools.core.command.impl.RegistryContext)3 BusinessCalendar (org.jbpm.process.core.timer.BusinessCalendar)3 StateBasedNodeInstance (org.jbpm.workflow.instance.node.StateBasedNodeInstance)3 TimerNodeInstance (org.jbpm.workflow.instance.node.TimerNodeInstance)3 NodeInstance (org.kie.api.runtime.process.NodeInstance)3 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)3 Blob (java.sql.Blob)2 Connection (java.sql.Connection)2 ResultSet (java.sql.ResultSet)2 Statement (java.sql.Statement)2