Search in sources :

Example 1 with VariableScopeInstance

use of org.jbpm.process.instance.context.variable.VariableScopeInstance in project jbpm by kiegroup.

the class JavaScriptReturnValueEvaluator method evaluate.

public Object evaluate(ProcessContext context) throws Exception {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    // insert globals into context
    Globals globals = context.getKieRuntime().getGlobals();
    if (globals != null && globals.getGlobalKeys() != null) {
        for (String gKey : globals.getGlobalKeys()) {
            engine.put(gKey, globals.get(gKey));
        }
    }
    // insert process kcontext
    engine.put("kcontext", context);
    if (context.getProcessInstance() != null && context.getProcessInstance().getProcess() != null) {
        // insert process variables
        VariableScopeInstance variableScope = (VariableScopeInstance) ((WorkflowProcessInstance) context.getProcessInstance()).getContextInstance(VariableScope.VARIABLE_SCOPE);
        Map<String, Object> variables = variableScope.getVariables();
        if (variables != null) {
            for (Entry<String, Object> variable : variables.entrySet()) {
                engine.put(variable.getKey(), variable.getValue());
            }
        }
    }
    Object value = engine.eval(expr);
    if (!(value instanceof Boolean)) {
        throw new RuntimeException("Constraints must return boolean values: " + expr + " returns " + value + (value == null ? "" : " (type=" + value.getClass()));
    }
    return ((Boolean) value).booleanValue();
}
Also used : Globals(org.kie.api.runtime.Globals) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 2 with VariableScopeInstance

use of org.jbpm.process.instance.context.variable.VariableScopeInstance in project jbpm by kiegroup.

the class WorkItemNodeInstance method createWorkItem.

protected WorkItem createWorkItem(WorkItemNode workItemNode) {
    Work work = workItemNode.getWork();
    workItem = new WorkItemImpl();
    ((WorkItem) workItem).setName(work.getName());
    ((WorkItem) workItem).setProcessInstanceId(getProcessInstance().getId());
    ((WorkItem) workItem).setParameters(new HashMap<String, Object>(work.getParameters()));
    // if there are any dynamic parameters add them
    if (dynamicParameters != null) {
        ((WorkItem) workItem).getParameters().putAll(dynamicParameters);
    }
    for (Iterator<DataAssociation> iterator = workItemNode.getInAssociations().iterator(); iterator.hasNext(); ) {
        DataAssociation association = iterator.next();
        if (association.getTransformation() != null) {
            Transformation transformation = association.getTransformation();
            DataTransformer transformer = DataTransformerRegistry.get().find(transformation.getLanguage());
            if (transformer != null) {
                Object parameterValue = transformer.transform(transformation.getCompiledExpression(), getSourceParameters(association));
                if (parameterValue != null) {
                    ((WorkItem) workItem).setParameter(association.getTarget(), parameterValue);
                }
            }
        } else if (association.getAssignments() == null || association.getAssignments().isEmpty()) {
            Object parameterValue = null;
            VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, association.getSources().get(0));
            if (variableScopeInstance != null) {
                parameterValue = variableScopeInstance.getVariable(association.getSources().get(0));
            } else {
                try {
                    parameterValue = MVELSafeHelper.getEvaluator().eval(association.getSources().get(0), new NodeInstanceResolverFactory(this));
                } catch (Throwable t) {
                    logger.error("Could not find variable scope for variable {}", association.getSources().get(0));
                    logger.error("when trying to execute Work Item {}", work.getName());
                    logger.error("Continuing without setting parameter.");
                }
            }
            if (parameterValue != null) {
                ((WorkItem) workItem).setParameter(association.getTarget(), parameterValue);
            }
        } else {
            for (Iterator<Assignment> it = association.getAssignments().iterator(); it.hasNext(); ) {
                handleAssignment(it.next());
            }
        }
    }
    for (Map.Entry<String, Object> entry : workItem.getParameters().entrySet()) {
        if (entry.getValue() instanceof String) {
            String s = (String) entry.getValue();
            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 string for Work Item {}", work.getName());
                            logger.error("Continuing without setting parameter.");
                        }
                    }
                }
            }
            for (Map.Entry<String, String> replacement : replacements.entrySet()) {
                s = s.replace("#{" + replacement.getKey() + "}", replacement.getValue());
            }
            ((WorkItem) workItem).setParameter(entry.getKey(), s);
        }
    }
    return workItem;
}
Also used : Transformation(org.jbpm.workflow.core.node.Transformation) DataAssociation(org.jbpm.workflow.core.node.DataAssociation) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) WorkItem(org.drools.core.process.instance.WorkItem) DataTransformer(org.kie.api.runtime.process.DataTransformer) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) Work(org.jbpm.process.core.Work) WorkItemImpl(org.drools.core.process.instance.impl.WorkItemImpl) NodeInstanceResolverFactory(org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory) Iterator(java.util.Iterator) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with VariableScopeInstance

use of org.jbpm.process.instance.context.variable.VariableScopeInstance in project jbpm by kiegroup.

