Example #1
0
        protected internal virtual void CreateMultiInstanceLoopCharacteristics(BpmnParse bpmnParse, Activity modelActivity)
        {
            MultiInstanceLoopCharacteristics loopCharacteristics = modelActivity.LoopCharacteristics;

            // Activity Behavior
            MultiInstanceActivityBehavior miActivityBehavior;

            if (loopCharacteristics.Sequential)
            {
                miActivityBehavior = bpmnParse.ActivityBehaviorFactory.CreateSequentialMultiInstanceBehavior(modelActivity, (AbstractBpmnActivityBehavior)modelActivity.Behavior);
            }
            else
            {
                miActivityBehavior = bpmnParse.ActivityBehaviorFactory.CreateParallelMultiInstanceBehavior(modelActivity, (AbstractBpmnActivityBehavior)modelActivity.Behavior);
            }

            modelActivity.Behavior = miActivityBehavior;

            ExpressionManager expressionManager = Context.ProcessEngineConfiguration.ExpressionManager;

            // loop cardinality
            if (!string.IsNullOrWhiteSpace(loopCharacteristics.LoopCardinality))
            {
                miActivityBehavior.LoopCardinalityExpression = expressionManager.CreateExpression(loopCharacteristics.LoopCardinality);
            }

            // completion condition
            if (!string.IsNullOrWhiteSpace(loopCharacteristics.CompletionCondition))
            {
                miActivityBehavior.CompletionConditionExpression = expressionManager.CreateExpression(loopCharacteristics.CompletionCondition);
            }

            // activiti:collection
            if (!string.IsNullOrWhiteSpace(loopCharacteristics.InputDataItem))
            {
                if (loopCharacteristics.InputDataItem.Contains("{"))
                {
                    miActivityBehavior.CollectionExpression = expressionManager.CreateExpression(loopCharacteristics.InputDataItem);
                }
                else
                {
                    miActivityBehavior.CollectionVariable = loopCharacteristics.InputDataItem;
                }
            }

            // activiti:elementVariable
            if (!string.IsNullOrWhiteSpace(loopCharacteristics.ElementVariable))
            {
                miActivityBehavior.CollectionElementVariable = loopCharacteristics.ElementVariable;
            }

            // activiti:elementIndexVariable
            if (!string.IsNullOrWhiteSpace(loopCharacteristics.ElementIndexVariable))
            {
                miActivityBehavior.CollectionElementIndexVariable = loopCharacteristics.ElementIndexVariable;
            }
        }
Example #2
0
        protected internal virtual void ParseFormField(Element formField, BpmnParse bpmnParse,
                                                       ExpressionManager expressionManager)
        {
            var formFieldHandler = new FormFieldHandler();

            // parse Id
            var id = formField.GetAttributeValue("id");

            if (ReferenceEquals(id, null) || (id.Length == 0))
            {
                bpmnParse.AddError("attribute id must be set for FormFieldGroup and must have a non-empty value",
                                   formField);
            }
            else
            {
                formFieldHandler.Id = id;
            }

            if (id.Equals(BusinessKeyFieldId))
            {
                formFieldHandler.BusinessKey = true;
            }

            // parse name
            var name = formField.GetAttributeValue("label");

            if (!ReferenceEquals(name, null))
            {
                IExpression nameExpression = (Bpm.Engine.Impl.EL.IExpression)expressionManager.CreateExpression(name);
                formFieldHandler.Label = nameExpression;
            }

            // parse properties
            ParseProperties(formField, formFieldHandler, bpmnParse, expressionManager);

            // parse validation
            ParseValidation(formField, formFieldHandler, bpmnParse, expressionManager);

            // parse type
            var formTypes = FormTypes;
            var formType  = formTypes.ParseFormPropertyType(formField, bpmnParse);

            formFieldHandler.SetType(formType);

            // parse default value
            var defaultValue = formField.GetAttributeValue("defaultValue");

            if (!ReferenceEquals(defaultValue, null))
            {
                IExpression defaultValueExpression = (Bpm.Engine.Impl.EL.IExpression)expressionManager.CreateExpression(defaultValue);
                formFieldHandler.DefaultValueExpression = defaultValueExpression;
            }

            FormFieldHandlers.Add(formFieldHandler);
        }
Example #3
0
 private void ApplyChanges()
 {
     if (m_currentExpression != null)
     {
         if (m_currentExpression.Id != m_exprIdTxt.Text)
         {
             throw new Exception("UI is out of sync with data");
         }
         // apply changes.
         m_mgr.As <ITransactionContext>().DoTransaction(delegate
         {
             m_currentExpression.Label  = m_exprLabelTxt.Text;
             m_currentExpression.Script = m_exprTxt.Text;
         }, "Edit expression".Localize()
                                                        );
         m_numOfOperation++;
     }
     else if (!string.IsNullOrWhiteSpace(m_exprTxt.Text))
     {
         Expression expr = m_mgr.CreateExpression();
         expr.Label  = m_exprLabelTxt.Text;
         expr.Script = m_exprTxt.Text;
         m_mgr.As <ITransactionContext>().DoTransaction(delegate
         {
             m_mgr.Expressions.Add(expr);
         }, "Add expression".Localize()
                                                        );
         m_numOfOperation++;
         SetActiveExpression(expr);
     }
 }
