Exemplo n.º 1
0
        /// <summary>
        /// 完成条件判断,根据signalData传递的数据判断当前提交人是否同意,如果有一个提交同意,该任务就结束.同时记录流程变量为true.
        /// </summary>
        /// <param name="parent">当前任务节点的运行实例</param>
        /// <param name="multiInstanceActivity">多任务活动行为</param>
        /// <param name="signalData">提交的变量数据</param>
        /// <returns></returns>
        public override bool CompletionConditionSatisfied(IExecutionEntity parent, MultiInstanceActivityBehavior multiInstanceActivity, object signalData)
        {
            //bool pass = base.CompletionConditionSatisfied(parent, multiInstanceActivity, signalData);

            object passed = parent.GetVariable(CompleteConditionVarName, true);

            if (passed is null || (bool.TryParse(passed.ToString(), out var p) && p))
            {
                //return pass;
                return(true);
            }

            var tf = (signalData as Dictionary <string, object>)[CompleteConditionVarName];

            bool.TryParse(tf?.ToString(), out bool approvaled);

            if (approvaled)
            {
                parent.SetVariable(CompleteConditionVarName, true);
            }
            else
            {
                parent.SetVariable(CompleteConditionVarName, false);
            }

            //return pass || approvaled;
            return(approvaled);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 完成条件判断,根据signalData传递的数据判断当前提交人是否同意,如果有一个提交人不同意,该任务就结束.
        /// </summary>
        /// <param name="parent">当前任务节点的运行实例</param>
        /// <param name="multiInstanceActivity">多任务活动行为</param>
        /// <param name="signalData">提交的变量数据</param>
        /// <returns></returns>
        public override bool CompletionConditionSatisfied(IExecutionEntity parent, MultiInstanceActivityBehavior multiInstanceActivity, object signalData)
        {
            int  nrOfActiveInstances = multiInstanceActivity.GetLoopVariable(parent, MultiInstanceActivityBehavior.NUMBER_OF_ACTIVE_INSTANCES).GetValueOrDefault(0);
            bool pass = base.CompletionConditionSatisfied(parent, multiInstanceActivity, signalData);

            if (pass)
            {
                parent.SetVariable(CompleteConditionVarName, true);
                return(true);
            }

            var tf = (signalData as IDictionary <string, object>)[CompleteConditionVarName];

            if (bool.TryParse(tf?.ToString(), out bool approvaled))
            {
                if (!approvaled)
                {
                    parent.SetVariable(CompleteConditionVarName, false);
                    return(true);
                }

                parent.SetVariable(CompleteConditionVarName, true);
            }

            return(nrOfActiveInstances == 0);
        }
        /// <summary>
        /// 完成条件判断,根据signalData传递的数据加上历史数据判断当半数人员同意就流程就结束,同时记录该流程的终值,半数通过记true否则false.
        /// </summary>
        /// <param name="parent">当前任务节点的运行实例</param>
        /// <param name="multiInstanceActivity">多任务活动行为</param>
        /// <param name="signalData">提交的变量数据</param>
        /// <returns></returns>
        public override bool CompletionConditionSatisfied(IExecutionEntity parent, MultiInstanceActivityBehavior multiInstanceActivity, object signalData)
        {
            bool pass = base.CompletionConditionSatisfied(parent, multiInstanceActivity, signalData);

            if (pass)
            {
                parent.SetVariable(CompleteConditionVarName, true);
                return(true);
            }

            var    config = Context.CommandContext.ProcessEngineConfiguration;
            object passed = parent.GetVariable(CompleteConditionVarName, true);

            if (passed is null || (bool.TryParse(passed.ToString(), out var p) && p))
            {
                return(true);
            }

            var tf = (signalData as IDictionary <string, object>)[CompleteConditionVarName];

            bool.TryParse(tf?.ToString(), out bool approvaled);

            int nrOfInstances = multiInstanceActivity.GetLoopVariable(parent, MultiInstanceActivityBehavior.NUMBER_OF_INSTANCES).GetValueOrDefault(0);

            int nrOfActiveInstances = multiInstanceActivity.GetLoopVariable(parent, MultiInstanceActivityBehavior.NUMBER_OF_ACTIVE_INSTANCES).GetValueOrDefault(0);

            int nrOfCompletedInstances = multiInstanceActivity.GetLoopVariable(parent, MultiInstanceActivityBehavior.NUMBER_OF_COMPLETED_INSTANCES).GetValueOrDefault(0);

            var assigneeType = (LeaveExection.CurrentFlowElement as UserTask).AssigneeType;

            bool halfPassed = AssigneeType.HALF_PASSED.Equals(assigneeType?.Value, StringComparison.OrdinalIgnoreCase);

            int votes = config.HistoryService.CreateHistoricVariableInstanceQuery()
                        .SetProcessInstanceId(LeaveExection.ProcessInstanceId)
                        .VariableValueEquals(CompleteConditionVarName, halfPassed)
                        .List()
                        .Where(x => string.IsNullOrWhiteSpace(x.TaskId) == false)
                        .Count();

            if ((votes + (approvaled & halfPassed ? 1 : !approvaled ? 1 : 0)) >= Math.Ceiling(nrOfInstances / 2M))
            {
                parent.SetVariable(CompleteConditionVarName, true);
                return(true);
            }
            else if (votes + nrOfActiveInstances < Math.Ceiling(nrOfInstances / 2M))
            {
                parent.SetVariable(CompleteConditionVarName, false);
                return(true);
            }
            else if (nrOfActiveInstances == 0)
            {
                parent.SetVariable(CompleteConditionVarName, false);
                return(true);
            }

            return(false);
        }
Exemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="execution"></param>
        public virtual void Initialize(IExecutionEntity execution)
        {
            foreach (Data data in this.dataInputs)
            {
                execution.SetVariable(data.Name, data.Definition.CreateInstance());
            }

            foreach (Data data in this.dataOutputs)
            {
                execution.SetVariable(data.Name, data.Definition.CreateInstance());
            }
        }
Exemplo n.º 5
0
        protected internal virtual void InitializeIoSpecification(IOSpecification activityIoSpecification, IExecutionEntity execution, BpmnModel bpmnModel)
        {
            foreach (DataSpec dataSpec in activityIoSpecification.DataInputs)
            {
                Datas.ItemDefinition itemDefinition = itemDefinitionMap[dataSpec.ItemSubjectRef];
                execution.SetVariable(dataSpec.Id, itemDefinition.CreateInstance());
            }

            foreach (DataSpec dataSpec in activityIoSpecification.DataOutputs)
            {
                Datas.ItemDefinition itemDefinition = itemDefinitionMap[dataSpec.ItemSubjectRef];
                execution.SetVariable(dataSpec.Id, itemDefinition.CreateInstance());
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 侦听接收通知处理
        /// </summary>
        /// <param name="execution"></param>
        public void Notify(IExecutionEntity execution)
        {
            if (execution.CurrentFlowElement is UserTask userTask && userTask.HasMultiInstanceLoopCharacteristics())
            {
                var varName = userTask.LoopCharacteristics.GetCollectionVarName();

                if (execution.GetVariable(varName) == null)
                {
                    List <IUserInfo> users         = new List <IUserInfo>();
                    string           getUserPolicy = userTask.GetUsersPolicy();
                    if (string.IsNullOrWhiteSpace(getUserPolicy) == false)
                    {
                        QueryBookmark[] actors = JsonConvert.DeserializeObject <QueryBookmark[]>(getUserPolicy);

                        IGetBookmarkRuleProvider ruleProvider = ProcessEngineServiceProvider.Resolve <IGetBookmarkRuleProvider>();

                        foreach (QueryBookmark query in actors)
                        {
                            IGetBookmarkRule rule = ruleProvider.CreateBookmarkRule(query.RuleType.ToString());
                            rule.Execution = execution;
                            rule.Condition = query;
                            users.AddRange(Context.ProcessEngineConfiguration.CommandExecutor.Execute(rule));
                        }
                    }

                    //if (users.Count == 0)
                    //{
                    //    throw new NoneCountersignUsersException(execution.CurrentFlowElement.Name);
                    //}

                    execution.SetVariable(varName, users.Count == 0 ? new string[] { "" } : users.Select(x => x.Id).Distinct().ToArray());
                }
            }
        }
        protected internal override object Execute(ICommandContext commandContext, IExecutionEntity execution)
        {
            if (variables is null || variables.Count == 0)
            {
                return(null);
            }

            if (isLocal)
            {
                foreach (string variableName in variables.Keys)
                {
                    execution.SetVariableLocal(variableName, variables[variableName], false);
                }
            }
            else
            {
                foreach (string variableName in variables.Keys)
                {
                    execution.SetVariable(variableName, variables[variableName], false);
                }
            }

            // ACT-1887: Force an update of the execution's revision to prevent
            // simultaneous inserts of the same
            // variable. If not, duplicate variables may occur since optimistic
            // locking doesn't work on inserts
            execution.ForceUpdate();

            return(null);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Handles the parallel case of spawning the instances. Will create child executions accordingly for every instance needed.
        /// </summary>
        protected internal override int CreateInstances(IExecutionEntity execution)
        {
            int nrOfInstances = ResolveNrOfInstances(execution);

            if (nrOfInstances < 0)
            {
                throw new ActivitiIllegalArgumentException("Invalid number of instances: must be non-negative integer value" + ", but was " + nrOfInstances);
            }

            execution.IsMultiInstanceRoot = true;

            SetLoopVariable(execution, NUMBER_OF_INSTANCES, nrOfInstances);
            SetLoopVariable(execution, NUMBER_OF_COMPLETED_INSTANCES, 0);
            SetLoopVariable(execution, NUMBER_OF_ACTIVE_INSTANCES, nrOfInstances);

            IList <IExecutionEntity> concurrentExecutions = new List <IExecutionEntity>();

            for (int loopCounter = 0; loopCounter < nrOfInstances; loopCounter++)
            {
                IExecutionEntity concurrentExecution = Context.CommandContext.ExecutionEntityManager.CreateChildExecution(execution);
                concurrentExecution.CurrentFlowElement = activity;
                concurrentExecution.IsActive           = true;
                concurrentExecution.IsScope            = false;

                concurrentExecutions.Add(concurrentExecution);
                LogLoopDetails(concurrentExecution, "initialized", loopCounter, 0, nrOfInstances, nrOfInstances);
            }

            // Before the activities are executed, all executions MUST be created up front
            // Do not try to merge this loop with the previous one, as it will lead
            // to bugs, due to possible child execution pruning.
            for (int loopCounter = 0; loopCounter < nrOfInstances; loopCounter++)
            {
                IExecutionEntity concurrentExecution = concurrentExecutions[loopCounter];
                // executions can be inactive, if instances are all automatics
                // (no-waitstate) and completionCondition has been met in the meantime
                if (concurrentExecution.IsActive && !concurrentExecution.Ended && concurrentExecution.Parent.IsActive && !concurrentExecution.Parent.Ended)
                {
                    SetLoopVariable(concurrentExecution, CollectionElementIndexVariable, loopCounter);
                    ExecuteOriginalBehavior(concurrentExecution, loopCounter);
                }
            }

            // See ACT-1586: ExecutionQuery returns wrong results when using multi
            // instance on a receive task The parent execution must be set to false, so it wouldn't show up in
            // the execution query when using .activityId(something). Do not we cannot nullify the
            // activityId (that would have been a better solution), as it would break boundary event behavior.
            if (concurrentExecutions.Count > 0)
            {
                IExecutionEntity executionEntity = execution;
                executionEntity.IsActive = false;
            }

            if (!string.IsNullOrWhiteSpace(completedPolicy.CompleteConditionVarName))
            {
                execution.SetVariable(completedPolicy.CompleteConditionVarName, false);
            }

            return(nrOfInstances);
        }
        public override void Evaluate(IExecutionEntity execution)
        {
            MessageInstance message = (MessageInstance)execution.GetVariable(WebServiceActivityBehavior.CURRENT_MESSAGE);

            if (message.StructureInstance is FieldBaseStructureInstance)
            {
                FieldBaseStructureInstance structure = (FieldBaseStructureInstance)message.StructureInstance;
                execution.SetVariable(this.Target, structure.GetFieldValue(this.Source));
            }
        }
Exemplo n.º 10
0
        public override void Execute(IExecutionEntity execution)
        {
            try
            {
                bool isSkipExpressionEnabled = SkipExpressionUtil.IsSkipExpressionEnabled(execution, skipExpression);
                if (!isSkipExpressionEnabled || (isSkipExpressionEnabled && !SkipExpressionUtil.ShouldSkipFlowElement(execution, skipExpression)))
                {
                    if (Context.ProcessEngineConfiguration.EnableProcessDefinitionInfoCache)
                    {
                        JToken taskElementProperties = Context.GetBpmnOverrideElementProperties(serviceTaskId, execution.ProcessDefinitionId);
                        if (taskElementProperties != null && taskElementProperties[DynamicBpmnConstants.SERVICE_TASK_EXPRESSION] != null)
                        {
                            string overrideExpression = taskElementProperties[DynamicBpmnConstants.SERVICE_TASK_EXPRESSION].ToString();
                            if (!string.IsNullOrWhiteSpace(overrideExpression) && !overrideExpression.Equals(expression.ExpressionText))
                            {
                                expression = Context.ProcessEngineConfiguration.ExpressionManager.CreateExpression(overrideExpression);
                            }
                        }
                    }

                    object value = expression.GetValue(execution);
                    if (!(resultVariable is null))
                    {
                        execution.SetVariable(resultVariable, value);
                    }
                }

                Leave(execution);
            }
            catch (Exception exc)
            {
                Exception cause = exc;
                BpmnError error = null;
                while (cause != null)
                {
                    if (cause is BpmnError)
                    {
                        error = (BpmnError)cause;
                        break;
                    }
                    cause = cause.InnerException;
                }

                if (error != null)
                {
                    ErrorPropagation.PropagateError(error, execution);
                }
                else
                {
                    throw new ActivitiException("Could not execute service task expression", exc);
                }
            }
        }
Exemplo n.º 11
0
        public virtual void ExecuteCommand(IExecutionEntity execution)
        {
            if (argList != null && argList.Count > 0)
            {
                //ProcessBuilder processBuilder = new ProcessBuilder(argList);
                //processBuilder.redirectErrorStream(RedirectErrorFlag);
                //if (CleanEnvBoolean.Value)
                //{
                //    IDictionary<string, string> env = processBuilder.environment();
                //    env.Clear();
                //}
                //if (!string.ReferenceEquals(DirectoryStr, null) && DirectoryStr.Length > 0)
                //{
                //    processBuilder.directory(new File(DirectoryStr));
                //}
                var     psi     = new ProcessStartInfo();
                Process process = new Process()
                {
                    StartInfo = psi
                };//processBuilder.start();

                if (WaitFlag.Value)
                {
                    int errorCode = 0;

                    process.WaitForExit();

                    if (ResultVariableStr is object)
                    {
                        string result = process.StandardOutput.ReadToEnd(); //convertStreamToStr(process.StandardOutput);
                        execution.SetVariable(ResultVariableStr, result);
                    }

                    if (ErrorCodeVariableStr is object)
                    {
                        execution.SetVariable(ErrorCodeVariableStr, Convert.ToString(errorCode));
                    }
                }
            }
        }
        /// <summary>
        /// 侦听接收通知处理
        /// </summary>
        /// <param name="execution"></param>
        public void Notify(IExecutionEntity execution)
        {
            if (execution.CurrentFlowElement is UserTask userTask && userTask.HasMultiInstanceLoopCharacteristics())
            {
                var varName = userTask.LoopCharacteristics.GetCollectionVarName();

                if (execution.GetVariable(varName) == null)
                {
                    List <IUserInfo> users         = new List <IUserInfo>();
                    string           getUserPolicy = userTask.GetUsersPolicy();
                    if (string.IsNullOrWhiteSpace(getUserPolicy) == false)
                    {
                        if (EXPR_PATTERN.IsMatch(getUserPolicy))
                        {
                            getUserPolicy = EXPR_PATTERN.Replace(getUserPolicy, (m) =>
                            {
                                var value     = m.Groups[1].Value;
                                var variables = execution.Variables;
                                object roles  = ExpressionManager.GetValue(variables, value, variables);
                                return(roles.ToString());
                            });
                        }

                        QueryBookmark[] actors = JsonConvert.DeserializeObject <QueryBookmark[]>(getUserPolicy);

                        IGetBookmarkRuleProvider ruleProvider = ProcessEngineServiceProvider.Resolve <IGetBookmarkRuleProvider>();

                        foreach (QueryBookmark query in actors)
                        {
                            IGetBookmarkRule rule = ruleProvider.CreateBookmarkRule(query.RuleType.ToString());
                            rule.Execution = execution;
                            rule.Condition = query;
                            var us = Context.ProcessEngineConfiguration.CommandExecutor.Execute(rule);
                            users.AddRange(us);
                        }
                    }

                    if (users.Count == 0)
                    {
                        users.Add(Authentication.AuthenticatedUser);
                        logger.LogWarning($"调用查询人员服务失败,分组没有人,重新指到当前提交人,Duty={getUserPolicy}");
                        //throw new NoneCountersignUsersException(execution.CurrentFlowElement.Name);
                    }

                    execution.SetVariable(varName, users.Count == 0 ? new string[] { "" } : users.Select(x => x.Id).Distinct().ToArray());
                }
            }
        }
        public override void Execute(IExecutionEntity execution)
        {
            ScriptingEngines scriptingEngines = Context.ProcessEngineConfiguration.ScriptingEngines;

            if (Context.ProcessEngineConfiguration.EnableProcessDefinitionInfoCache)
            {
                JToken taskElementProperties = Context.GetBpmnOverrideElementProperties(scriptTaskId, execution.ProcessDefinitionId);
                if (taskElementProperties != null && taskElementProperties[DynamicBpmnConstants.SCRIPT_TASK_SCRIPT] != null)
                {
                    string overrideScript = taskElementProperties[DynamicBpmnConstants.SCRIPT_TASK_SCRIPT].ToString();
                    if (!string.IsNullOrWhiteSpace(overrideScript) && !overrideScript.Equals(script))
                    {
                        script = overrideScript;
                    }
                }
            }

            bool noErrors = true;

            try
            {
                object result = scriptingEngines.Evaluate(script, execution);

                if (!(resultVariable is null))
                {
                    execution.SetVariable(resultVariable, result);
                }
            }
            catch (ActivitiException e)
            {
                logger.LogWarning("Exception while executing " + execution.CurrentFlowElement.Id + " : " + e.Message);

                noErrors = false;
                if (e is BpmnError)
                {
                    ErrorPropagation.PropagateError((BpmnError)e, execution);
                }
                else
                {
                    throw e;
                }
            }
            if (noErrors)
            {
                Leave(execution);
            }
        }
Exemplo n.º 14
0
        private void ExecuteGet(IExecutionEntity execution, string url, object request, string dataObj, IHttpClientProxy httpProxy)
        {
            url = QueryParameter(execution, url, request, true);

            if (string.IsNullOrWhiteSpace(dataObj))
            {
                httpProxy.GetAsync(url).GetAwaiter().GetResult();
            }
            else
            {
                HttpResponseMessage response = httpProxy.GetAsync <HttpResponseMessage>(url, CancellationToken.None).GetAwaiter().GetResult();

                response.EnsureSuccessStatusCode();
                object data = ToObject(response).GetAwaiter().GetResult();

                execution.SetVariable(dataObj, data);
            }
        }
Exemplo n.º 15
0
        private void ExecuteGet(IExecutionEntity execution, string url, object request, string dataObj, IHttpClientProxy httpProxy)
        {
            url = QueryParameter(execution, url, request, true);

            if (string.IsNullOrWhiteSpace(dataObj))
            {
                AsyncHelper.RunSync(() => httpProxy.GetAsync(url));
            }
            else
            {
                HttpResponseMessage response = AsyncHelper.RunSync(() => httpProxy.GetAsync <HttpResponseMessage>(url, CancellationToken.None));

                object data = null;
                if (response is null == false)
                {
                    response.EnsureSuccessStatusCode();
                    data = AsyncHelper.RunSync(() => ToObject(response));
                }

                execution.SetVariable(dataObj, data);
            }
        }
Exemplo n.º 16
0
        private void ExecuteDebugMode(IExecutionEntity execution)
        {
            execution.CurrentFlowElement.ExtensionElements.TryGetValue(BpmnXMLConstants.ELEMENT_EXTENSIONS_PROPERTY,
                                                                       out IList <ExtensionElement> pElements);

            if (pElements != null)
            {
                var parameter = new WebApiParameter(execution, pElements);

                string dataObj = parameter.VariableName;
                if (!string.IsNullOrEmpty(dataObj))
                {
                    try
                    {
                        execution.SetVariable(dataObj, parameter.MockData);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"调用服务失败MockData=${dataObj}\r\n${ex.Message}${ex.StackTrace}");
                        string errorCode = execution.CurrentFlowElement.GetExtensionElementAttributeValue("errorCode");

                        BpmnError error;
                        if (string.IsNullOrWhiteSpace(errorCode) == false)
                        {
                            error = new BpmnError(errorCode, ex.Message);
                        }
                        else
                        {
                            error = new BpmnError(Context.CommandContext.ProcessEngineConfiguration.WebApiErrorCode, ex.Message);
                        }

                        ErrorPropagation.PropagateError(error, execution);
                    }
                }
            }
        }
Exemplo n.º 17
0
        public virtual void Completing(IExecutionEntity execution, IExecutionEntity subProcessInstance)
        {
            // only data. no control flow available on this execution.

            ExpressionManager expressionManager = Context.ProcessEngineConfiguration.ExpressionManager;

            // copy process variables
            CallActivity callActivity = (CallActivity)execution.CurrentFlowElement;

            foreach (IOParameter ioParameter in callActivity.OutParameters)
            {
                object value = null;
                if (!string.IsNullOrWhiteSpace(ioParameter.SourceExpression))
                {
                    IExpression expression = expressionManager.CreateExpression(ioParameter.SourceExpression.Trim());
                    value = expression.GetValue(subProcessInstance);
                }
                else
                {
                    value = subProcessInstance.GetVariable(ioParameter.Source);
                }
                execution.SetVariable(ioParameter.Target, value);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="execution"></param>
        public override void Evaluate(IExecutionEntity execution)
        {
            object value = this.transformation.GetValue(execution);

            execution.SetVariable(this.Target, value);
        }
Exemplo n.º 19
0
        public virtual object Execute(ICommandContext commandContext)
        {
            lock (syncRoot)
            {
                ProcessEngineConfigurationImpl processEngineConfiguration = commandContext.ProcessEngineConfiguration;
                Interceptor.ICommandExecutor   commandExecutor            = processEngineConfiguration.CommandExecutor;

                ITaskEntity task = commandExecutor.Execute(new GetTaskByIdCmd(currentTaskId)) as ITaskEntity;
                if (task is null)
                {
                    throw new ActivitiObjectNotFoundException(string.Concat("No task found for id '", currentTaskId));
                }

                string           currentExecutionId = task.ExecutionId;
                IExecutionEntity execution          = task.Execution;
                if (execution is null)
                {
                    throw new ActivitiObjectNotFoundException(string.Concat("No execution found for id '", currentExecutionId));
                }

                var flowElement = ProcessDefinitionUtil.GetFlowElement(execution.ProcessDefinitionId, returnToActivityId);
                if (flowElement is null)
                {
                    throw new ActivitiObjectNotFoundException(string.Concat("No execution found for id '", currentExecutionId, "'"));
                }

                IHistoricActivityInstanceEntity hisInst = processEngineConfiguration.HistoryService.CreateHistoricActivityInstanceQuery()
                                                          .SetProcessInstanceId(execution.ProcessInstanceId)
                                                          .SetActivityId(returnToActivityId)
                                                          .OrderByHistoricActivityInstanceStartTime()
                                                          .Desc()
                                                          .List()
                                                          .FirstOrDefault() as IHistoricActivityInstanceEntity;

                IExecutionEntityManager executionEntityManager = commandContext.ExecutionEntityManager;

                IExecutionEntity returnToExec = executionEntityManager.CreateChildExecution(execution.ProcessInstance);
                returnToExec.CurrentFlowElement = flowElement;
                foreach (var key in variables.Keys)
                {
                    returnToExec.SetVariable(key, variables[key]);
                }

                executionEntityManager.Insert(returnToExec);

                commandContext.Agenda.PlanContinueProcessOperation(returnToExec);

                IExecutionEntity miRoot = commandExecutor.Execute(new GetMultiInstanceRootExecutionCmd(execution));

                List <ITask> tasks = new List <ITask>();
                if (miRoot != null)
                {
                    ITaskQuery query = commandContext.ProcessEngineConfiguration.TaskService.CreateTaskQuery();

                    IEnumerable <IExecutionEntity> childExecutions = commandExecutor.Execute(new GetChildExecutionsCmd(miRoot));

                    query.SetExecutionIdIn(childExecutions.Select(x => x.Id).ToArray());

                    tasks.AddRange(query.List());
                }
                else
                {
                    tasks.Add(task);
                }

                DeleteTasks(commandContext, commandExecutor, miRoot != null ? miRoot : execution, executionEntityManager, tasks);

                return(null);
            }
        }
Exemplo n.º 20
0
        public virtual IProcessInstance CreateAndStartProcessInstanceWithInitialFlowElement(IProcessDefinition processDefinition, string businessKey, string processInstanceName, FlowElement initialFlowElement, Process process, IDictionary <string, object> variables, IDictionary <string, object> transientVariables, bool startProcessInstance)
        {
            ICommandContext commandContext = Context.CommandContext;

            // Create the process instance
            string initiatorVariableName = null;

            if (initialFlowElement is StartEvent)
            {
                initiatorVariableName = ((StartEvent)initialFlowElement).Initiator;
            }

            IExecutionEntity processInstance = commandContext.ExecutionEntityManager.CreateProcessInstanceExecution(processDefinition, businessKey, processDefinition.TenantId, initiatorVariableName);

            commandContext.HistoryManager.RecordProcessInstanceStart(processInstance, initialFlowElement);

            processInstance.Variables = ProcessDataObjects(process.DataObjects);

            if (string.IsNullOrWhiteSpace(businessKey) == false)
            {
                processInstance.SetVariable(WorkflowVariable.GLOBAL_PROCESSINSTANCE_BUSINESSKEY_VARNAME, businessKey);
            }

            // Set the variables passed into the start command
            if (variables != null)
            {
                foreach (string varName in variables.Keys)
                {
                    processInstance.SetVariable(varName, variables[varName]);
                }
            }

            if (transientVariables != null)
            {
                foreach (string varName in transientVariables.Keys)
                {
                    processInstance.SetTransientVariable(varName, transientVariables[varName]);
                }
            }

            // Set processInstance name
            if (!(processInstanceName is null))
            {
                processInstance.Name = processInstanceName;
                commandContext.HistoryManager.RecordProcessInstanceNameChange(processInstance.Id, processInstanceName);
            }

            // Fire events
            if (Context.ProcessEngineConfiguration.EventDispatcher.Enabled)
            {
                Context.ProcessEngineConfiguration.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityWithVariablesEvent(ActivitiEventType.ENTITY_INITIALIZED, processInstance, variables, false));
            }

            // Create the first execution that will visit all the process definition elements
            IExecutionEntity execution = commandContext.ExecutionEntityManager.CreateChildExecution(processInstance);

            execution.CurrentFlowElement = initialFlowElement;

            if (startProcessInstance)
            {
                this.StartProcessInstance(processInstance, commandContext, variables);
            }

            return(processInstance);
        }
Exemplo n.º 21
0
        /// <summary>
        ///
        /// </summary>
        public virtual IProcessInstance CreateAndStartProcessInstanceWithInitialFlowElement(IProcessDefinition processDefinition, string businessKey, string processInstanceName, FlowElement initialFlowElement, Process process, IDictionary <string, object> variables, IDictionary <string, object> transientVariables, bool startProcessInstance)
        {
            ICommandContext commandContext = Context.CommandContext;

            // Create the process instance
            string initiatorVariableName = null;

            if (initialFlowElement is StartEvent)
            {
                initiatorVariableName = ((StartEvent)initialFlowElement).Initiator;
            }

            IExecutionEntity processInstance = commandContext.ExecutionEntityManager.CreateProcessInstanceExecution(processDefinition, businessKey, processDefinition.TenantId, initiatorVariableName);

            commandContext.HistoryManager.RecordProcessInstanceStart(processInstance, initialFlowElement);

            processInstance.Variables = ProcessDataObjects(process.DataObjects);

            if (string.IsNullOrWhiteSpace(businessKey) == false)
            {
                processInstance.SetVariable(WorkflowVariable.GLOBAL_PROCESSINSTANCE_BUSINESSKEY_VARNAME, businessKey);
            }

            var title = process.GetExtensionElementAttributeValue(WorkflowVariable.GLOBAL_PROCESSINSTANCE_TITLE);

            if (string.IsNullOrWhiteSpace(title) == false)
            {
                var reg = new Regex(@"(\$\{)(.*?)(}{1,1})", RegexOptions.Multiline);
                title = reg.Replace(title, (m) =>
                {
                    return(ExpressionEvaluator.GetValue(variables, m.Groups[2].Value)?.ToString());
                });
                processInstance.SetVariable(WorkflowVariable.GLOBAL_PROCESSINSTANCE_TITLE, title);
            }
            else
            {
                processInstance.SetVariable(WorkflowVariable.GLOBAL_PROCESSINSTANCE_TITLE, process.Name);
            }

            // Set the variables passed into the start command
            if (variables != null)
            {
                foreach (string varName in variables.Keys)
                {
                    processInstance.SetVariable(varName, variables[varName]);
                }
            }

            if (transientVariables != null)
            {
                foreach (string varName in transientVariables.Keys)
                {
                    processInstance.SetTransientVariable(varName, transientVariables[varName]);
                }
            }

            // Set processInstance name
            if (title is object)
            {
                processInstance.Name = title;
                commandContext.HistoryManager.RecordProcessInstanceNameChange(processInstance.Id, title);
            }
            else if (processInstanceName is object)
            {
                processInstance.Name = processInstanceName;
                commandContext.HistoryManager.RecordProcessInstanceNameChange(processInstance.Id, processInstanceName);
            }

            // Fire events
            if (Context.ProcessEngineConfiguration.EventDispatcher.Enabled)
            {
                Context.ProcessEngineConfiguration.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityWithVariablesEvent(ActivitiEventType.ENTITY_INITIALIZED, processInstance, variables, false));
            }

            // Create the first execution that will visit all the process definition elements
            IExecutionEntity execution = commandContext.ExecutionEntityManager.CreateChildExecution(processInstance);

            execution.CurrentFlowElement = initialFlowElement;

            if (startProcessInstance)
            {
                this.StartProcessInstance(processInstance, commandContext, variables);
            }

            return(processInstance);
        }
Exemplo n.º 22
0
        public override void Execute(IExecutionEntity execution)
        {
            BpmnModel               bpmnModel   = ProcessDefinitionUtil.GetBpmnModel(execution.ProcessDefinitionId);
            FlowElement             flowElement = execution.CurrentFlowElement;
            IOSpecification         ioSpecification;
            string                  operationRef;
            IList <DataAssociation> dataInputAssociations;
            IList <DataAssociation> dataOutputAssociations;

            if (flowElement is SendTask sendTask)
            {
                ioSpecification        = sendTask.IoSpecification;
                operationRef           = sendTask.OperationRef;
                dataInputAssociations  = sendTask.DataInputAssociations;
                dataOutputAssociations = sendTask.DataOutputAssociations;
            }
            else if (flowElement is ServiceTask serviceTask)
            {
                ioSpecification        = serviceTask.IoSpecification;
                operationRef           = serviceTask.OperationRef;
                dataInputAssociations  = serviceTask.DataInputAssociations;
                dataOutputAssociations = serviceTask.DataOutputAssociations;
            }
            else
            {
                throw new ActivitiException("Unsupported flow element type " + flowElement);
            }

            MessageInstance message = null;

            FillDefinitionMaps(bpmnModel);

            Webservice.Operation operation = operationMap[operationRef];

            try
            {
                if (ioSpecification != null)
                {
                    InitializeIoSpecification(ioSpecification, execution, bpmnModel);
                    if (ioSpecification.DataInputRefs.Count > 0)
                    {
                        string       firstDataInputName = ioSpecification.DataInputRefs[0];
                        ItemInstance inputItem          = (ItemInstance)execution.GetVariable(firstDataInputName);
                        message = new MessageInstance(operation.InMessage, inputItem);
                    }
                }
                else
                {
                    message = operation.InMessage.CreateInstance();
                }

                execution.SetVariable(CURRENT_MESSAGE, message);

                FillMessage(dataInputAssociations, execution);

                ProcessEngineConfigurationImpl processEngineConfig = Context.ProcessEngineConfiguration;
                MessageInstance receivedMessage = operation.SendMessage(message, processEngineConfig.WsOverridenEndpointAddresses);

                execution.SetVariable(CURRENT_MESSAGE, receivedMessage);

                if (ioSpecification != null && ioSpecification.DataOutputRefs.Count > 0)
                {
                    string firstDataOutputName = ioSpecification.DataOutputRefs[0];
                    if (!(firstDataOutputName is null))
                    {
                        ItemInstance outputItem = (ItemInstance)execution.GetVariable(firstDataOutputName);
                        outputItem.StructureInstance.LoadFrom(receivedMessage.StructureInstance.ToArray());
                    }
                }

                ReturnMessage(dataOutputAssociations, execution);

                execution.SetVariable(CURRENT_MESSAGE, null);
                Leave(execution);
            }
            catch (Exception exc)
            {
                Exception cause = exc;
                BpmnError error = null;
                while (cause != null)
                {
                    if (cause is BpmnError)
                    {
                        error = (BpmnError)cause;
                        break;
                    }
                    cause = cause.InnerException;
                }

                if (error != null)
                {
                    ErrorPropagation.PropagateError(error, execution);
                }
                else if (exc is Exception)
                {
                    throw (Exception)exc;
                }
            }
        }