the class WorkItemNodeInstance method triggerCompleted.

public void triggerCompleted(WorkItem workItem) {
    this.workItem = workItem;
    WorkItemNode workItemNode = getWorkItemNode();
    if (workItemNode != null && workItem.getState() == WorkItem.COMPLETED) {
        validateWorkItemResultVariable(getProcessInstance().getProcessName(), workItemNode.getOutAssociations(), workItem);
        for (Iterator<DataAssociation> iterator = getWorkItemNode().getOutAssociations().iterator(); iterator.hasNext(); ) {
            DataAssociation association = iterator.next();
            if (association.getTransformation() != null) {
                Transformation transformation = association.getTransformation();
                DataTransformer transformer = DataTransformerRegistry.get().find(transformation.getLanguage());
                if (transformer != null) {
                    Object parameterValue = transformer.transform(transformation.getCompiledExpression(), workItem.getResults());
                    VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, association.getTarget());
                    if (variableScopeInstance != null && parameterValue != null) {
                        variableScopeInstance.getVariableScope().validateVariable(getProcessInstance().getProcessName(), association.getTarget(), parameterValue);
                        variableScopeInstance.setVariable(association.getTarget(), parameterValue);
                    } else {
                        logger.warn("Could not find variable scope for variable {}", association.getTarget());
                        logger.warn("when trying to complete Work Item {}", workItem.getName());
                        logger.warn("Continuing without setting variable.");
                    }
                    if (parameterValue != null) {
                        ((WorkItem) workItem).setParameter(association.getTarget(), parameterValue);
                    }
                }
            } else if (association.getAssignments() == null || association.getAssignments().isEmpty()) {
                VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, association.getTarget());
                if (variableScopeInstance != null) {
                    Object value = workItem.getResult(association.getSources().get(0));
                    if (value == null) {
                        try {
                            value = MVELSafeHelper.getEvaluator().eval(association.getSources().get(0), new WorkItemResolverFactory(workItem));
                        } catch (Throwable t) {
                        // do nothing
                        }
                    }
                    Variable varDef = variableScopeInstance.getVariableScope().findVariable(association.getTarget());
                    DataType dataType = varDef.getType();
                    // exclude java.lang.Object as it is considered unknown type
                    if (!dataType.getStringType().endsWith("java.lang.Object") && !dataType.getStringType().endsWith("Object") && value instanceof String) {
                        value = dataType.readValue((String) value);
                    } else {
                        variableScopeInstance.getVariableScope().validateVariable(getProcessInstance().getProcessName(), association.getTarget(), value);
                    }
                    variableScopeInstance.setVariable(association.getTarget(), value);
                } else {
                    logger.warn("Could not find variable scope for variable {}", association.getTarget());
                    logger.warn("when trying to complete Work Item {}", workItem.getName());
                    logger.warn("Continuing without setting variable.");
                }
            } else {
                try {
                    for (Iterator<Assignment> it = association.getAssignments().iterator(); it.hasNext(); ) {
                        handleAssignment(it.next());
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    // handle dynamic nodes
    if (getNode() == null) {
        setMetaData("NodeType", workItem.getName());
        mapDynamicOutputData(workItem.getResults());
    }
    if (isInversionOfControl()) {
        KieRuntime kruntime = ((ProcessInstance) getProcessInstance()).getKnowledgeRuntime();
        kruntime.update(kruntime.getFactHandle(this), this);
    } else {
        triggerCompleted();
    }
}
Also used : Transformation(org.jbpm.workflow.core.node.Transformation) Variable(org.jbpm.process.core.context.variable.Variable) DataAssociation(org.jbpm.workflow.core.node.DataAssociation) KieRuntime(org.kie.api.runtime.KieRuntime) WorkItem(org.drools.core.process.instance.WorkItem) WorkflowRuntimeException(org.jbpm.workflow.instance.WorkflowRuntimeException) WorkItemHandlerNotFoundException(org.drools.core.WorkItemHandlerNotFoundException) WorkItemResolverFactory(org.jbpm.workflow.instance.impl.WorkItemResolverFactory) WorkflowRuntimeException(org.jbpm.workflow.instance.WorkflowRuntimeException) DataTransformer(org.kie.api.runtime.process.DataTransformer) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) WorkItemNode(org.jbpm.workflow.core.node.WorkItemNode) Iterator(java.util.Iterator) DataType(org.jbpm.process.core.datatype.DataType) ProcessInstance(org.jbpm.process.instance.ProcessInstance)

Example 4 with VariableScopeInstance

use of org.jbpm.process.instance.context.variable.VariableScopeInstance in project jbpm by kiegroup.

the class JoinInstance method internalTrigger.

public void internalTrigger(final NodeInstance from, String type) {
    if (!org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE.equals(type)) {
        throw new IllegalArgumentException("An ActionNode only accepts default incoming connections!");
    }
    final Join join = getJoin();
    switch(join.getType()) {
        case Join.TYPE_XOR:
            triggerCompleted();
            break;
        case Join.TYPE_AND:
            Integer count = (Integer) this.triggers.get(from.getNodeId());
            if (count == null) {
                this.triggers.put(from.getNodeId(), 1);
            } else {
                this.triggers.put(from.getNodeId(), count.intValue() + 1);
            }
            if (checkAllActivated()) {
                decreaseAllTriggers();
                triggerCompleted();
            }
            break;
        case Join.TYPE_DISCRIMINATOR:
            boolean triggerCompleted = triggers.isEmpty();
            triggers.put(from.getNodeId(), new Integer(1));
            if (checkAllActivated()) {
                resetAllTriggers();
            }
            if (triggerCompleted) {
                triggerCompleted();
            }
            break;
        case Join.TYPE_N_OF_M:
            count = (Integer) this.triggers.get(from.getNodeId());
            if (count == null) {
                this.triggers.put(from.getNodeId(), 1);
            } else {
                this.triggers.put(from.getNodeId(), count.intValue() + 1);
            }
            int counter = 0;
            for (final Connection connection : getJoin().getDefaultIncomingConnections()) {
                if (this.triggers.get(connection.getFrom().getId()) != null) {
                    counter++;
                }
            }
            String n = join.getN();
            Integer number = null;
            if (n.startsWith("#{") && n.endsWith("}")) {
                n = n.substring(2, n.length() - 1);
                VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, n);
                if (variableScopeInstance == null) {
                    throw new IllegalArgumentException("Could not find variable " + n + " when executing join.");
                }
                Object value = variableScopeInstance.getVariable(n);
                if (value instanceof Number) {
                    number = ((Number) value).intValue();
                } else {
                    throw new IllegalArgumentException("Variable " + n + " did not return a number when executing join: " + value);
                }
            } else {
                number = new Integer(n);
            }
            if (counter >= number) {
                resetAllTriggers();
                triggerCompleted();
            }
            break;
        case Join.TYPE_OR:
            NodeInstanceContainer nodeInstanceContainer = (NodeInstanceContainer) getNodeInstanceContainer();
            boolean activePathExists = existsActiveDirectFlow(nodeInstanceContainer, getJoin());
            if (!activePathExists) {
                triggerCompleted();
            }
            break;
        default:
            throw new IllegalArgumentException("Illegal join type " + join.getType());
    }
}
Also used : NodeInstanceContainer(org.kie.api.runtime.process.NodeInstanceContainer) VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) Connection(org.kie.api.definition.process.Connection) Join(org.jbpm.workflow.core.node.Join)

