Search in sources :

Example 1 with InternalKnowledgeRuntime

use of org.drools.core.common.InternalKnowledgeRuntime in project jbpm by kiegroup.

the class IntermediateEventTest method testEventTypesLifeCycle.

@Test
@RequirePersistence
public void testEventTypesLifeCycle() throws Exception {
    // JBPM-4246
    KieBase kbase = createKnowledgeBase("BPMN2-IntermediateCatchSignalBetweenUserTasks.bpmn2");
    EntityManagerFactory separateEmf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa");
    Environment env = createEnvironment(separateEmf);
    ksession = createKnowledgeSession(kbase, null, env);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new DoNothingWorkItemHandler());
    ksession.startProcess("BPMN2-IntermediateCatchSignalBetweenUserTasks");
    int signalListSize = ksession.execute(new ExecutableCommand<Integer>() {

        public Integer execute(Context context) {
            SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) ksession).getRunner();
            InternalKnowledgeRuntime kruntime = (InternalKnowledgeRuntime) commandService.getKieSession();
            ProcessPersistenceContextManager contextManager = (ProcessPersistenceContextManager) kruntime.getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
            ProcessPersistenceContext pcontext = contextManager.getProcessPersistenceContext();
            List<Long> processInstancesToSignalList = pcontext.getProcessInstancesWaitingForEvent("MySignal");
            return processInstancesToSignalList.size();
        }
    });
    // Process instance is not waiting for signal
    assertThat(signalListSize).isEqualTo(0);
    ksession.getWorkItemManager().completeWorkItem(1, null);
    signalListSize = ksession.execute(new ExecutableCommand<Integer>() {

        public Integer execute(Context context) {
            SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) ksession).getRunner();
            InternalKnowledgeRuntime kruntime = (InternalKnowledgeRuntime) commandService.getKieSession();
            ProcessPersistenceContextManager contextManager = (ProcessPersistenceContextManager) kruntime.getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
            ProcessPersistenceContext pcontext = contextManager.getProcessPersistenceContext();
            List<Long> processInstancesToSignalList = pcontext.getProcessInstancesWaitingForEvent("MySignal");
            return processInstancesToSignalList.size();
        }
    });
    // Process instance is waiting for signal now
    assertThat(signalListSize).isEqualTo(1);
    ksession.signalEvent("MySignal", null);
    signalListSize = ksession.execute(new ExecutableCommand<Integer>() {

        public Integer execute(Context context) {
            SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) ksession).getRunner();
            InternalKnowledgeRuntime kruntime = (InternalKnowledgeRuntime) commandService.getKieSession();
            ProcessPersistenceContextManager contextManager = (ProcessPersistenceContextManager) kruntime.getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
            ProcessPersistenceContext pcontext = contextManager.getProcessPersistenceContext();
            List<Long> processInstancesToSignalList = pcontext.getProcessInstancesWaitingForEvent("MySignal");
            return processInstancesToSignalList.size();
        }
    });
    // Process instance is not waiting for signal
    assertThat(signalListSize).isEqualTo(0);
    ksession.getWorkItemManager().completeWorkItem(2, null);
    ksession.dispose();
    ksession = null;
    separateEmf.close();
}
Also used : RegistryContext(org.drools.core.command.impl.RegistryContext) ProcessPersistenceContext(org.jbpm.persistence.api.ProcessPersistenceContext) Context(org.kie.api.runtime.Context) DoNothingWorkItemHandler(org.jbpm.process.instance.impl.demo.DoNothingWorkItemHandler) SingleSessionCommandService(org.drools.core.command.SingleSessionCommandService) CommandBasedStatefulKnowledgeSession(org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession) ProcessPersistenceContext(org.jbpm.persistence.api.ProcessPersistenceContext) InternalKnowledgeRuntime(org.drools.core.common.InternalKnowledgeRuntime) KieBase(org.kie.api.KieBase) EntityManagerFactory(javax.persistence.EntityManagerFactory) Environment(org.kie.api.runtime.Environment) ExecutableCommand(org.drools.core.command.impl.ExecutableCommand) List(java.util.List) ArrayList(java.util.ArrayList) ProcessPersistenceContextManager(org.jbpm.persistence.api.ProcessPersistenceContextManager) Test(org.junit.Test) RequirePersistence(org.jbpm.bpmn2.test.RequirePersistence)

Example 2 with InternalKnowledgeRuntime

use of org.drools.core.common.InternalKnowledgeRuntime in project jbpm by kiegroup.

the class SplitInstance method executeStrategy.

