Search in sources :

Example 1 with CorrelationKey

use of io.automatiko.engine.services.correlation.CorrelationKey in project automatiko-engine by automatiko-io.

the class SubProcessNodeInstance method internalTrigger.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
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 (!io.automatiko.engine.workflow.process.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 {
                    ExpressionEvaluator evaluator = (ExpressionEvaluator) ((WorkflowProcess) getProcessInstance().getProcess()).getDefaultContext(ExpressionEvaluator.EXPRESSION_EVALUATOR);
                    parameterValue = evaluator.evaluate(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);
        String replacementKey = paramName;
        String defaultValue = "";
        if (paramName.contains(":")) {
            String[] items = paramName.split(":");
            paramName = items[0];
            defaultValue = items[1];
        }
        if (replacements.get(replacementKey) == null) {
            VariableScopeInstance variableScopeInstance = (VariableScopeInstance) resolveContextInstance(VariableScope.VARIABLE_SCOPE, paramName);
            if (variableScopeInstance != null) {
                Object variableValue = variableScopeInstance.getVariable(paramName);
                String variableValueString = variableValue == null ? defaultValue : variableValue.toString();
                replacements.put(replacementKey, variableValueString);
            } else {
                try {
                    ExpressionEvaluator evaluator = (ExpressionEvaluator) ((WorkflowProcess) getProcessInstance().getProcess()).getDefaultContext(ExpressionEvaluator.EXPRESSION_EVALUATOR);
                    Object variableValue = evaluator.evaluate(paramName, new NodeInstanceResolverFactory(this));
                    String variableValueString = variableValue == null ? defaultValue : variableValue.toString();
                    replacements.put(replacementKey, 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());
    }
    // start process instance
    Process process = getProcessInstance().getProcessRuntime().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 {
        ProcessRuntime kruntime = ((ProcessInstance) getProcessInstance()).getProcessRuntime();
        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()));
            CorrelationKey subProcessCorrelationKey = new StringCorrelationKey(businessKeys.stream().collect(Collectors.joining(":")));
            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).setRootProcessInstanceId(StringUtils.isEmpty(getProcessInstance().getRootProcessInstanceId()) ? getProcessInstance().getId() : getProcessInstance().getRootProcessInstanceId());
        ((ProcessInstanceImpl) processInstance).setRootProcessId(StringUtils.isEmpty(getProcessInstance().getRootProcessId()) ? getProcessInstance().getProcessId() : getProcessInstance().getRootProcessId());
        ((ProcessInstanceImpl) processInstance).setSignalCompletion(getSubProcessNode().isWaitForCompletion());
        ((ProcessInstanceImpl) processInstance).addChild(processInstance.getProcessId(), processInstance.getId());
        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(io.automatiko.engine.workflow.process.core.node.Transformation) StringCorrelationKey(io.automatiko.engine.services.correlation.StringCorrelationKey) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) WorkflowProcess(io.automatiko.engine.workflow.process.core.WorkflowProcess) Process(io.automatiko.engine.api.definition.process.Process) ExpressionEvaluator(io.automatiko.engine.api.expression.ExpressionEvaluator) DataTransformer(io.automatiko.engine.api.runtime.process.DataTransformer) VariableScopeInstance(io.automatiko.engine.workflow.base.instance.context.variable.VariableScopeInstance) CorrelationKey(io.automatiko.engine.services.correlation.CorrelationKey) StringCorrelationKey(io.automatiko.engine.services.correlation.StringCorrelationKey) ProcessRuntime(io.automatiko.engine.api.runtime.process.ProcessRuntime) InternalProcessRuntime(io.automatiko.engine.workflow.base.instance.InternalProcessRuntime) CorrelationAwareProcessRuntime(io.automatiko.engine.services.correlation.CorrelationAwareProcessRuntime) CorrelationAwareProcessRuntime(io.automatiko.engine.services.correlation.CorrelationAwareProcessRuntime) DataAssociation(io.automatiko.engine.workflow.process.core.node.DataAssociation) WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) ProcessInstanceImpl(io.automatiko.engine.workflow.base.instance.impl.ProcessInstanceImpl) NodeInstanceResolverFactory(io.automatiko.engine.workflow.process.instance.impl.NodeInstanceResolverFactory) ProcessInstance(io.automatiko.engine.workflow.base.instance.ProcessInstance) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with CorrelationKey

use of io.automatiko.engine.services.correlation.CorrelationKey in project automatiko-engine by automatiko-io.

the class DynamicUtils method executeSubProcess.