Example 5 with VariableScopeInstance

use of org.jbpm.process.instance.context.variable.VariableScopeInstance in project jbpm by kiegroup.

the class RuleSetNodeInstance method resolveVariable.

private Object resolveVariable(Object s) {
    if (s instanceof String) {
        Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher((String) s);
        while (matcher.find()) {
            String paramName = matcher.group(1);
            VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, paramName);
            if (variableScopeInstance != null) {
                Object variableValue = variableScopeInstance.getVariable(paramName);
                if (variableValue != null) {
                    return variableValue;
                }
            } else {
                try {
                    Object variableValue = MVELSafeHelper.getEvaluator().eval(paramName, new NodeInstanceResolverFactory(this));
                    if (variableValue != null) {
                        return variableValue;
                    }
                } catch (Throwable t) {
                    logger.error("Could not find variable scope for variable {}", paramName);
                }
            }
        }
    }
    return s;
}
Also used : VariableScopeInstance(org.jbpm.process.instance.context.variable.VariableScopeInstance) Matcher(java.util.regex.Matcher) NodeInstanceResolverFactory(org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory)

Aggregations

VariableScopeInstance (org.jbpm.process.instance.context.variable.VariableScopeInstance)38 HashMap (java.util.HashMap)17 Map (java.util.Map)12 NodeInstanceResolverFactory (org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory)9 ExclusiveGroupInstance (org.jbpm.process.instance.context.exclusive.ExclusiveGroupInstance)8 NodeInstance (org.kie.api.runtime.process.NodeInstance)8 ArrayList (java.util.ArrayList)6 Matcher (java.util.regex.Matcher)6 SwimlaneContextInstance (org.jbpm.process.instance.context.swimlane.SwimlaneContextInstance)6 DataAssociation (org.jbpm.workflow.core.node.DataAssociation)6 Transformation (org.jbpm.workflow.core.node.Transformation)6 DataTransformer (org.kie.api.runtime.process.DataTransformer)6 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)6 ContextInstance (org.jbpm.process.instance.ContextInstance)5 WorkflowProcessInstanceImpl (org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl)5 Process (org.kie.api.definition.process.Process)5 MarshallerReaderContext (org.drools.core.marshalling.impl.MarshallerReaderContext)4 MarshallerWriteContext (org.drools.core.marshalling.impl.MarshallerWriteContext)4 Context (org.jbpm.process.core.Context)4 SwimlaneContext (org.jbpm.process.core.context.swimlane.SwimlaneContext)4