@Override
  public Void execute(CommandContext commandContext) {
    if (currentTaskEntity != null) {

      ExecutionEntity execution =
          commandContext
              .getExecutionEntityManager()
              .findExecutionById(currentTaskEntity.getExecutionId());
      execution.setActivity(activity);
      execution.performOperation(AtomicOperation.TRANSITION_CREATE_SCOPE);

      if (variables != null) {
        if (currentTaskEntity.getExecutionId() != null) {
          currentTaskEntity.setExecutionVariables(variables);
        } else {
          currentTaskEntity.setVariables(variables);
        }
      }
      // 删除当前的任务,不能删除当前正在执行的任务,所以要先清除掉关联
      Context.getCommandContext()
          .getTaskEntityManager()
          .deleteTask(currentTaskEntity, TaskEntity.DELETE_REASON_DELETED, false);
    }
    return null;
  }
Beispiel #2
0
  protected Object execute(CommandContext commandContext, ExecutionEntity execution) {
    if (execution.getActivity().getActivityBehavior() instanceof UserTaskActivityBehavior)
      throw new ActivitiException("UserTask:" + execution.getId() + " should not be signalled.");

    if (processVariables != null) {
      execution.setVariables(processVariables);
    }
    execution.signal(signalName, signalData);
    return null;
  }