private static String executeSubProcess(InternalProcessRuntime runtime, String processId, Map<String, Object> parameters, ProcessInstance processInstance, SubProcessNodeInstance subProcessNodeInstance) {
    Process process = runtime.getProcess(processId);
    if (process == null) {
        logger.error("Could not find process {}", processId);
        throw new IllegalArgumentException("No process definition found with id: " + processId);
    } else {
        ProcessEventSupport eventSupport = runtime.getProcessEventSupport();
        eventSupport.fireBeforeNodeTriggered(subProcessNodeInstance, runtime);
        ProcessInstance subProcessInstance = null;
        if (((WorkflowProcessInstanceImpl) processInstance).getCorrelationKey() != null) {
            List<String> businessKeys = new ArrayList<>();
            businessKeys.add(((WorkflowProcessInstanceImpl) processInstance).getCorrelationKey());
            businessKeys.add(processId);
            businessKeys.add(String.valueOf(System.currentTimeMillis()));
            CorrelationKey subProcessCorrelationKey = new StringCorrelationKey(businessKeys.stream().collect(Collectors.joining(":")));
            subProcessInstance = (ProcessInstance) runtime.createProcessInstance(processId, subProcessCorrelationKey, parameters);
        } else {
            subProcessInstance = (ProcessInstance) runtime.createProcessInstance(processId, parameters);
        }
        ((ProcessInstanceImpl) subProcessInstance).setMetaData("ParentProcessInstanceId", processInstance.getId());
        ((ProcessInstanceImpl) subProcessInstance).setParentProcessInstanceId(processInstance.getId());
        subProcessInstance = (ProcessInstance) runtime.startProcessInstance(subProcessInstance.getId());
        subProcessNodeInstance.internalSetProcessInstanceId(subProcessInstance.getId());
        eventSupport.fireAfterNodeTriggered(subProcessNodeInstance, runtime);
        if (subProcessInstance.getState() == io.automatiko.engine.api.runtime.process.ProcessInstance.STATE_COMPLETED) {
            subProcessNodeInstance.triggerCompleted();
        } else {
            subProcessNodeInstance.addEventListeners();
        }
        return subProcessInstance.getId();
    }
}
Also used : ProcessEventSupport(io.automatiko.engine.workflow.base.core.event.ProcessEventSupport) StringCorrelationKey(io.automatiko.engine.services.correlation.StringCorrelationKey) CorrelationKey(io.automatiko.engine.services.correlation.CorrelationKey) StringCorrelationKey(io.automatiko.engine.services.correlation.StringCorrelationKey) WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) ProcessInstanceImpl(io.automatiko.engine.workflow.base.instance.impl.ProcessInstanceImpl) ArrayList(java.util.ArrayList) WorkflowProcess(io.automatiko.engine.workflow.process.core.WorkflowProcess) Process(io.automatiko.engine.api.definition.process.Process) ProcessInstance(io.automatiko.engine.workflow.base.instance.ProcessInstance) WorkflowProcessInstance(io.automatiko.engine.workflow.process.instance.WorkflowProcessInstance)

Example 3 with CorrelationKey

use of io.automatiko.engine.services.correlation.CorrelationKey in project automatiko-engine by automatiko-io.

the class LightProcessRuntime method createProcessInstance.