protected void executeStrategy(Split split, String type) {
    // TODO make different strategies for each type
    switch(split.getType()) {
        case Split.TYPE_AND:
            triggerCompleted(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE, true);
            break;
        case Split.TYPE_XOR:
            List<Connection> outgoing = split.getDefaultOutgoingConnections();
            int priority = Integer.MAX_VALUE;
            Connection selected = null;
            for (final Iterator<Connection> iterator = outgoing.iterator(); iterator.hasNext(); ) {
                final Connection connection = (Connection) iterator.next();
                ConstraintEvaluator constraint = (ConstraintEvaluator) split.getConstraint(connection);
                if (constraint != null && constraint.getPriority() < priority && !constraint.isDefault()) {
                    try {
                        if (constraint.evaluate(this, connection, constraint)) {
                            selected = connection;
                            priority = constraint.getPriority();
                        }
                    } catch (RuntimeException e) {
                        throw new RuntimeException("Exception when trying to evaluate constraint " + constraint.getName() + " in split " + split.getName(), e);
                    }
                }
            }
            ((NodeInstanceContainer) getNodeInstanceContainer()).removeNodeInstance(this);
            if (selected == null) {
                for (final Iterator<Connection> iterator = outgoing.iterator(); iterator.hasNext(); ) {
                    final Connection connection = (Connection) iterator.next();
                    if (split.isDefault(connection)) {
                        selected = connection;
                        break;
                    }
                }
            }
            if (selected == null) {
                throw new IllegalArgumentException("XOR split could not find at least one valid outgoing connection for split " + getSplit().getName());
            }
            if (!hasLoop(selected.getTo(), split)) {
                setLevel(1);
                ((NodeInstanceContainer) getNodeInstanceContainer()).setCurrentLevel(1);
            }
            triggerConnection(selected);
            break;
        case Split.TYPE_OR:
            ((NodeInstanceContainer) getNodeInstanceContainer()).removeNodeInstance(this);
            outgoing = split.getDefaultOutgoingConnections();
            boolean found = false;
            List<NodeInstanceTrigger> nodeInstances = new ArrayList<NodeInstanceTrigger>();
            List<Connection> outgoingCopy = new ArrayList<Connection>(outgoing);
            while (!outgoingCopy.isEmpty()) {
                priority = Integer.MAX_VALUE;
                Connection selectedConnection = null;
                ConstraintEvaluator selectedConstraint = null;
                for (final Iterator<Connection> iterator = outgoingCopy.iterator(); iterator.hasNext(); ) {
                    final Connection connection = (Connection) iterator.next();
                    ConstraintEvaluator constraint = (ConstraintEvaluator) split.getConstraint(connection);
                    if (constraint != null && constraint.getPriority() < priority && !constraint.isDefault()) {
                        priority = constraint.getPriority();
                        selectedConnection = connection;
                        selectedConstraint = constraint;
                    }
                }
                if (selectedConstraint == null) {
                    break;
                }
                if (selectedConstraint.evaluate(this, selectedConnection, selectedConstraint)) {
                    nodeInstances.add(new NodeInstanceTrigger(followConnection(selectedConnection), selectedConnection.getToType()));
                    found = true;
                }
                outgoingCopy.remove(selectedConnection);
            }
            for (NodeInstanceTrigger nodeInstance : nodeInstances) {
                // stop if this process instance has been aborted / completed
                if (getProcessInstance().getState() != ProcessInstance.STATE_ACTIVE) {
                    return;
                }
                triggerNodeInstance(nodeInstance.getNodeInstance(), nodeInstance.getToType());
            }
            if (!found) {
                for (final Iterator<Connection> iterator = outgoing.iterator(); iterator.hasNext(); ) {
                    final Connection connection = (Connection) iterator.next();
                    ConstraintEvaluator constraint = (ConstraintEvaluator) split.getConstraint(connection);
                    if (constraint != null && constraint.isDefault() || split.isDefault(connection)) {
                        triggerConnection(connection);
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {
                throw new IllegalArgumentException("OR split could not find at least one valid outgoing connection for split " + getSplit().getName());
            }
            break;
        case Split.TYPE_XAND:
            ((org.jbpm.workflow.instance.NodeInstanceContainer) getNodeInstanceContainer()).removeNodeInstance(this);
            Node node = getNode();
            List<Connection> connections = null;
            if (node != null) {
                connections = node.getOutgoingConnections(type);
            }
            if (connections == null || connections.isEmpty()) {
                ((org.jbpm.workflow.instance.NodeInstanceContainer) getNodeInstanceContainer()).nodeInstanceCompleted(this, type);
            } else {
                ExclusiveGroupInstance groupInstance = new ExclusiveGroupInstance();
                org.kie.api.runtime.process.NodeInstanceContainer parent = getNodeInstanceContainer();
                if (parent instanceof ContextInstanceContainer) {
                    ((ContextInstanceContainer) parent).addContextInstance(ExclusiveGroup.EXCLUSIVE_GROUP, groupInstance);
                } else {
                    throw new IllegalArgumentException("An Exclusive AND is only possible if the parent is a context instance container");
                }
                Map<org.jbpm.workflow.instance.NodeInstance, String> nodeInstancesMap = new HashMap<org.jbpm.workflow.instance.NodeInstance, String>();
                for (Connection connection : connections) {
                    nodeInstancesMap.put(followConnection(connection), connection.getToType());
                }
                for (NodeInstance nodeInstance : nodeInstancesMap.keySet()) {
                    groupInstance.addNodeInstance(nodeInstance);
                }
                for (Map.Entry<org.jbpm.workflow.instance.NodeInstance, String> entry : nodeInstancesMap.entrySet()) {
                    // stop if this process instance has been aborted / completed
                    if (getProcessInstance().getState() != ProcessInstance.STATE_ACTIVE) {
                        return;
                    }
                    boolean hidden = false;
                    if (getNode().getMetaData().get("hidden") != null) {
                        hidden = true;
                    }
                    InternalKnowledgeRuntime kruntime = getProcessInstance().getKnowledgeRuntime();
                    if (!hidden) {
                        ((InternalProcessRuntime) kruntime.getProcessRuntime()).getProcessEventSupport().fireBeforeNodeLeft(this, kruntime);
                    }
                    ((org.jbpm.workflow.instance.NodeInstance) entry.getKey()).trigger(this, entry.getValue());
                    if (!hidden) {
                        ((InternalProcessRuntime) kruntime.getProcessRuntime()).getProcessEventSupport().fireAfterNodeLeft(this, kruntime);
                    }
                }
            }
            break;
        default:
            throw new IllegalArgumentException("Illegal split type " + split.getType());
    }
}
Also used : NodeInstanceContainer(org.jbpm.workflow.instance.NodeInstanceContainer) HashMap(java.util.HashMap) Node(org.kie.api.definition.process.Node) ArrayList(java.util.ArrayList) ConstraintEvaluator(org.jbpm.process.instance.impl.ConstraintEvaluator) InternalKnowledgeRuntime(org.drools.core.common.InternalKnowledgeRuntime) WorkflowRuntimeException(org.jbpm.workflow.instance.WorkflowRuntimeException) ContextInstanceContainer(org.jbpm.process.instance.ContextInstanceContainer) ExclusiveGroupInstance(org.jbpm.process.instance.context.exclusive.ExclusiveGroupInstance) Connection(org.kie.api.definition.process.Connection) NodeInstance(org.kie.api.runtime.process.NodeInstance) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with InternalKnowledgeRuntime

use of org.drools.core.common.InternalKnowledgeRuntime in project jbpm by kiegroup.

the class SubProcessNodeInstance method cancel.

public void cancel() {
    super.cancel();
    if (getSubProcessNode() == null || !getSubProcessNode().isIndependent()) {
        ProcessInstance processInstance = null;
        InternalKnowledgeRuntime kruntime = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime();
        RuntimeManager manager = (RuntimeManager) kruntime.getEnvironment().get(EnvironmentName.RUNTIME_MANAGER);
        if (manager != null) {
            try {
                org.kie.api.runtime.manager.Context<?> context = ProcessInstanceIdContext.get(processInstanceId);
                String caseId = (String) kruntime.getEnvironment().get(EnvironmentName.CASE_ID);
                if (caseId != null) {
                    context = CaseContext.get(caseId);
                }
                RuntimeEngine runtime = manager.getRuntimeEngine(context);
                KieRuntime managedkruntime = (KieRuntime) runtime.getKieSession();
                processInstance = (ProcessInstance) managedkruntime.getProcessInstance(processInstanceId);
            } catch (SessionNotFoundException e) {
            // in case no session is found for parent process let's skip signal for process instance completion
            }
        } else {
            processInstance = (ProcessInstance) kruntime.getProcessInstance(processInstanceId);
        }
        if (processInstance != null) {
            processInstance.setState(ProcessInstance.STATE_ABORTED);
        }
    }
}
Also used : InternalKnowledgeRuntime(org.drools.core.common.InternalKnowledgeRuntime) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) KieRuntime(org.kie.api.runtime.KieRuntime) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) ProcessInstance(org.jbpm.process.instance.ProcessInstance) SessionNotFoundException(org.kie.internal.runtime.manager.SessionNotFoundException)

Example 4 with InternalKnowledgeRuntime

use of org.drools.core.common.InternalKnowledgeRuntime in project jbpm by kiegroup.

the class WorkflowProcessInstanceImpl method configureSLATimer.

public TimerInstance configureSLATimer(String slaDueDateExpression) {
    // setup SLA if provided
    slaDueDateExpression = resolveVariable(slaDueDateExpression);
    if (slaDueDateExpression == null || slaDueDateExpression.trim().isEmpty()) {
        logger.debug("Sla due date expression resolved to no value '{}'", slaDueDateExpression);
        return null;
    }
    logger.debug("SLA due date is set to {}", slaDueDateExpression);
    InternalKnowledgeRuntime kruntime = getKnowledgeRuntime();
    long duration = -1;
    if (kruntime != null && kruntime.getEnvironment().get("jbpm.business.calendar") != null) {
        BusinessCalendar businessCalendar = (BusinessCalendar) kruntime.getEnvironment().get("jbpm.business.calendar");
        duration = businessCalendar.calculateBusinessTimeAsDuration(slaDueDateExpression);
    } else {
        duration = DateTimeUtils.parseDuration(slaDueDateExpression);
    }
    TimerInstance timerInstance = new TimerInstance();
    timerInstance.setId(-1);
    timerInstance.setDelay(duration);
    timerInstance.setPeriod(0);
    if (useTimerSLATracking()) {
        ((InternalProcessRuntime) kruntime.getProcessRuntime()).getTimerManager().registerTimer(timerInstance, this);
    }
    return timerInstance;
}
Also used : InternalKnowledgeRuntime(org.drools.core.common.InternalKnowledgeRuntime) TimerInstance(org.jbpm.process.instance.timer.TimerInstance) BusinessCalendar(org.jbpm.process.core.timer.BusinessCalendar)

Example 5 with InternalKnowledgeRuntime

use of org.drools.core.common.InternalKnowledgeRuntime in project jbpm by kiegroup.

the class NodeInstanceImpl method triggerNodeInstance.

protected void triggerNodeInstance(org.jbpm.workflow.instance.NodeInstance nodeInstance, String type) {
    boolean hidden = false;
    if (getNode().getMetaData().get("hidden") != null) {
        hidden = true;
    }
    InternalKnowledgeRuntime kruntime = getProcessInstance().getKnowledgeRuntime();
    if (!hidden) {
        ((InternalProcessRuntime) kruntime.getProcessRuntime()).getProcessEventSupport().fireBeforeNodeLeft(this, kruntime);
    }
    // trigger next node
    nodeInstance.trigger(this, type);
    Collection<Connection> outgoing = getNode().getOutgoingConnections(type);
    for (Connection conn : outgoing) {
        if (conn.getTo().getId() == nodeInstance.getNodeId()) {
            this.metaData.put("OutgoingConnection", conn.getMetaData().get("UniqueId"));
            break;
        }
    }
    if (!hidden) {
        ((InternalProcessRuntime) kruntime.getProcessRuntime()).getProcessEventSupport().fireAfterNodeLeft(this, kruntime);
    }
}
Also used : InternalKnowledgeRuntime(org.drools.core.common.InternalKnowledgeRuntime) Connection(org.kie.api.definition.process.Connection)

Aggregations

InternalKnowledgeRuntime (org.drools.core.common.InternalKnowledgeRuntime)18 ArrayList (java.util.ArrayList)4 Connection (org.kie.api.definition.process.Connection)4 NodeInstance (org.kie.api.runtime.process.NodeInstance)4 HashMap (java.util.HashMap)3 CompositeNodeInstance (org.jbpm.workflow.instance.node.CompositeNodeInstance)3 Node (org.kie.api.definition.process.Node)3 Map (java.util.Map)2 ExecutableCommand (org.drools.core.command.impl.ExecutableCommand)2 RegistryContext (org.drools.core.command.impl.RegistryContext)2 MarshallingConfigurationImpl (org.drools.serialization.protobuf.marshalling.MarshallingConfigurationImpl)2 InternalProcessRuntime (org.jbpm.process.instance.InternalProcessRuntime)2 ProcessInstance (org.jbpm.process.instance.ProcessInstance)2 ConstraintEvaluator (org.jbpm.process.instance.impl.ConstraintEvaluator)2 NodeInstanceContainer (org.jbpm.workflow.instance.NodeInstanceContainer)2 WorkflowRuntimeException (org.jbpm.workflow.instance.WorkflowRuntimeException)2 ActionNodeInstance (org.jbpm.workflow.instance.node.ActionNodeInstance)2 Test (org.junit.Test)2 KieBase (org.kie.api.KieBase)2 KieRuntime (org.kie.api.runtime.KieRuntime)2