Beispiel #3
0
  /** 根据任务历史,创建待办任务. */
  public void processHistoryTask(
      HistoricTaskInstanceEntity historicTaskInstanceEntity,
      HistoricActivityInstanceEntity historicActivityInstanceEntity) {
    /*
     * historicTaskInstanceEntity.setEndTime(null); historicTaskInstanceEntity.setDurationInMillis(null);
     * historicActivityInstanceEntity.setEndTime(null); historicActivityInstanceEntity.setDurationInMillis(null);
     */

    // 创建新任务
    TaskEntity task = TaskEntity.create(new Date());
    task.setProcessDefinitionId(historicTaskInstanceEntity.getProcessDefinitionId());
    // task.setId(historicTaskInstanceEntity.getId());
    // task.setAssigneeWithoutCascade(historicTaskInstanceEntity.getAssignee());
    task.setAssigneeWithoutCascade(this.userId);
    task.setParentTaskIdWithoutCascade(historicTaskInstanceEntity.getParentTaskId());
    task.setNameWithoutCascade(historicTaskInstanceEntity.getName());
    task.setTaskDefinitionKey(historicTaskInstanceEntity.getTaskDefinitionKey());
    task.setExecutionId(historicTaskInstanceEntity.getExecutionId());
    task.setPriority(historicTaskInstanceEntity.getPriority());
    task.setProcessInstanceId(historicTaskInstanceEntity.getProcessInstanceId());
    task.setExecutionId(historicTaskInstanceEntity.getExecutionId());
    task.setDescriptionWithoutCascade(historicTaskInstanceEntity.getDescription());
    task.setTenantId(historicTaskInstanceEntity.getTenantId());

    Context.getCommandContext().getTaskEntityManager().insert(task);

    // 把流程指向任务对应的节点
    ExecutionEntity executionEntity =
        Context.getCommandContext()
            .getExecutionEntityManager()
            .findExecutionById(historicTaskInstanceEntity.getExecutionId());
    executionEntity.setActivity(getActivity(historicActivityInstanceEntity));

    // 创建HistoricActivityInstance
    Context.getCommandContext().getHistoryManager().recordActivityStart(executionEntity);

    // 创建HistoricTaskInstance
    Context.getCommandContext().getHistoryManager().recordTaskCreated(task, executionEntity);
    Context.getCommandContext().getHistoryManager().recordTaskId(task);
    // 更新ACT_HI_ACTIVITY里的assignee字段
    Context.getCommandContext().getHistoryManager().recordTaskAssignment(task);

    try {
      // humanTask
      this.createHumanTask(task, historicTaskInstanceEntity);
    } catch (Exception ex) {
      logger.error(ex.getMessage(), ex);
    }
  }
  public void notify(DelegateExecution execution) throws Exception {
    this.logger.debug("enter the node event listener.." + execution.getId());

    ExecutionEntity ent = (ExecutionEntity) execution;

    if (ent.getActivityId() == null) return;

    String actDefId = ent.getProcessDefinitionId();
    String nodeId = ent.getActivityId();

    execute(execution, actDefId, nodeId);

    String scriptType = getScriptType();

    exeEventScript(execution, scriptType, actDefId, nodeId);
  }
  public void execute(
      JobEntity job,
      String configuration,
      ExecutionEntity execution,
      CommandContext commandContext) {
    ActivityImpl borderEventActivity = execution.getProcessDefinition().findActivity(configuration);

    if (borderEventActivity == null) {
      throw new ActivitiException(
          "Error while firing timer: border event activity " + configuration + " not found");
    }

    try {

      borderEventActivity.getActivityBehavior().execute(execution);

      if (commandContext.getEventDispatcher().isEnabled()) {
        commandContext
            .getEventDispatcher()
            .dispatchEvent(
                ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TIMER_FIRED, job));
      }

    } catch (RuntimeException e) {
      log.error("exception during timer execution", e);
      throw e;

    } catch (Exception e) {
      log.error("exception during timer execution", e);
      throw new ActivitiException("exception during timer execution: " + e.getMessage(), e);
    }
  }
  protected void localize(ProcessInstance processInstance) {
    ExecutionEntity processInstanceExecution = (ExecutionEntity) processInstance;
    processInstanceExecution.setLocalizedName(null);
    processInstanceExecution.setLocalizedDescription(null);

    if (locale != null) {
      String processDefinitionId = processInstanceExecution.getProcessDefinitionId();
      if (processDefinitionId != null) {
        ObjectNode languageNode =
            Context.getLocalizationElementProperties(
                locale,
                processInstanceExecution.getProcessDefinitionKey(),
                processDefinitionId,
                withLocalizationFallback);
        if (languageNode != null) {
          JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME);
          if (languageNameNode != null && languageNameNode.isNull() == false) {
            processInstanceExecution.setLocalizedName(languageNameNode.asText());
          }

          JsonNode languageDescriptionNode =
              languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION);
          if (languageDescriptionNode != null && languageDescriptionNode.isNull() == false) {
            processInstanceExecution.setLocalizedDescription(languageDescriptionNode.asText());
          }
        }
      }
    }
  }
  public ProcessInstance execute(CommandContext commandContext) {
    DeploymentManager deploymentCache =
        Context.getProcessEngineConfiguration().getDeploymentManager();

    // Find the process definition
    ProcessDefinitionEntity processDefinition = null;
    if (processDefinitionId != null) {
      processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
      if (processDefinition == null) {
        throw new ActivitiException(
            "No process definition found for id = '" + processDefinitionId + "'");
      }
    } else if (processDefinitionKey != null) {
      /* Original state
      processDefinition = deploymentCache.findDeployedLatestProcessDefinitionByKey(processDefinitionKey);
      if (processDefinition == null) {
        throw new ActivitiException("No process definition found for key '" + processDefinitionKey +"'");
      }
      */
      throw new ActivitiException(
          "Operation usupported due to unavailability to get latest definition by key for a Liferay Company");
    } else {
      throw new ActivitiException("processDefinitionKey and processDefinitionId are null");
    }

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

    // Start the process instance
    ExecutionEntity processInstance = processDefinition.createProcessInstance(businessKey);
    if (variables != null) {
      processInstance.setVariables(variables);
    }
    processInstance.start();

    return processInstance;
  }
  public void processHistoryTask(
      HistoricTaskInstanceEntity historicTaskInstanceEntity,
      HistoricActivityInstanceEntity historicActivityInstanceEntity) {
    historicTaskInstanceEntity.setEndTime(null);
    historicTaskInstanceEntity.setDurationInMillis(null);
    historicActivityInstanceEntity.setEndTime(null);
    historicActivityInstanceEntity.setDurationInMillis(null);

    TaskEntity task = TaskEntity.create(new Date());
    task.setProcessDefinitionId(historicTaskInstanceEntity.getProcessDefinitionId());
    task.setId(historicTaskInstanceEntity.getId());
    task.setAssigneeWithoutCascade(historicTaskInstanceEntity.getAssignee());
    task.setParentTaskIdWithoutCascade(historicTaskInstanceEntity.getParentTaskId());
    task.setNameWithoutCascade(historicTaskInstanceEntity.getName());
    task.setTaskDefinitionKey(historicTaskInstanceEntity.getTaskDefinitionKey());
    task.setExecutionId(historicTaskInstanceEntity.getExecutionId());
    task.setPriority(historicTaskInstanceEntity.getPriority());
    task.setProcessInstanceId(historicTaskInstanceEntity.getProcessInstanceId());
    task.setDescriptionWithoutCascade(historicTaskInstanceEntity.getDescription());
    task.setTenantId(historicTaskInstanceEntity.getTenantId());

    Context.getCommandContext().getTaskEntityManager().insert(task);

    try {
      HumanTaskConnector humanTaskConnector =
          ApplicationContextHelper.getBean(HumanTaskConnector.class);
      // humantask
      humanTaskConnector.removeHumanTaskByTaskId(historicTaskInstanceEntity.getId());
      this.createHumanTask(task);
    } catch (Exception ex) {
      logger.error(ex.getMessage(), ex);
    }

    ExecutionEntity executionEntity =
        Context.getCommandContext()
            .getExecutionEntityManager()
            .findExecutionById(historicTaskInstanceEntity.getExecutionId());
    executionEntity.setActivity(getActivity(historicActivityInstanceEntity));
  }
  public void handleEvent(
      EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) {

    String configuration = eventSubscription.getConfiguration();
    if (configuration == null) {
      throw new ActivitiException(
          "Compensating execution not set for compensate event subscription with id "
              + eventSubscription.getId());
    }

    ExecutionEntity compensatingExecution =
        commandContext.getExecutionEntityManager().findExecutionById(configuration);

    ActivityImpl compensationHandler = eventSubscription.getActivity();

    if ((compensationHandler.getProperty(BpmnParse.PROPERTYNAME_IS_FOR_COMPENSATION) == null
            || !(Boolean)
                compensationHandler.getProperty(BpmnParse.PROPERTYNAME_IS_FOR_COMPENSATION))
        && compensationHandler.isScope()) {

      // descend into scope:
      List<CompensateEventSubscriptionEntity> eventsForThisScope =
          compensatingExecution.getCompensateEventSubscriptions();
      ScopeUtil.throwCompensationEvent(eventsForThisScope, compensatingExecution, false);

    } else {
      try {

        if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
          commandContext
              .getProcessEngineConfiguration()
              .getEventDispatcher()
              .dispatchEvent(
                  ActivitiEventBuilder.createActivityEvent(
                      ActivitiEventType.ACTIVITY_COMPENSATE,
                      compensationHandler.getId(),
                      compensatingExecution.getId(),
                      compensatingExecution.getProcessInstanceId(),
                      compensatingExecution.getProcessDefinitionId()));
        }
        compensatingExecution.setActivity(compensationHandler);

        // executing the atomic operation makes sure activity start events are fired
        compensatingExecution.performOperation(AtomicOperation.ACTIVITY_START);

      } catch (Exception e) {
        throw new ActivitiException(
            "Error while handling compensation event " + eventSubscription, e);
      }
    }
  }
  public TimerEntity prepareTimerEntity(ExecutionEntity executionEntity) {
    BusinessCalendar businessCalendar =
        Context.getProcessEngineConfiguration()
            .getBusinessCalendarManager()
            .getBusinessCalendar(type.calendarName);

    if (description == null) {
      // Prevent NPE from happening in the next line
      throw new ActivitiIllegalArgumentException(
          "Timer '"
              + executionEntity.getActivityId()
              + "' was not configured with a valid duration/time");
    }

    String endDateString = null;
    String dueDateString = null;
    Date duedate = null;
    Date endDate = null;

    // ACT-1415: timer-declaration on start-event may contain expressions NOT
    // evaluating variables but other context, evaluating should happen nevertheless
    VariableScope scopeForExpression = executionEntity;
    if (scopeForExpression == null) {
      scopeForExpression = NoExecutionVariableScope.getSharedInstance();
    }

    if (endDateExpression != null && !(scopeForExpression instanceof NoExecutionVariableScope)) {
      Object endDateValue = endDateExpression.getValue(scopeForExpression);
      if (endDateValue instanceof String) {
        endDateString = (String) endDateValue;
      } else if (endDateValue instanceof Date) {
        endDate = (Date) endDateValue;
      } else if (endDateValue instanceof DateTime) {
        // Joda DateTime support
        duedate = ((DateTime) endDateValue).toDate();
      } else {
        throw new ActivitiException(
            "Timer '"
                + executionEntity.getActivityId()
                + "' 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 (endDate == null) {
        endDate = businessCalendar.resolveEndDate(endDateString);
      }
    }

    Object dueDateValue = description.getValue(scopeForExpression);
    if (dueDateValue instanceof String) {
      dueDateString = (String) dueDateValue;
    } else if (dueDateValue instanceof Date) {
      duedate = (Date) dueDateValue;
    } else if (dueDateValue instanceof DateTime) {
      // Joda DateTime support
      duedate = ((DateTime) dueDateValue).toDate();
    } else if (dueDateValue != null) {
      // dueDateValue==null is OK - but unexpected class type must throw an error.
      throw new ActivitiException(
          "Timer '"
              + executionEntity.getActivityId()
              + "' 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 && dueDateString != null) {
      duedate = businessCalendar.resolveDuedate(dueDateString);
    }

    TimerEntity timer = null;
    // if dueDateValue is null -> this is OK - timer will be null and job not scheduled
    if (duedate != null) {
      timer = new TimerEntity(this);
      timer.setDuedate(duedate);
      timer.setEndDate(endDate);

      if (executionEntity != null) {
        timer.setExecution(executionEntity);
        timer.setProcessDefinitionId(executionEntity.getProcessDefinitionId());
        timer.setProcessInstanceId(executionEntity.getProcessInstanceId());

        // Inherit tenant identifier (if applicable)
        if (executionEntity != null && executionEntity.getTenantId() != null) {
          timer.setTenantId(executionEntity.getTenantId());
        }
      }

      if (type == TimerDeclarationType.CYCLE) {

        // See ACT-1427: A boundary timer with a cancelActivity='true', doesn't need to repeat
        // itself
        boolean repeat = !isInterruptingTimer;

        // ACT-1951: intermediate catching timer events shouldn't repeat according to spec
        if (TimerCatchIntermediateEventJobHandler.TYPE.equals(jobHandlerType)) {
          repeat = false;
          if (endDate != null) {
            long endDateMiliss = endDate.getTime();
            long dueDateMiliss = duedate.getTime();
            long dueDate = Math.min(endDateMiliss, dueDateMiliss);
            timer.setDuedate(new Date(dueDate));
          }
        }

        if (repeat) {
          String prepared = prepareRepeat(dueDateString);
          timer.setRepeat(prepared);
        }
      }
    }
    return timer;
  }
  /**
   * Called when the wrapped {@link ActivityBehavior} calls the {@link
   * AbstractBpmnActivityBehavior#leave(ActivityExecution)} method. Handles the completion of one of
   * the parallel instances
   */
  public void leave(ActivityExecution execution) {
    callActivityEndListeners(execution);

    int loopCounter = getLoopVariable(execution, LOOP_COUNTER);
    int nrOfInstances = getLoopVariable(execution, NUMBER_OF_INSTANCES);
    int nrOfCompletedInstances = getLoopVariable(execution, NUMBER_OF_COMPLETED_INSTANCES) + 1;
    int nrOfActiveInstances = getLoopVariable(execution, NUMBER_OF_ACTIVE_INSTANCES) - 1;

    if (isExtraScopeNeeded()) {
      // In case an extra scope was created, it must be destroyed first before going further
      ExecutionEntity extraScope = (ExecutionEntity) execution;
      execution = execution.getParent();
      extraScope.remove();
    }

    setLoopVariable(execution.getParent(), NUMBER_OF_COMPLETED_INSTANCES, nrOfCompletedInstances);
    setLoopVariable(execution.getParent(), NUMBER_OF_ACTIVE_INSTANCES, nrOfActiveInstances);
    logLoopDetails(
        execution,
        "instance completed",
        loopCounter,
        nrOfCompletedInstances,
        nrOfActiveInstances,
        nrOfInstances);

    ExecutionEntity executionEntity = (ExecutionEntity) execution;
    executionEntity.inactivate();
    executionEntity.getParent().forceUpdate();

    List<ActivityExecution> joinedExecutions =
        executionEntity.findInactiveConcurrentExecutions(execution.getActivity());
    if (joinedExecutions.size() == nrOfInstances || completionConditionSatisfied(execution)) {

      // Removing all active child executions (ie because completionCondition is true)
      List<ExecutionEntity> executionsToRemove = new ArrayList<ExecutionEntity>();
      for (ActivityExecution childExecution : executionEntity.getParent().getExecutions()) {
        if (childExecution.isActive()) {
          executionsToRemove.add((ExecutionEntity) childExecution);
        }
      }
      for (ExecutionEntity executionToRemove : executionsToRemove) {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug(
              "Execution {} still active, but multi-instance is completed. Removing this execution.",
              executionToRemove);
        }
        executionToRemove.inactivate();
        executionToRemove.deleteCascade("multi-instance completed");
      }
      executionEntity.takeAll(
          executionEntity.getActivity().getOutgoingTransitions(), joinedExecutions);
    }
  }
Beispiel #12
0
  /**
   * 打开任务 传入的request必须有以下参数 taskId:task的Id taskPage:处理task的页面路径 model:业务表类名 formId:业务表id
   * formProperties:控制表单的名称
   *
   * @return
   * @throws Exception
   */
  public String open_task() throws Exception {
    log.debug("open_task()");
    List<String> nextTaskList = new ArrayList<String>();
    String taskId = getpara("taskId");
    String taskPage = getpara("taskPage");
    String modelStr = getpara("model");
    // add by hb for only query user task
    String readonly = getpara("readonly");
    // end
    String formId = (String) infActiviti.getVariableByTaskId(taskId, "formId");
    if (formId == null || formId.equals("") || modelStr == null || "".equals(modelStr)) {
      rhs.put("model", null);
    } else {
      BaseModel model = (BaseModel) baseDao.loadById(modelStr, Long.parseLong(formId));
      rhs.put("model", model);
    }

    /* add by chenzhijian 20130419 -s */
    // 获取 formProperties 配置文件
    String formProperties = getpara("formProperties");
    HashMap<String, String> formPro = new HashMap<String, String>();
    Properties p = new Properties();
    try {
      // String filepath = System.getProperty("webroot", "./src/main/webapp/");
      String filepath = getWebroot();
      // eg: app/manager/wo/wo.properties
      filepath +=
          "/app/manager/" + modelStr.toLowerCase() + "/" + modelStr.toLowerCase() + ".properties";
      FileInputStream in = new FileInputStream(filepath);
      p.load(in);
      in.close();
      Set<String> set = p.stringPropertyNames();
      for (String s : set) {
        if (s.startsWith("default")) {
          formPro.put(s.replace("default.", ""), p.getProperty(s));
        }
      }
      for (String s : set) {
        if (s.startsWith(formProperties)) {
          formPro.put(s.replace(formProperties + ".", ""), p.getProperty(s));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    rhs.put("formPro", formPro);
    /* add by chenzhijian 20130419 -e */

    Task task = infActiviti.getTaskById(taskId);
    /*add by hb for get next task 20140128 start*/
    String nextTask = "";
    String initiator = (String) infActiviti.getVariableByTaskId(task.getId(), "initiator");
    // 当前任务获取当前流程的流程定义,然后根据流程定义获得所有的节点
    ProcessDefinitionEntity def =
        (ProcessDefinitionEntity)
            ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(task.getProcessDefinitionId());
    List<ActivityImpl> activitiList = def.getActivities();
    // 根据任务获取当前流程执行ID,执行实例以及当前流程节点的ID
    String excId = task.getExecutionId();
    ExecutionEntity execution =
        (ExecutionEntity) runtimeService.createExecutionQuery().executionId(excId).singleResult();
    String activitiId = execution.getActivityId();
    // 循环activitiList 并判断出当前流程所处节点,然后得到当前节点实例,
    // 根据节点实例获取所有从当前节点出发的路径,然后根据路径获得下一个节点实例
    for (ActivityImpl activityImpl : activitiList) {
      String id = activityImpl.getId();
      if (activitiId.equals(id)) {
        log.debug("当前任务:" + activityImpl.getProperty("name"));
        List<PvmTransition> outTransitions =
            activityImpl.getOutgoingTransitions(); // 获取从某个节点出来的所有线路
        for (PvmTransition tr : outTransitions) {
          PvmActivity ac = tr.getDestination(); // 获取线路的终点节点,在这里应该还要加个判断,如果是并行或者相容关口,则需要继续往下找下一个任务。
          if (ac.getProperty("type").equals("parallelGateway")
              || ac.getProperty("type")
                  .equals(
                      "inclusiveGateway")) { // 不能包括互斥关口
                                             // ac.getProperty("type").equals("exclusiveGateway")
            List<PvmTransition> outTransitions2 = ac.getOutgoingTransitions(); // 因为是关口,所以继续往下找任务
            for (PvmTransition pvmTransition : outTransitions2) {
              PvmActivity ac2 = pvmTransition.getDestination();
              nextTask = (String) ac2.getId();
              log.debug("下一个任务----->:" + nextTask);
              nextTaskList.add(nextTask);
            }
          } else {
            nextTask = (String) ac.getId();
            log.debug("下一个任务++++>:" + nextTask);
            nextTaskList.add(nextTask);
          }
        }
        break;
      }
    }

    /*end*/
    rhs.put("task", task);
    rhs.put("initiator", initiator);
    rhs.put("nextTaskList", nextTaskList);
    rhs.put("taskPage", taskPage);
    rhs.put("readonly", readonly);
    getAllUserAndGroupInfo();

    return "success";
  }