Example #4
0
 /// <summary>
 /// Creates an <seealso cref="IExpression"/> for the <seealso cref="FieldExtension"/>.
 /// </summary>
 public static IExpression CreateExpressionForField(FieldExtension fieldExtension)
 {
     if (!string.IsNullOrWhiteSpace(fieldExtension.Expression))
     {
         ExpressionManager expressionManager = Context.ProcessEngineConfiguration.ExpressionManager;
         return(expressionManager.CreateExpression(fieldExtension.Expression));
     }
     else
     {
         return(new FixedValue(fieldExtension.StringValue));
     }
 }
Example #5
0
 /// <summary>
 ///     Creates a new <seealso cref="ExecutableScript" /> from a source. It excepts static and dynamic sources.
 ///     Dynamic means that the source is an expression which will be evaluated during execution.
 /// </summary>
 /// <param name="language"> the language of the script </param>
 /// <param name="source"> the source code of the script or an expression which evaluates to the source code </param>
 /// <param name="expressionManager"> the expression manager to use to generate the expressions of dynamic scripts </param>
 /// <param name="scriptFactory"> the script factory used to create the script </param>
 /// <returns> the newly created script </returns>
 /// <exception cref="NotValidException"> if language is null or empty or source is null </exception>
 public static ExecutableScript GetScriptFormSource(string language, string source,
                                                    ExpressionManager expressionManager, ScriptFactory scriptFactory)
 {
     EnsureUtil.EnsureNotEmpty(typeof(NotValidException), "Script language", language);
     EnsureUtil.EnsureNotNull(typeof(NotValidException), "Script source", source);
     if (IsDynamicScriptExpression(language, source))
     {
         IExpression sourceExpression = expressionManager.CreateExpression(source);
         return(GetScriptFromSourceExpression(language, sourceExpression, scriptFactory));
     }
     return(GetScriptFromSource(language, source, scriptFactory));
 }
Example #6
0
 protected internal virtual AbstractDataAssociation CreateDataOutputAssociation(DataAssociation dataAssociationElement)
 {
     if (!string.IsNullOrWhiteSpace(dataAssociationElement.SourceRef))
     {
         return(new MessageImplicitDataOutputAssociation(dataAssociationElement.TargetRef, dataAssociationElement.SourceRef));
     }
     else
     {
         ExpressionManager       expressionManager     = Context.ProcessEngineConfiguration.ExpressionManager;
         IExpression             transformation        = expressionManager.CreateExpression(dataAssociationElement.Transformation);
         AbstractDataAssociation dataOutputAssociation = new TransformationDataOutputAssociation(null, dataAssociationElement.TargetRef, transformation);
         return(dataOutputAssociation);
     }
 }
