Search in sources :

Example 6 with NodeInstanceResolverFactory

use of org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory in project jbpm by kiegroup.

the class SubProcessNodeInstance method internalTrigger.

public void internalTrigger(final NodeInstance from, String type) {
    super.internalTrigger(from, type);
    // if node instance was cancelled, abort
    if (getNodeInstanceContainer().getNodeInstance(getId()) == null) {
        return;
    }
    if (!org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE.equals(type)) {
        throw new IllegalArgumentException("A SubProcess node only accepts default incoming connections!");
    }
    Map<String, Object> parameters = new HashMap<String, Object>();
    for (Iterator<DataAssociation> iterator = getSubProcessNode().getInAssociations().iterator(); iterator.hasNext(); ) {
        DataAssociation mapping = iterator.next();
        Object parameterValue = null;
        if (mapping.getTransformation() != null) {
            Transformation transformation = mapping.getTransformation();
            DataTransformer transformer = DataTransformerRegistry.get().find(transformation.getLanguage());
            if (transformer != null) {
                parameterValue = transformer.transform(transformation.getCompiledExpression(), getSourceParameters(mapping));
            }
        } else {
            VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, mapping.getSources().get(0));
            if (variableScopeInstance != null) {
                parameterValue = variableScopeInstance.getVariable(mapping.getSources().get(0));
            } else {
                try {
                    parameterValue = MVELSafeHelper.getEvaluator().eval(mapping.getSources().get(0), new NodeInstanceResolverFactory(this));
                } catch (Throwable t) {
                    parameterValue = VariableUtil.resolveVariable(mapping.getSources().get(0), this);
                    if (parameterValue != null) {
                        parameters.put(mapping.getTarget(), parameterValue);
                    } else {
                        logger.error("Could not find variable scope for variable {}", mapping.getSources().get(0));
                        logger.error("when trying to execute SubProcess node {}", getSubProcessNode().getName());
                        logger.error("Continuing without setting parameter.");
                    }
                }
            }
        }
        if (parameterValue != null) {
            parameters.put(mapping.getTarget(), parameterValue);
        }
    }
    String processId = getSubProcessNode().getProcessId();
    if (processId == null) {
        // if process id is not given try with process name
        processId = getSubProcessNode().getProcessName();
    }
    // resolve processId if necessary
    Map<String, String> replacements = new HashMap<String, String>();
    Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(processId);
    while (matcher.find()) {
        String paramName = matcher.group(1);
        if (replacements.get(paramName) == null) {
            VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, paramName);
            if (variableScopeInstance != null) {
                Object variableValue = variableScopeInstance.getVariable(paramName);
                String variableValueString = variableValue == null ? "" : variableValue.toString();
                replacements.put(paramName, variableValueString);
            } else {
                try {
                    Object variableValue = MVELSafeHelper.getEvaluator().eval(paramName, new NodeInstanceResolverFactory(this));
                    String variableValueString = variableValue == null ? "" : variableValue.toString();
                    replacements.put(paramName, variableValueString);
                } catch (Throwable t) {
                    logger.error("Could not find variable scope for variable {}", paramName);
                    logger.error("when trying to replace variable in processId for sub process {}", getNodeName());
                    logger.error("Continuing without setting process id.");
                }
            }
        }
    }
    for (Map.Entry<String, String> replacement : replacements.entrySet()) {
        processId = processId.replace("#{" + replacement.getKey() + "}", replacement.getValue());
    }
    KieBase kbase = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime().getKieBase();
    // start process instance
    Process process = kbase.getProcess(processId);
    if (process == null) {
        // try to find it by name
        String latestProcessId = StartProcessHelper.findLatestProcessByName(kbase, processId);
        if (latestProcessId != null) {
            processId = latestProcessId;
            process = kbase.getProcess(processId);
        }
    }
    if (process == null) {
        logger.error("Could not find process {}", processId);
        logger.error("Aborting process");
        ((ProcessInstance) getProcessInstance()).setState(ProcessInstance.STATE_ABORTED);
        throw new RuntimeException("Could not find process " + processId);
    } else {
        KieRuntime kruntime = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime();
        RuntimeManager manager = (RuntimeManager) kruntime.getEnvironment().get(EnvironmentName.RUNTIME_MANAGER);
        if (manager != null) {
            org.kie.api.runtime.manager.Context<?> context = ProcessInstanceIdContext.get();
            String caseId = (String) kruntime.getEnvironment().get(EnvironmentName.CASE_ID);
            if (caseId != null) {
                context = CaseContext.get(caseId);
            }
            RuntimeEngine runtime = manager.getRuntimeEngine(context);
            kruntime = (KieRuntime) runtime.getKieSession();
        }
        if (getSubProcessNode().getMetaData("MICollectionInput") != null) {
            // remove foreach input variable to avoid problems when running in variable strict mode
            parameters.remove(getSubProcessNode().getMetaData("MICollectionInput"));
        }
        ProcessInstance processInstance = null;
        if (((WorkflowProcessInstanceImpl) getProcessInstance()).getCorrelationKey() != null) {
            // in case there is correlation key on parent instance pass it along to child so it can be easily correlated
            // since correlation key must be unique for active instances it appends processId and timestamp
            List<String> businessKeys = new ArrayList<String>();
            businessKeys.add(((WorkflowProcessInstanceImpl) getProcessInstance()).getCorrelationKey());
            businessKeys.add(processId);
            businessKeys.add(String.valueOf(System.currentTimeMillis()));
            CorrelationKeyFactory correlationKeyFactory = KieInternalServices.Factory.get().newCorrelationKeyFactory();
            CorrelationKey subProcessCorrelationKey = correlationKeyFactory.newCorrelationKey(businessKeys);
            processInstance = (ProcessInstance) ((CorrelationAwareProcessRuntime) kruntime).createProcessInstance(processId, subProcessCorrelationKey, parameters);
        } else {
            processInstance = (ProcessInstance) kruntime.createProcessInstance(processId, parameters);
        }
        this.processInstanceId = processInstance.getId();
        ((ProcessInstanceImpl) processInstance).setMetaData("ParentProcessInstanceId", getProcessInstance().getId());
        ((ProcessInstanceImpl) processInstance).setMetaData("ParentNodeInstanceId", getUniqueId());
        ((ProcessInstanceImpl) processInstance).setMetaData("ParentNodeId", getSubProcessNode().getUniqueId());
        ((ProcessInstanceImpl) processInstance).setParentProcessInstanceId(getProcessInstance().getId());
        ((ProcessInstanceImpl) processInstance).setSignalCompletion(getSubProcessNode().isWaitForCompletion());
        kruntime.startProcessInstance(processInstance.getId());
        if (!getSubProcessNode().isWaitForCompletion()) {
            triggerCompleted();
        } else if (processInstance.getState() == ProcessInstance.STATE_COMPLETED || processInstance.getState() == ProcessInstance.STATE_ABORTED) {
            processInstanceCompleted(processInstance);
        } else {
            addProcessListener();
        }
    }
}
Also used : Transformation(org.jbpm.workflow.core.node.Transformation) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Process(org.kie.api.definition.process.Process) DataTransformer(org.kie.api.runtime.process.DataTransformer) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) CorrelationKey(org.kie.internal.process.CorrelationKey) KieBase(org.kie.api.KieBase) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) CorrelationAwareProcessRuntime(org.kie.internal.process.CorrelationAwareProcessRuntime) DataAssociation(org.jbpm.workflow.core.node.DataAssociation) WorkflowProcessInstanceImpl(org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl) ProcessInstanceImpl(org.jbpm.process.instance.impl.ProcessInstanceImpl) KieRuntime(org.kie.api.runtime.KieRuntime) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) CorrelationKeyFactory(org.kie.internal.process.CorrelationKeyFactory) NodeInstanceResolverFactory(org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory) ProcessInstance(org.jbpm.process.instance.ProcessInstance) Map(java.util.Map) HashMap(java.util.HashMap)