private io.automatiko.engine.workflow.base.instance.ProcessInstance createProcessInstance(Process process, CorrelationKey correlationKey, Map<String, Object> parameters) {
    io.automatiko.engine.workflow.base.instance.ProcessInstance pi = runtimeContext.createProcessInstance(process, correlationKey);
    pi.setProcessRuntime(this);
    runtimeContext.setupParameters(pi, parameters, variableInitializer);
    Map<String, Object> temp = new HashMap<>();
    if (parameters != null) {
        temp.putAll(parameters);
    }
    temp.putAll(pi.getVariables());
    String uuid;
    if (correlationKey != null) {
        uuid = UUID.nameUUIDFromBytes(correlationKey.toExternalForm().getBytes(StandardCharsets.UTF_8)).toString();
        ((WorkflowProcessInstanceImpl) pi).setCorrelationKey(correlationKey.toExternalForm());
    } else {
        VariableScope variableScope = (VariableScope) ((ContextContainer) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
        Optional<Object> businessKeyVar = variableScope.getVariables().stream().filter(var -> var.hasTag(Variable.BUSINESS_KEY_TAG)).map(v -> temp.get(v.getName())).filter(var -> var != null).findAny();
        if (businessKeyVar.isPresent()) {
            Object businessKey = businessKeyVar.get();
            uuid = UUID.nameUUIDFromBytes(businessKey.toString().getBytes(StandardCharsets.UTF_8)).toString();
            ((WorkflowProcessInstanceImpl) pi).setCorrelationKey(businessKey.toString());
        } else {
            uuid = UUID.randomUUID().toString();
        }
    }
    pi.setId(uuid);
    VariableScope variableScope = (VariableScope) ((ContextContainer) process).getDefaultContext(VariableScope.VARIABLE_SCOPE);
    VariableScopeInstance variableScopeInstance = (VariableScopeInstance) pi.getContextInstance(VariableScope.VARIABLE_SCOPE);
    // set input parameters
    if (parameters != null) {
        if (variableScope != null) {
            for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                variableScope.validateVariable(process.getName(), entry.getKey(), entry.getValue());
                variableScopeInstance.setVariable(entry.getKey(), entry.getValue());
            }
        } else {
            throw new IllegalArgumentException("This process does not support parameters!");
        }
    }
    variableScopeInstance.enforceRequiredVariables();
    return pi;
}
Also used : SignalManager(io.automatiko.engine.api.workflow.signal.SignalManager) Trigger(io.automatiko.engine.workflow.process.core.node.Trigger) Timer(io.automatiko.engine.workflow.base.core.timer.Timer) TimeUtils(io.automatiko.engine.workflow.base.core.timer.TimeUtils) ExactExpirationTime(io.automatiko.engine.api.jobs.ExactExpirationTime) WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) ExpirationTime(io.automatiko.engine.api.jobs.ExpirationTime) CorrelationKey(io.automatiko.engine.services.correlation.CorrelationKey) HashMap(java.util.HashMap) DefaultProcessInstanceManager(io.automatiko.engine.workflow.base.instance.impl.DefaultProcessInstanceManager) Node(io.automatiko.engine.api.definition.process.Node) VariableScopeInstance(io.automatiko.engine.workflow.base.instance.context.variable.VariableScopeInstance) DurationExpirationTime(io.automatiko.engine.api.jobs.DurationExpirationTime) ProcessJobDescription(io.automatiko.engine.api.jobs.ProcessJobDescription) JobsService(io.automatiko.engine.api.jobs.JobsService) ContextContainer(io.automatiko.engine.workflow.base.core.ContextContainer) ProcessInstance(io.automatiko.engine.api.runtime.process.ProcessInstance) ProcessEventSupport(io.automatiko.engine.workflow.base.core.event.ProcessEventSupport) Map(java.util.Map) EventListener(io.automatiko.engine.api.runtime.process.EventListener) Process(io.automatiko.engine.api.definition.process.Process) EventFilter(io.automatiko.engine.workflow.base.core.event.EventFilter) ProcessEventListener(io.automatiko.engine.api.event.process.ProcessEventListener) UnitOfWorkManager(io.automatiko.engine.api.uow.UnitOfWorkManager) Collection(java.util.Collection) ExecutableProcess(io.automatiko.engine.workflow.process.executable.core.ExecutableProcess) EventTransformer(io.automatiko.engine.workflow.base.core.event.EventTransformer) DateTimeUtils(io.automatiko.engine.workflow.base.core.timer.DateTimeUtils) UUID(java.util.UUID) InMemoryJobService(io.automatiko.engine.services.jobs.impl.InMemoryJobService) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope) StandardCharsets(java.nio.charset.StandardCharsets) WorkItemExecutionError(io.automatiko.engine.api.workflow.workitem.WorkItemExecutionError) VariableInitializer(io.automatiko.engine.api.workflow.VariableInitializer) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) EventTypeFilter(io.automatiko.engine.workflow.base.core.event.EventTypeFilter) CronExpirationTime(io.automatiko.engine.workflow.base.core.timer.CronExpirationTime) Optional(java.util.Optional) StartNode(io.automatiko.engine.workflow.process.core.node.StartNode) WorkItemManager(io.automatiko.engine.api.runtime.process.WorkItemManager) Variable(io.automatiko.engine.workflow.base.core.context.variable.Variable) EventTrigger(io.automatiko.engine.workflow.process.core.node.EventTrigger) Collections(java.util.Collections) HashMap(java.util.HashMap) WorkflowProcessInstanceImpl(io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl) VariableScopeInstance(io.automatiko.engine.workflow.base.instance.context.variable.VariableScopeInstance) HashMap(java.util.HashMap) Map(java.util.Map) VariableScope(io.automatiko.engine.workflow.base.core.context.variable.VariableScope)

Aggregations

Process (io.automatiko.engine.api.definition.process.Process)3 CorrelationKey (io.automatiko.engine.services.correlation.CorrelationKey)3 WorkflowProcessInstanceImpl (io.automatiko.engine.workflow.process.instance.impl.WorkflowProcessInstanceImpl)3 StringCorrelationKey (io.automatiko.engine.services.correlation.StringCorrelationKey)2 ProcessEventSupport (io.automatiko.engine.workflow.base.core.event.ProcessEventSupport)2 ProcessInstance (io.automatiko.engine.workflow.base.instance.ProcessInstance)2 VariableScopeInstance (io.automatiko.engine.workflow.base.instance.context.variable.VariableScopeInstance)2 ProcessInstanceImpl (io.automatiko.engine.workflow.base.instance.impl.ProcessInstanceImpl)2 WorkflowProcess (io.automatiko.engine.workflow.process.core.WorkflowProcess)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Node (io.automatiko.engine.api.definition.process.Node)1 ProcessEventListener (io.automatiko.engine.api.event.process.ProcessEventListener)1 ExpressionEvaluator (io.automatiko.engine.api.expression.ExpressionEvaluator)1 DurationExpirationTime (io.automatiko.engine.api.jobs.DurationExpirationTime)1 ExactExpirationTime (io.automatiko.engine.api.jobs.ExactExpirationTime)1 ExpirationTime (io.automatiko.engine.api.jobs.ExpirationTime)1 JobsService (io.automatiko.engine.api.jobs.JobsService)1 ProcessJobDescription (io.automatiko.engine.api.jobs.ProcessJobDescription)1