Example #7
0
        protected internal virtual AbstractDataAssociation CreateDataInputAssociation(DataAssociation dataAssociationElement)
        {
            if (dataAssociationElement.Assignments.Count == 0)
            {
                return(new MessageImplicitDataInputAssociation(dataAssociationElement.SourceRef, dataAssociationElement.TargetRef));
            }
            else
            {
                SimpleDataInputAssociation dataAssociation   = new SimpleDataInputAssociation(dataAssociationElement.SourceRef, dataAssociationElement.TargetRef);
                ExpressionManager          expressionManager = Context.ProcessEngineConfiguration.ExpressionManager;

                foreach (Assignment assignmentElement in dataAssociationElement.Assignments)
                {
                    if (!string.IsNullOrWhiteSpace(assignmentElement.From) && !string.IsNullOrWhiteSpace(assignmentElement.To))
                    {
                        IExpression      from       = expressionManager.CreateExpression(assignmentElement.From);
                        IExpression      to         = expressionManager.CreateExpression(assignmentElement.To);
                        Datas.Assignment assignment = new Datas.Assignment(from, to);
                        dataAssociation.AddAssignment(assignment);
                    }
                }
                return(dataAssociation);
            }
        }
        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);
            }
        }
        public override void Execute(IExecutionEntity execution)
        {
            string finalProcessDefinitonKey;

            if (processDefinitionExpression != null)
            {
                finalProcessDefinitonKey = (string)processDefinitionExpression.GetValue(execution);
            }
            else
            {
                finalProcessDefinitonKey = processDefinitonKey;
            }

            IProcessDefinition processDefinition = FindProcessDefinition(finalProcessDefinitonKey, execution.TenantId);

            // Get model from cache
            Process subProcess = ProcessDefinitionUtil.GetProcess(processDefinition.Id);

            if (subProcess == null)
            {
                throw new ActivitiException("Cannot start a sub process instance. Process model " + processDefinition.Name + " (id = " + processDefinition.Id + ") could not be found");
            }

            FlowElement initialFlowElement = subProcess.InitialFlowElement;

            if (initialFlowElement == null)
            {
                throw new ActivitiException("No start element found for process definition " + processDefinition.Id);
            }

            // Do not start a process instance if the process definition is suspended
            if (ProcessDefinitionUtil.IsProcessDefinitionSuspended(processDefinition.Id))
            {
                throw new ActivitiException("Cannot start process instance. Process definition " + processDefinition.Name + " (id = " + processDefinition.Id + ") is suspended");
            }

            ProcessEngineConfigurationImpl processEngineConfiguration = Context.ProcessEngineConfiguration;
            IExecutionEntityManager        executionEntityManager     = Context.CommandContext.ExecutionEntityManager;
            ExpressionManager expressionManager = processEngineConfiguration.ExpressionManager;

            CallActivity callActivity = (CallActivity)execution.CurrentFlowElement;

            string businessKey = null;

            if (!string.IsNullOrWhiteSpace(callActivity.BusinessKey))
            {
                IExpression expression = expressionManager.CreateExpression(callActivity.BusinessKey);
                businessKey = expression.GetValue(execution).ToString();
            }
            else if (callActivity.InheritBusinessKey)
            {
                IExecutionEntity processInstance = executionEntityManager.FindById <IExecutionEntity>(execution.ProcessInstanceId);
                businessKey = processInstance.BusinessKey;
            }

            IExecutionEntity subProcessInstance = Context.CommandContext.ExecutionEntityManager.CreateSubprocessInstance(processDefinition, execution, businessKey);

            Context.CommandContext.HistoryManager.RecordSubProcessInstanceStart(execution, subProcessInstance, initialFlowElement);

            // process template-defined data objects
            IDictionary <string, object> variables = ProcessDataObjects(subProcess.DataObjects);

            if (callActivity.InheritVariables)
            {
                IDictionary <string, object> executionVariables = execution.Variables;
                foreach (KeyValuePair <string, object> entry in executionVariables.SetOfKeyValuePairs())
                {
                    variables[entry.Key] = entry.Value;
                }
            }

            // copy process variables
            foreach (IOParameter ioParameter in callActivity.InParameters)
            {
                object value = null;
                if (!string.IsNullOrWhiteSpace(ioParameter.SourceExpression))
                {
                    IExpression expression = expressionManager.CreateExpression(ioParameter.SourceExpression.Trim());
                    value = expression.GetValue(execution);
                }
                else
                {
                    value = execution.GetVariable(ioParameter.Source);
                }
                variables[ioParameter.Target] = value;
            }

            if (variables.Count > 0)
            {
                InitializeVariables(subProcessInstance, variables);
            }

            // Create the first execution that will visit all the process definition elements
            IExecutionEntity subProcessInitialExecution = executionEntityManager.CreateChildExecution(subProcessInstance);

            subProcessInitialExecution.CurrentFlowElement = initialFlowElement;

            Context.Agenda.PlanContinueProcessOperation(subProcessInitialExecution);

            Context.ProcessEngineConfiguration.EventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateProcessStartedEvent(subProcessInitialExecution, variables, false));
        }