Example 7 with NodeInstanceResolverFactory

use of org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory in project jbpm by kiegroup.

the class WorkItemNodeInstance method getSourceParameters.

protected Map<String, Object> getSourceParameters(DataAssociation association) {
    Map<String, Object> parameters = new HashMap<String, Object>();
    for (String sourceParam : association.getSources()) {
        Object parameterValue = null;
        VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, sourceParam);
        if (variableScopeInstance != null) {
            parameterValue = variableScopeInstance.getVariable(sourceParam);
        } else {
            try {
                parameterValue = MVELSafeHelper.getEvaluator().eval(sourceParam, new NodeInstanceResolverFactory(this));
            } catch (Throwable t) {
                logger.warn("Could not find variable scope for variable {}", sourceParam);
            }
        }
        if (parameterValue != null) {
            parameters.put(association.getTarget(), parameterValue);
        }
    }
    return parameters;
}
Also used : VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) HashMap(java.util.HashMap) NodeInstanceResolverFactory(org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory)

Example 8 with NodeInstanceResolverFactory

use of org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory in project jbpm by kiegroup.

the class ForEachNodeInstance method evaluateCollectionExpression.

private Collection<?> evaluateCollectionExpression(String collectionExpression) {
    // TODO: should evaluate this expression using MVEL
    Object collection = null;
    VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, collectionExpression);
    if (variableScopeInstance != null) {
        collection = variableScopeInstance.getVariable(collectionExpression);
    } else {
        try {
            collection = MVELSafeHelper.getEvaluator().eval(collectionExpression, new NodeInstanceResolverFactory(this));
        } catch (Throwable t) {
            throw new IllegalArgumentException("Could not find collection " + collectionExpression);
        }
    }
    if (collection == null) {
        return Collections.EMPTY_LIST;
    }
    if (collection instanceof Collection<?>) {
        return (Collection<?>) collection;
    }
    if (collection.getClass().isArray()) {
        List<Object> list = new ArrayList<Object>();
        for (Object o : (Object[]) collection) {
            list.add(o);
        }
        return list;
    }
    throw new IllegalArgumentException("Unexpected collection type: " + collection.getClass());
}
Also used : VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) NodeInstanceResolverFactory(org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory) ArrayList(java.util.ArrayList) Collection(java.util.Collection)