Example #10
0
        protected internal virtual void ParseFormProperties(BpmnParse bpmnParse, ExpressionManager expressionManager,
                                                            Element extensionElement)
        {
            var formTypes = FormTypes;

            var formPropertyElements = extensionElement.ElementsNS(BpmnParse.CamundaBpmnExtensionsNs,
                                                                   FormPropertyElement);

            foreach (var formPropertyElement in formPropertyElements)
            {
                var formPropertyHandler = new FormPropertyHandler();

                var id = formPropertyElement.GetAttributeValue("id");
                if (ReferenceEquals(id, null))
                {
                    bpmnParse.AddError("attribute 'id' is required", formPropertyElement);
                }
                formPropertyHandler.Id = id;

                var name = formPropertyElement.GetAttributeValue("name");
                formPropertyHandler.Name = name;

                var type = formTypes.ParseFormPropertyType(formPropertyElement, bpmnParse);
                formPropertyHandler.SetType(type);

                var requiredText = formPropertyElement.GetAttributeValue("required", "false");
                var required     = bpmnParse.ParseBooleanAttribute(requiredText);
                if (required != null)
                {
                    formPropertyHandler.Required = required.Value;
                }
                else
                {
                    bpmnParse.AddError(
                        "attribute 'required' must be one of {on|yes|true|enabled|active|off|no|false|disabled|inactive}",
                        formPropertyElement);
                }

                var readableText = formPropertyElement.GetAttributeValue("readable", "true");
                var readable     = bpmnParse.ParseBooleanAttribute(readableText);
                if (readable != null)
                {
                    formPropertyHandler.Readable = readable.Value;
                }
                else
                {
                    bpmnParse.AddError(
                        "attribute 'readable' must be one of {on|yes|true|enabled|active|off|no|false|disabled|inactive}",
                        formPropertyElement);
                }

                var writableText = formPropertyElement.GetAttributeValue("writable", "true");
                var writable     = bpmnParse.ParseBooleanAttribute(writableText);
                if (writable != null)
                {
                    formPropertyHandler.Writable = writable.Value;
                }
                else
                {
                    bpmnParse.AddError(
                        "attribute 'writable' must be one of {on|yes|true|enabled|active|off|no|false|disabled|inactive}",
                        formPropertyElement);
                }

                var variableName = formPropertyElement.GetAttributeValue("variable");
                formPropertyHandler.VariableName = variableName;

                var expressionText = formPropertyElement.GetAttributeValue("expression");
                if (!ReferenceEquals(expressionText, null))
                {
                    IExpression expression = (Bpm.Engine.Impl.EL.IExpression)expressionManager.CreateExpression(expressionText);
                    formPropertyHandler.VariableExpression = expression;
                }

                var defaultExpressionText = formPropertyElement.GetAttributeValue("default");
                if (!ReferenceEquals(defaultExpressionText, null))
                {
                    IExpression defaultExpression = (Bpm.Engine.Impl.EL.IExpression)expressionManager.CreateExpression(defaultExpressionText);
                    formPropertyHandler.DefaultExpression = defaultExpression;
                }

                FormPropertyHandlers.Add(formPropertyHandler);
            }
        }
Example #11
0
        public virtual void TestDecoratePriorityFromVariable()
        {
            // given
            var aPriority = 10;

            taskService.SetVariable(Task.Id, "priority", aPriority);

            var priorityExpression = ExpressionManager.CreateExpression("${priority}");

            TaskDefinition.PriorityExpression = priorityExpression;

            // when
            Decorate(Task, TaskDecorator);

            // then
            Assert.AreEqual(aPriority, Task.Priority);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="execution"></param>
        public override void Execute(IExecutionEntity execution)
        {
            ICommandContext    commandContext    = Context.CommandContext;
            ITaskEntityManager taskEntityManager = commandContext.TaskEntityManager;

            //如果当前任务为补偿任务,则修改任务的父级为流程实例
            if ((execution.CurrentFlowElement as UserTask).ForCompensation)
            {
                execution.Parent = execution.ProcessInstance;
            }

            ITaskEntity task = taskEntityManager.Create();

            task.Execution         = execution;
            task.TaskDefinitionKey = userTask.Id;
            task.IsRuntimeAssignee();

            task.CanTransfer  = userTask.CanTransfer;
            task.OnlyAssignee = task.OnlyAssignee;

            ProcessEngineConfigurationImpl processEngineConfiguration = Context.ProcessEngineConfiguration;
            ExpressionManager expressionManager = processEngineConfiguration.ExpressionManager;

            string         activeTaskName;
            string         activeTaskDescription;
            string         activeTaskDueDate;
            string         activeTaskCategory;
            string         activeTaskSkipExpression;
            string         activeTaskPriority;
            string         activeTaskFormKey;
            string         activeTaskAssignee;
            string         activeTaskOwner;
            IList <string> activeTaskCandidateUsers;
            IList <string> activeTaskCandidateGroups;

            if (Context.ProcessEngineConfiguration.EnableProcessDefinitionInfoCache)
            {
                JToken taskElementProperties = Context.GetBpmnOverrideElementProperties(userTask.Id, execution.ProcessDefinitionId);
                activeTaskName            = GetActiveValue(userTask.Name, DynamicBpmnConstants.USER_TASK_NAME, taskElementProperties);
                activeTaskDescription     = GetActiveValue(userTask.Documentation, DynamicBpmnConstants.USER_TASK_DESCRIPTION, taskElementProperties);
                activeTaskDueDate         = GetActiveValue(userTask.DueDate, DynamicBpmnConstants.USER_TASK_DUEDATE, taskElementProperties);
                activeTaskPriority        = GetActiveValue(userTask.Priority, DynamicBpmnConstants.USER_TASK_PRIORITY, taskElementProperties);
                activeTaskCategory        = GetActiveValue(userTask.Category, DynamicBpmnConstants.USER_TASK_CATEGORY, taskElementProperties);
                activeTaskFormKey         = GetActiveValue(userTask.FormKey, DynamicBpmnConstants.USER_TASK_FORM_KEY, taskElementProperties);
                activeTaskSkipExpression  = GetActiveValue(userTask.SkipExpression, DynamicBpmnConstants.TASK_SKIP_EXPRESSION, taskElementProperties);
                activeTaskAssignee        = GetActiveValue(userTask.Assignee, DynamicBpmnConstants.USER_TASK_ASSIGNEE, taskElementProperties);
                activeTaskOwner           = GetActiveValue(userTask.Owner, DynamicBpmnConstants.USER_TASK_OWNER, taskElementProperties);
                activeTaskCandidateUsers  = GetActiveValueList(userTask.CandidateUsers, DynamicBpmnConstants.USER_TASK_CANDIDATE_USERS, taskElementProperties);
                activeTaskCandidateGroups = GetActiveValueList(userTask.CandidateGroups, DynamicBpmnConstants.USER_TASK_CANDIDATE_GROUPS, taskElementProperties);
            }
            else
            {
                activeTaskName            = userTask.Name;
                activeTaskDescription     = userTask.Documentation;
                activeTaskDueDate         = userTask.DueDate;
                activeTaskPriority        = userTask.Priority;
                activeTaskCategory        = userTask.Category;
                activeTaskFormKey         = userTask.FormKey;
                activeTaskSkipExpression  = userTask.SkipExpression;
                activeTaskAssignee        = userTask.Assignee;
                activeTaskOwner           = userTask.Owner;
                activeTaskCandidateUsers  = userTask.CandidateUsers;
                activeTaskCandidateGroups = userTask.CandidateGroups;
            }

            if (!string.IsNullOrWhiteSpace(activeTaskName))
            {
                string name;
                try
                {
                    name = (string)expressionManager.CreateExpression(activeTaskName).GetValue(execution);
                }
                catch (ActivitiException e)
                {
                    name = activeTaskName;
                    log.LogWarning("property not found in task name expression " + e.Message);
                }
                task.Name = name;
            }

            if (!string.IsNullOrWhiteSpace(activeTaskDescription))
            {
                string description;
                try
                {
                    description = (string)expressionManager.CreateExpression(activeTaskDescription).GetValue(execution);
                }
                catch (ActivitiException e)
                {
                    description = activeTaskDescription;
                    log.LogWarning("property not found in task description expression " + e.Message);
                }
                task.Description = description;
            }

            if (!string.IsNullOrWhiteSpace(activeTaskDueDate))
            {
                object dueDate = expressionManager.CreateExpression(activeTaskDueDate).GetValue(execution);
                if (dueDate != null)
                {
                    if (dueDate is DateTime time)
                    {
                        task.DueDate = time;
                    }
                    else if (dueDate is string @string)
                    {
                        string businessCalendarName;
                        if (!string.IsNullOrWhiteSpace(userTask.BusinessCalendarName))
                        {
                            businessCalendarName = expressionManager.CreateExpression(userTask.BusinessCalendarName).GetValue(execution).ToString();
                        }
                        else
                        {
                            businessCalendarName = DueDateBusinessCalendar.NAME;
                        }

                        IBusinessCalendar businessCalendar = Context.ProcessEngineConfiguration.BusinessCalendarManager.GetBusinessCalendar(businessCalendarName);
                        task.DueDate = businessCalendar.ResolveDuedate(@string);
                    }
                    else
                    {
                        throw new ActivitiIllegalArgumentException("Due date expression does not resolve to a Date or Date string: " + activeTaskDueDate);
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(activeTaskPriority))
            {
                object priority = expressionManager.CreateExpression(activeTaskPriority).GetValue(execution);
                if (priority != null)
                {
                    if (priority is string @string)
                    {
                        try
                        {
                            task.Priority = Convert.ToInt32(@string);
                        }
                        catch (FormatException e)
                        {
                            throw new ActivitiIllegalArgumentException("Priority does not resolve to a number: " + priority, e);
                        }
                    }
                    else if (priority is int || priority is long)
                    {
                        task.Priority = (int)priority;
                    }
                    else
                    {
                        throw new ActivitiIllegalArgumentException("Priority expression does not resolve to a number: " + activeTaskPriority);
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(activeTaskCategory))
            {
                object category = expressionManager.CreateExpression(activeTaskCategory).GetValue(execution);
                if (category != null)
                {
                    if (category is string)
                    {
                        task.Category = category.ToString();
                    }
                    else
                    {
                        throw new ActivitiIllegalArgumentException("Category expression does not resolve to a string: " + activeTaskCategory);
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(activeTaskFormKey))
            {
                object formKey = expressionManager.CreateExpression(activeTaskFormKey).GetValue(execution);
                if (formKey != null)
                {
                    if (formKey is string)
                    {
                        task.FormKey = formKey.ToString();
                    }
                    else
                    {
                        throw new ActivitiIllegalArgumentException("FormKey expression does not resolve to a string: " + activeTaskFormKey);
                    }
                }
            }

            taskEntityManager.Insert(task, execution);

            bool skipUserTask = false;

            if (!string.IsNullOrWhiteSpace(activeTaskSkipExpression))
            {
                IExpression skipExpression = expressionManager.CreateExpression(activeTaskSkipExpression);
                skipUserTask = SkipExpressionUtil.IsSkipExpressionEnabled(execution, skipExpression) && SkipExpressionUtil.ShouldSkipFlowElement(execution, skipExpression);
            }

            // Handling assignments need to be done after the task is inserted, to have an id
            if (!skipUserTask)
            {
                HandleAssignments(taskEntityManager, activeTaskAssignee, activeTaskOwner, activeTaskCandidateUsers, activeTaskCandidateGroups, task, expressionManager, execution);
            }

            processEngineConfiguration.ListenerNotificationHelper.ExecuteTaskListeners(task, BaseTaskListenerFields.EVENTNAME_CREATE);

            // All properties set, now fire events
            if (Context.ProcessEngineConfiguration.EventDispatcher.Enabled)
            {
                IActivitiEventDispatcher eventDispatcher = Context.ProcessEngineConfiguration.EventDispatcher;
                eventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.TASK_CREATED, task));
                if (string.IsNullOrWhiteSpace(task.Assignee) == false)
                {
                    eventDispatcher.DispatchEvent(ActivitiEventBuilder.CreateEntityEvent(ActivitiEventType.TASK_ASSIGNED, task));
                }
            }

            if (skipUserTask)
            {
                taskEntityManager.DeleteTask(task, null, false, false);
                Leave(execution);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="taskEntityManager"></param>
        /// <param name="assignee"></param>
        /// <param name="owner"></param>
        /// <param name="candidateUsers"></param>
        /// <param name="candidateGroups"></param>
        /// <param name="task"></param>
        /// <param name="expressionManager"></param>
        /// <param name="execution"></param>
        protected internal virtual void HandleAssignments(ITaskEntityManager taskEntityManager, string assignee, string owner, IList <string> candidateUsers, IList <string> candidateGroups, ITaskEntity task, ExpressionManager expressionManager, IExecutionEntity execution)
        {
            if (!string.IsNullOrWhiteSpace(assignee))
            {
                object assigneeExpressionValue = expressionManager.CreateExpression(assignee).GetValue(execution);
                string assigneeValue           = null;
                if (assigneeExpressionValue != null)
                {
                    assigneeValue = assigneeExpressionValue.ToString();
                }
                string assigneeUser = null;

                if (string.IsNullOrWhiteSpace(assigneeValue) == false)
                {
                    IUserServiceProxy userService = ProcessEngineServiceProvider.Resolve <IUserServiceProxy>();

                    var user = userService.GetUser(assigneeValue)
                               .ConfigureAwait(false)
                               .GetAwaiter()
                               .GetResult();

                    assigneeUser = user?.FullName;

                    task.SetVariableLocal(assigneeValue, user);
                }
                taskEntityManager.ChangeTaskAssigneeNoEvents(task, assigneeValue, assigneeUser);
            }

            if (!string.IsNullOrWhiteSpace(owner))
            {
                object ownerExpressionValue = expressionManager.CreateExpression(owner).GetValue(execution);
                string ownerValue           = null;
                if (ownerExpressionValue != null)
                {
                    ownerValue = ownerExpressionValue.ToString();
                }

                taskEntityManager.ChangeTaskOwner(task, ownerValue);
            }

            if (candidateGroups != null && candidateGroups.Count > 0)
            {
                foreach (string candidateGroup in candidateGroups)
                {
                    IExpression groupIdExpr = expressionManager.CreateExpression(candidateGroup);
                    object      value       = groupIdExpr.GetValue(execution);
                    if (value is string @string)
                    {
                        IList <string> candidates = ExtractCandidates(@string);
                        task.AddCandidateGroups(candidates);
                    }
                    else if (value is ICollection)
                    {
                        task.AddCandidateGroups((ICollection <string>)value);
                    }
                    else
                    {
                        throw new ActivitiIllegalArgumentException("Expression did not resolve to a string or collection of strings");
                    }
                }
            }

            if (candidateUsers != null && candidateUsers.Count > 0)
            {
                foreach (string candidateUser in candidateUsers)
                {
                    IExpression userIdExpr = expressionManager.CreateExpression(candidateUser);
                    object      value      = userIdExpr.GetValue(execution);
                    if (value is string @string)
                    {
                        IList <string> candidates = ExtractCandidates(@string);
                        task.AddCandidateUsers(candidates);
                    }
                    else if (value is ICollection)
                    {
                        task.AddCandidateUsers((ICollection <string>)value);
                    }
                    else
                    {
                        throw new ActivitiException("Expression did not resolve to a string or collection of strings");
                    }
                }
            }

            if (userTask.CustomUserIdentityLinks != null && userTask.CustomUserIdentityLinks.Count > 0)
            {
                foreach (string customUserIdentityLinkType in userTask.CustomUserIdentityLinks.Keys)
                {
                    foreach (string userIdentityLink in userTask.CustomUserIdentityLinks[customUserIdentityLinkType])
                    {
                        IExpression idExpression = expressionManager.CreateExpression(userIdentityLink);
                        object      value        = idExpression.GetValue(execution);
                        if (value is string @string)
                        {
                            IList <string> userIds = ExtractCandidates(@string);
                            foreach (string userId in userIds)
                            {
                                task.AddUserIdentityLink(userId, customUserIdentityLinkType);
                            }
                        }
                        else if (value is ICollection collection)
                        {
                            IEnumerator userIdSet = collection.GetEnumerator();
                            while (userIdSet.MoveNext())
                            {
                                task.AddUserIdentityLink((string)userIdSet.Current, customUserIdentityLinkType);
                            }
                        }
                        else
                        {
                            throw new ActivitiException("Expression did not resolve to a string or collection of strings");
                        }
                    }
                }
            }

            if (userTask.CustomGroupIdentityLinks != null && userTask.CustomGroupIdentityLinks.Count > 0)
            {
                foreach (string customGroupIdentityLinkType in userTask.CustomGroupIdentityLinks.Keys)
                {
                    foreach (string groupIdentityLink in userTask.CustomGroupIdentityLinks[customGroupIdentityLinkType])
                    {
                        IExpression idExpression = expressionManager.CreateExpression(groupIdentityLink);
                        object      value        = idExpression.GetValue(execution);
                        if (value is string @string)
                        {
                            IList <string> groupIds = ExtractCandidates(@string);
                            foreach (string groupId in groupIds)
                            {
                                task.AddGroupIdentityLink(groupId, customGroupIdentityLinkType);
                            }
                        }
                        else if (value is ICollection collection)
                        {
                            IEnumerator groupIdSet = collection.GetEnumerator();
                            while (groupIdSet.MoveNext())
                            {
                                task.AddGroupIdentityLink((string)groupIdSet.Current, customGroupIdentityLinkType);
                            }
                        }
                        else
                        {
                            throw new ActivitiException("Expression did not resolve to a string or collection of strings");
                        }
                    }
                }
            }
        }
Example #14
0
        /// <summary>
        /// The event definition on which the timer is based.
        ///
        /// Takes in an optional execution, if missing the <seealso cref="NoExecutionVariableScope"/> will be used (eg Timer start event)
        /// </summary>
        public static ITimerJobEntity CreateTimerEntityForTimerEventDefinition(TimerEventDefinition timerEventDefinition, bool isInterruptingTimer, IExecutionEntity executionEntity, string jobHandlerType, string jobHandlerConfig)
        {
            ProcessEngineConfigurationImpl processEngineConfiguration = Context.ProcessEngineConfiguration;

            string            businessCalendarRef = null;
            IExpression       expression          = null;
            ExpressionManager expressionManager   = processEngineConfiguration.ExpressionManager;

            // ACT-1415: timer-declaration on start-event may contain expressions NOT
            // evaluating variables but other context, evaluating should happen nevertheless
            IVariableScope scopeForExpression = executionEntity;

            if (scopeForExpression == null)
            {
                //scopeForExpression = NoExecutionVariableScope.SharedInstance;
            }

            if (!string.IsNullOrWhiteSpace(timerEventDefinition.TimeDate))
            {
                businessCalendarRef = DueDateBusinessCalendar.NAME;
                expression          = expressionManager.CreateExpression(timerEventDefinition.TimeDate);
            }
            else if (!string.IsNullOrWhiteSpace(timerEventDefinition.TimeCycle))
            {
                businessCalendarRef = CycleBusinessCalendar.NAME;
                expression          = expressionManager.CreateExpression(timerEventDefinition.TimeCycle);
            }
            else if (!string.IsNullOrWhiteSpace(timerEventDefinition.TimeDuration))
            {
                businessCalendarRef = DurationBusinessCalendar.NAME;
                expression          = expressionManager.CreateExpression(timerEventDefinition.TimeDuration);
            }

            if (!string.IsNullOrWhiteSpace(timerEventDefinition.CalendarName))
            {
                businessCalendarRef = timerEventDefinition.CalendarName;
                IExpression businessCalendarExpression = expressionManager.CreateExpression(businessCalendarRef);
                businessCalendarRef = businessCalendarExpression.GetValue(scopeForExpression).ToString();
            }

            if (expression == null)
            {
                throw new ActivitiException("Timer needs configuration (either timeDate, timeCycle or timeDuration is needed) (" + timerEventDefinition.Id + ")");
            }

            IBusinessCalendar businessCalendar = processEngineConfiguration.BusinessCalendarManager.GetBusinessCalendar(businessCalendarRef);

            string   dueDateString = null;
            DateTime?duedate       = null;

            object dueDateValue = expression.GetValue(scopeForExpression);

            if (dueDateValue is string)
            {
                dueDateString = (string)dueDateValue;
            }
            else if (dueDateValue is DateTime)
            {
                duedate = (DateTime)dueDateValue;
            }
            else if (dueDateValue is Nullable <DateTime> )
            {
                //JodaTime support
                duedate = (DateTime?)dueDateValue;
            }
            else if (dueDateValue != null)
            {
                throw new ActivitiException("Timer '" + executionEntity.ActivityId + "' was not configured with a valid duration/time, either hand in a java.util.Date or a String in format 'yyyy-MM-dd'T'hh:mm:ss'");
            }

            if (duedate == null && !string.IsNullOrWhiteSpace(dueDateString))
            {
                duedate = businessCalendar.ResolveDuedate(dueDateString);
            }

            ITimerJobEntity timer = null;

            if (duedate != null)
            {
                timer                         = Context.CommandContext.TimerJobEntityManager.Create();
                timer.JobType                 = JobFields.JOB_TYPE_TIMER;
                timer.Revision                = 1;
                timer.JobHandlerType          = jobHandlerType;
                timer.JobHandlerConfiguration = jobHandlerConfig;
                timer.Exclusive               = true;
                timer.Retries                 = processEngineConfiguration.AsyncExecutorNumberOfRetries;
                timer.Duedate                 = duedate;
                if (executionEntity != null)
                {
                    timer.Execution           = executionEntity;
                    timer.ProcessDefinitionId = executionEntity.ProcessDefinitionId;
                    timer.ProcessInstanceId   = executionEntity.ProcessInstanceId;

                    // Inherit tenant identifier (if applicable)
                    if (!string.IsNullOrWhiteSpace(executionEntity.TenantId))
                    {
                        timer.TenantId = executionEntity.TenantId;
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(timerEventDefinition.TimeCycle))
            {
                // See ACT-1427: A boundary timer with a cancelActivity='true', doesn't need to repeat itself
                bool repeat = !isInterruptingTimer;

                // ACT-1951: intermediate catching timer events shouldn't repeat according to spec
                if (executionEntity != null)
                {
                    FlowElement currentElement = executionEntity.CurrentFlowElement;
                    if (currentElement is IntermediateCatchEvent)
                    {
                        repeat = false;
                    }
                }

                if (repeat)
                {
                    string prepared = PrepareRepeat(dueDateString);
                    timer.Repeat = prepared;
                }
            }

            if (timer != null && executionEntity != null)
            {
                timer.Execution           = executionEntity;
                timer.ProcessDefinitionId = executionEntity.ProcessDefinitionId;

                // Inherit tenant identifier (if applicable)
                if (!string.IsNullOrWhiteSpace(executionEntity.TenantId))
                {
                    timer.TenantId = executionEntity.TenantId;
                }
            }

            return(timer);
        }
Example #15
0
        public virtual IList <FieldDeclaration> CreateFieldDeclarations(IList <FieldExtension> fieldList)
        {
            IList <FieldDeclaration> fieldDeclarations = new List <FieldDeclaration>();

            foreach (FieldExtension fieldExtension in fieldList)
            {
                FieldDeclaration fieldDeclaration = null;
                if (!string.IsNullOrWhiteSpace(fieldExtension.Expression))
                {
                    fieldDeclaration = new FieldDeclaration(fieldExtension.FieldName, typeof(IExpression).FullName, expressionManager.CreateExpression(fieldExtension.Expression));
                }
                else
                {
                    fieldDeclaration = new FieldDeclaration(fieldExtension.FieldName, typeof(IExpression).FullName, new FixedValue(fieldExtension.StringValue));
                }

                fieldDeclarations.Add(fieldDeclaration);
            }
            return(fieldDeclarations);
        }
Example #16
0
 /// <summary>
 /// Checks whether a <seealso cref="String"/> seams to be a composite expression or not. In contrast to an eval expression
 /// is the composite expression also allowed to consist of a combination of literal and eval expressions, e.g.,
 /// "Welcome ${customer.name} to our site".
 ///
 /// Note: If you just want to allow eval expression, then the expression must always start with "#{" or "${".
 /// Use <seealso cref="#isExpression(String)"/> to conduct these kind of checks.
 ///
 /// </summary>
 public static bool IsCompositeExpression(string text, ExpressionManager expressionManager)
 {
     return(!expressionManager.CreateExpression(text).LiteralText);
 }