Example 9 with NodeInstanceResolverFactory

use of org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory in project jbpm by kiegroup.

the class StateBasedNodeInstance method resolveVariable.

protected String resolveVariable(String s) {
    if (s == null) {
        return null;
    }
    // cannot parse delay, trying to interpret it
    Map<String, String> replacements = new HashMap<String, String>();
    Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher(s);
    while (matcher.find()) {
        String paramName = matcher.group(1);
        if (replacements.get(paramName) == null) {
            VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, paramName);
            if (variableScopeInstance != null) {
                Object variableValue = variableScopeInstance.getVariable(paramName);
                String variableValueString = variableValue == null ? "" : variableValue.toString();
                replacements.put(paramName, variableValueString);
            } else {
                try {
                    Object variableValue = MVELSafeHelper.getEvaluator().eval(paramName, new NodeInstanceResolverFactory(this));
                    String variableValueString = variableValue == null ? "" : variableValue.toString();
                    replacements.put(paramName, variableValueString);
                } catch (Throwable t) {
                    logger.error("Could not find variable scope for variable {}", paramName);
                    logger.error("when trying to replace variable in processId for sub process {}", getNodeName());
                    logger.error("Continuing without setting process id.");
                }
            }
        }
    }
    for (Map.Entry<String, String> replacement : replacements.entrySet()) {
        s = s.replace("#{" + replacement.getKey() + "}", replacement.getValue());
    }
    return s;
}
Also used : VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) NodeInstanceResolverFactory(org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with NodeInstanceResolverFactory

use of org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory in project jbpm by kiegroup.

the class DynamicNodeInstance method nodeInstanceCompleted.

public void nodeInstanceCompleted(org.jbpm.workflow.instance.NodeInstance nodeInstance, String outType) {
    Node nodeInstanceNode = nodeInstance.getNode();
    if (nodeInstanceNode != null) {
        Object compensationBoolObj = nodeInstanceNode.getMetaData().get("isForCompensation");
        boolean isForCompensation = compensationBoolObj == null ? false : ((Boolean) compensationBoolObj);
        if (isForCompensation) {
            return;
        }
    }
    String completionCondition = getDynamicNode().getCompletionExpression();
    // TODO are we sure there will always be node instances left if we are not done yet?
    if (isTerminated(nodeInstance)) {
        triggerCompleted(NodeImpl.CONNECTION_DEFAULT_TYPE);
    } else if (getDynamicNode().isAutoComplete() && getNodeInstances(false).isEmpty()) {
        triggerCompleted(NodeImpl.CONNECTION_DEFAULT_TYPE);
    } else if (completionCondition != null && "mvel".equals(getDynamicNode().getLanguage())) {
        Object value = MVELSafeHelper.getEvaluator().eval(completionCondition, new NodeInstanceResolverFactory(this));
        if (!(value instanceof Boolean)) {
            throw new RuntimeException("Completion condition expression must return boolean values: " + value + " for expression " + completionCondition);
        }
        if (((Boolean) value).booleanValue()) {
            triggerCompleted(NodeImpl.CONNECTION_DEFAULT_TYPE);
        }
    }
}
Also used : DynamicNode(org.jbpm.workflow.core.node.DynamicNode) Node(org.kie.api.definition.process.Node) NodeInstanceResolverFactory(org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory)

Aggregations

NodeInstanceResolverFactory (org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory)10 VariableScopeInstance (org.jbpm.process.instance.context.variable.VariableScopeInstance)9 HashMap (java.util.HashMap)7 Map (java.util.Map)4 Matcher (java.util.regex.Matcher)4 DataAssociation (org.jbpm.workflow.core.node.DataAssociation)3 Transformation (org.jbpm.workflow.core.node.Transformation)3 DataTransformer (org.kie.api.runtime.process.DataTransformer)3 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)1 Iterator (java.util.Iterator)1 WorkItem (org.drools.core.process.instance.WorkItem)1 WorkItemImpl (org.drools.core.process.instance.impl.WorkItemImpl)1 Work (org.jbpm.process.core.Work)1 ProcessInstance (org.jbpm.process.instance.ProcessInstance)1 ProcessInstanceImpl (org.jbpm.process.instance.impl.ProcessInstanceImpl)1 DynamicNode (org.jbpm.workflow.core.node.DynamicNode)1 WorkflowProcessInstanceImpl (org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl)1 KieBase (org.kie.api.KieBase)1 Node (org.kie.api.definition.process.Node)1