protected void changeProcessDefinitionState(
      CommandContext commandContext, List<ProcessDefinitionEntity> processDefinitions) {
    for (ProcessDefinitionEntity processDefinition : processDefinitions) {

      SuspensionStateUtil.setSuspensionState(
          processDefinition, getProcessDefinitionSuspensionState());

      // Evict cache
      Context.getProcessEngineConfiguration()
          .getDeploymentManager()
          .getProcessDefinitionCache()
          .remove(processDefinition.getId());

      // Suspend process instances (if needed)
      if (includeProcessInstances) {

        int currentStartIndex = 0;
        List<ProcessInstance> processInstances =
            fetchProcessInstancesPage(commandContext, processDefinition, currentStartIndex);
        while (processInstances.size() > 0) {

          for (ProcessInstance processInstance : processInstances) {
            AbstractSetProcessInstanceStateCmd processInstanceCmd =
                getProcessInstanceChangeStateCmd(processInstance);
            processInstanceCmd.execute(commandContext);
          }

          // Fetch new batch of process instances
          currentStartIndex += processInstances.size();
          processInstances =
              fetchProcessInstancesPage(commandContext, processDefinition, currentStartIndex);
        }
      }
    }
  }
  public StreamResource buildStreamResource(
      ProcessInstance processInstance,
      RepositoryService repositoryService,
      RuntimeService runtimeService) {

    StreamResource imageResource = null;

    ProcessDefinitionEntity processDefinition =
        (ProcessDefinitionEntity)
            ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(processInstance.getProcessDefinitionId());

    if (processDefinition != null && processDefinition.isGraphicalNotationDefined()) {
      InputStream definitionImageStream =
          ProcessDiagramGenerator.generateDiagram(
              processDefinition,
              "png",
              runtimeService.getActiveActivityIds(processInstance.getId()));

      StreamSource streamSource = new InputStreamStreamSource(definitionImageStream);

      // Create image name
      String imageExtension = extractImageExtension(processDefinition.getDiagramResourceName());
      String fileName = processInstance.getId() + UUID.randomUUID() + "." + imageExtension;

      imageResource = new StreamResource(streamSource, fileName, ExplorerApp.get());
    }
    return imageResource;
  }
Ejemplo n.º 3
0
  protected void removeObsoleteTimers(ProcessDefinitionEntity processDefinition) {

    List<Job> jobsToDelete = null;

    if (processDefinition.getTenantId() != null
        && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
      jobsToDelete =
          Context.getCommandContext()
              .getJobEntityManager()
              .findJobsByTypeAndProcessDefinitionKeyAndTenantId(
                  TimerStartEventJobHandler.TYPE,
                  processDefinition.getKey(),
                  processDefinition.getTenantId());
    } else {
      jobsToDelete =
          Context.getCommandContext()
              .getJobEntityManager()
              .findJobsByTypeAndProcessDefinitionKeyNoTenantId(
                  TimerStartEventJobHandler.TYPE, processDefinition.getKey());
    }

    if (jobsToDelete != null) {
      for (Job job : jobsToDelete) {
        new CancelJobsCmd(job.getId()).execute(Context.getCommandContext());
      }
    }
  }
Ejemplo n.º 4
0
  @Deployment
  public void testAsyncInvocationWithDataFlowUEL() throws Exception {
    assertEquals(-1, webServiceMock.getCount());

    ProcessDefinitionEntity processDefinition =
        processEngineConfiguration
            .getCommandExecutor()
            .execute(
                new Command<ProcessDefinitionEntity>() {
                  public ProcessDefinitionEntity execute(CommandContext commandContext) {
                    return Context.getProcessEngineConfiguration()
                        .getDeploymentManager()
                        .findDeployedLatestProcessDefinitionByKey(
                            "asyncWebServiceInvocationWithDataFlowUEL");
                  }
                });

    ItemDefinition itemDefinition =
        processDefinition.getIoSpecification().getDataInputs().get(0).getDefinition();

    ItemInstance itemInstance = itemDefinition.createInstance();
    FieldBaseStructureInstance structureInstance =
        (FieldBaseStructureInstance) itemInstance.getStructureInstance();
    structureInstance.setFieldValue("newCounterValue", 23);

    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("dataInputOfProcess", itemInstance);

    processEngine
        .getRuntimeService()
        .startProcessInstanceByKey("asyncWebServiceInvocationWithDataFlowUEL", variables);
    waitForJobExecutorToProcessAllJobs(10000L, 250L);

    assertEquals(23, webServiceMock.getCount());
  }
Ejemplo n.º 5
0
  public ActivityImpl getActivity(HistoricActivityInstanceEntity historicActivityInstanceEntity) {
    ProcessDefinitionEntity processDefinitionEntity =
        new GetDeploymentProcessDefinitionCmd(
                historicActivityInstanceEntity.getProcessDefinitionId())
            .execute(Context.getCommandContext());

    return processDefinitionEntity.findActivity(historicActivityInstanceEntity.getActivityId());
  }
Ejemplo n.º 6
0
 protected void addAuthorizations(ProcessDefinitionEntity processDefinition) {
   addAuthorizationsFromIterator(
       processDefinition.getCandidateStarterUserIdExpressions(), processDefinition, ExprType.USER);
   addAuthorizationsFromIterator(
       processDefinition.getCandidateStarterGroupIdExpressions(),
       processDefinition,
       ExprType.GROUP);
 }
Ejemplo n.º 7
0
 public ProcessDefinitionEntity getProcessDefinition(String processDefinitionKey) {
   for (ProcessDefinitionEntity processDefinition : processDefinitions) {
     if (processDefinition.getKey().equals(processDefinitionKey)) {
       return processDefinition;
     }
   }
   return null;
 }
Ejemplo n.º 8
0
 public static void put(String processDefinitionId, ProcessDefinition processDefinition) {
   map.put(processDefinitionId, processDefinition);
   ProcessDefinitionEntity pde = (ProcessDefinitionEntity) processDefinition;
   activities.put(processDefinitionId, pde.getActivities());
   for (ActivityImpl activityImpl : pde.getActivities()) {
     singleActivity.put(processDefinitionId + "_" + activityImpl.getId(), activityImpl);
   }
 }
Ejemplo n.º 9
0
 public TaskDefinition getTaskDefinition() {
   if (taskDefinition == null && taskDefinitionKey != null) {
     ProcessDefinitionEntity processDefinition =
         Context.getProcessEngineConfiguration()
             .getDeploymentManager()
             .findDeployedProcessDefinitionById(processDefinitionId);
     taskDefinition = processDefinition.getTaskDefinitions().get(taskDefinitionKey);
   }
   return taskDefinition;
 }
Ejemplo n.º 10
0
 public String process_definition_activity() {
   String processDefinitionId = getpara("processDefinitionId");
   ProcessDefinitionEntity processDefinition =
       (ProcessDefinitionEntity)
           ((RepositoryServiceImpl) repositoryService)
               .getDeployedProcessDefinition(processDefinitionId);
   List<ActivityImpl> activityImplList = processDefinition.getActivities();
   for (ActivityImpl a : activityImplList) {
     log.debug(a.getProperties().toString());
   }
   rhs.put("list", activityImplList);
   return "success";
 }
 protected void createTimerForDelayedExecution(
     CommandContext commandContext, List<ProcessDefinitionEntity> processDefinitions) {
   for (ProcessDefinitionEntity processDefinition : processDefinitions) {
     TimerEntity timer = new TimerEntity();
     timer.setProcessDefinitionId(processDefinition.getId());
     timer.setDuedate(executionDate);
     timer.setJobHandlerType(getDelayedExecutionJobHandlerType());
     timer.setJobHandlerConfiguration(
         TimerChangeProcessDefinitionSuspensionStateJobHandler.createJobHandlerConfiguration(
             includeProcessInstances));
     commandContext.getJobEntityManager().schedule(timer);
   }
 }
Ejemplo n.º 12
0
  protected void addDefinitionInfoToCache(
      ProcessDefinitionEntity processDefinition,
      ProcessEngineConfigurationImpl processEngineConfiguration,
      CommandContext commandContext) {

    if (processEngineConfiguration.isEnableProcessDefinitionInfoCache() == false) {
      return;
    }

    DeploymentManager deploymentManager = processEngineConfiguration.getDeploymentManager();
    ProcessDefinitionInfoEntityManager definitionInfoEntityManager =
        commandContext.getProcessDefinitionInfoEntityManager();
    ObjectMapper objectMapper = commandContext.getProcessEngineConfiguration().getObjectMapper();
    ProcessDefinitionInfoEntity definitionInfoEntity =
        definitionInfoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(
            processDefinition.getId());

    ObjectNode infoNode = null;
    if (definitionInfoEntity != null && definitionInfoEntity.getInfoJsonId() != null) {
      byte[] infoBytes =
          definitionInfoEntityManager.findInfoJsonById(definitionInfoEntity.getInfoJsonId());
      if (infoBytes != null) {
        try {
          infoNode = (ObjectNode) objectMapper.readTree(infoBytes);
        } catch (Exception e) {
          throw new ActivitiException(
              "Error deserializing json info for process definition " + processDefinition.getId());
        }
      }
    }

    ProcessDefinitionInfoCacheObject definitionCacheObject = new ProcessDefinitionInfoCacheObject();
    if (definitionInfoEntity == null) {
      definitionCacheObject.setRevision(0);
    } else {
      definitionCacheObject.setId(definitionInfoEntity.getId());
      definitionCacheObject.setRevision(definitionInfoEntity.getRevision());
    }

    if (infoNode == null) {
      infoNode = objectMapper.createObjectNode();
    }
    definitionCacheObject.setInfoNode(infoNode);

    deploymentManager
        .getProcessDefinitionInfoCache()
        .add(processDefinition.getId(), definitionCacheObject);
  }
Ejemplo n.º 13
0
  public FirstTaskForm findStartEventForm(ProcessDefinitionEntity processDefinitionEntity) {
    FirstTaskForm firstTaskForm = new FirstTaskForm();
    firstTaskForm.setExists(true);
    firstTaskForm.setProcessDefinitionId(processDefinitionId);
    firstTaskForm.setTaskForm(false);

    DefaultFormHandler formHandler =
        (DefaultFormHandler) processDefinitionEntity.getStartFormHandler();

    if (formHandler.getFormKey() != null) {
      String formKey = formHandler.getFormKey().getExpressionText();
      firstTaskForm.setFormKey(formKey);
      firstTaskForm.setActivityId(processDefinitionEntity.getInitial().getId());
    }

    return firstTaskForm;
  }
Ejemplo n.º 14
0
  protected void removeExistingSignalEventSubScription(
      ProcessDefinitionEntity processDefinition, ProcessDefinitionEntity latestProcessDefinition) {
    if (latestProcessDefinition != null) {
      CommandContext commandContext = Context.getCommandContext();

      List<EventSubscriptionEntity> subscriptionsToDisable =
          commandContext
              .getEventSubscriptionEntityManager()
              .findEventSubscriptionsByTypeAndProcessDefinitionId(
                  SignalEventHandler.EVENT_HANDLER_TYPE,
                  latestProcessDefinition.getId(),
                  latestProcessDefinition.getTenantId());

      for (EventSubscriptionEntity eventSubscriptionEntity : subscriptionsToDisable) {
        eventSubscriptionEntity.delete();
      }
    }
  }
  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;
  }
Ejemplo n.º 16
0
  public void createBPMNShape(
      String key, GraphicInfo graphicInfo, ProcessDefinitionEntity processDefinition) {
    ActivityImpl activity = processDefinition.findActivity(key);
    if (activity != null) {
      createDIBounds(graphicInfo, activity);

    } else {
      org.activiti.engine.impl.pvm.process.Lane lane = processDefinition.getLaneForId(key);

      if (lane != null) {
        // The shape represents a lane
        createDIBounds(graphicInfo, lane);
      } else {
        bpmnModel.addProblem(
            "Invalid reference in 'bpmnElement' attribute, activity " + key + " not found",
            graphicInfo);
      }
    }
  }
 /** * 获取跟踪信息 * * @return * @throws Exception */
 public String getProcessMap() throws Exception {
   String procDefId = ""; // request.getParameter("procDefId");
   String proInstId = ""; // request.getParameter("procInstId");
   ProcessDefinition processDefinition =
       repositoryService
           .createProcessDefinitionQuery()
           .processDefinitionId(procDefId)
           .singleResult();
   ProcessDefinitionImpl pdImpl = (ProcessDefinitionImpl) processDefinition;
   String processDefinitionId = pdImpl.getId(); // 流程标识
   ProcessDefinitionEntity def =
       (ProcessDefinitionEntity)
           ((RepositoryServiceImpl) repositoryService)
               .getDeployedProcessDefinition(processDefinitionId);
   List<ActivityImpl> activitiList = def.getActivities();
   // 获得当前任务的所有节点 /****/
   List<String> ActiveActivityIds = runtimeService.getActiveActivityIds(proInstId);
   for (String activeId : ActiveActivityIds) {
     for (ActivityImpl activityImpl : activitiList) {
       String id = activityImpl.getId();
       if (activityImpl.isScope()) {
         if (activityImpl.getActivities().size() > 1) {
           List<ActivityImpl> subAcList = activityImpl.getActivities();
           for (ActivityImpl subActImpl : subAcList) {
             String subid = subActImpl.getId();
             System.out.println("subImpl:" + subid);
             if (activeId.equals(subid)) { // 获得执行到那个节点
               actImpls.add(subActImpl);
               break;
             }
           }
         }
       }
       if (activeId.equals(id)) { // 获得执行到那个节点
         actImpls.add(activityImpl);
         System.out.println(id);
       }
     }
   }
   /** * */
   return "SUCCESS";
 }
Ejemplo n.º 18
0
  @SuppressWarnings("unchecked")
  protected void addSignalEventSubscriptions(ProcessDefinitionEntity processDefinition) {
    List<EventSubscriptionDeclaration> eventDefinitions =
        (List<EventSubscriptionDeclaration>)
            processDefinition.getProperty(BpmnParse.PROPERTYNAME_EVENT_SUBSCRIPTION_DECLARATION);
    if (eventDefinitions != null) {
      for (EventSubscriptionDeclaration eventDefinition : eventDefinitions) {
        if (eventDefinition.getEventType().equals("signal") && eventDefinition.isStartEvent()) {

          SignalEventSubscriptionEntity subscriptionEntity = new SignalEventSubscriptionEntity();
          subscriptionEntity.setEventName(eventDefinition.getEventName());
          subscriptionEntity.setActivityId(eventDefinition.getActivityId());
          subscriptionEntity.setProcessDefinitionId(processDefinition.getId());
          if (processDefinition.getTenantId() != null) {
            subscriptionEntity.setTenantId(processDefinition.getTenantId());
          }
          subscriptionEntity.insert();
        }
      }
    }
  }
Ejemplo n.º 19
0
  @SuppressWarnings("unchecked")
  protected void addTimerDeclarations(
      ProcessDefinitionEntity processDefinition, List<TimerEntity> timers) {
    List<TimerDeclarationImpl> timerDeclarations =
        (List<TimerDeclarationImpl>)
            processDefinition.getProperty(BpmnParse.PROPERTYNAME_START_TIMER);
    if (timerDeclarations != null) {
      for (TimerDeclarationImpl timerDeclaration : timerDeclarations) {
        TimerEntity timer = timerDeclaration.prepareTimerEntity(null);
        if (timer != null) {
          timer.setProcessDefinitionId(processDefinition.getId());

          // Inherit timer (if appliccable)
          if (processDefinition.getTenantId() != null) {
            timer.setTenantId(processDefinition.getTenantId());
          }
          timers.add(timer);
        }
      }
    }
  }
Ejemplo n.º 20
0
 public ProcessArchive getProcessArchiveByProcessDefinitionId(final String processDefinitionId) {
   // first try to hit the cache
   ProcessDefinitionEntity processDefinitionEntity =
       processEngineConfiguration
           .getDeploymentCache()
           .getProcessDefinitionCache()
           .get(processDefinitionId);
   if (processDefinitionEntity == null) {
     // now look for it in the database (will add it to the cache).
     processDefinitionEntity =
         processEngineConfiguration
             .getCommandExecutorTxRequired()
             .execute(
                 new Command<ProcessDefinitionEntity>() {
                   public ProcessDefinitionEntity execute(CommandContext commandContext) {
                     return commandContext
                         .getProcessDefinitionManager()
                         .findLatestProcessDefinitionById(processDefinitionId);
                   }
                 });
   }
   if (processDefinitionEntity == null) {
     throw new FoxPlatformException(
         "Could not find process definition with id '"
             + processDefinitionId
             + "' for process engine '"
             + processEngineName
             + "'.");
   }
   String processDefinitionKey = processDefinitionEntity.getKey();
   if (processDefinitionKey == null) {
     throw new FoxPlatformException(
         "Could not find process definition with id '"
             + processDefinitionId
             + "' for process engine '"
             + processEngineName
             + "'.");
   }
   return getProcessArchiveByProcessDefinitionKey(processDefinitionKey);
 }
Ejemplo n.º 21
0
  public void processDI() {
    if (bpmnModel.getLocationMap().size() > 0) {
      for (Process process : bpmnModel.getProcesses()) {
        if (process.isExecutable() == false) continue;
        ProcessDefinitionEntity processDefinition = getProcessDefinition(process.getId());
        if (processDefinition != null) {
          processDefinition.setGraphicalNotationDefined(true);
          for (String shapeId : bpmnModel.getLocationMap().keySet()) {
            if (processDefinition.findActivity(shapeId) != null) {
              createBPMNShape(shapeId, bpmnModel.getGraphicInfo(shapeId), processDefinition);
            }
          }

          for (String edgeId : bpmnModel.getFlowLocationMap().keySet()) {
            if (bpmnModel.getFlowElement(edgeId) != null) {
              createBPMNEdge(edgeId, bpmnModel.getFlowLocationGraphicInfo(edgeId));
            }
          }
        }
      }
    }
  }
Ejemplo n.º 22
0
  public void initSource() {
    // source task
    this.jumpInfo.setSourceTaskId(this.taskId);

    TaskEntity sourceTask =
        Context.getCommandContext().getTaskEntityManager().findTaskById(this.taskId);
    this.jumpInfo.setSourceTask(sourceTask);

    ProcessDefinitionEntity processDefinitionEntity =
        Context.getProcessEngineConfiguration()
            .getDeploymentManager()
            .findDeployedProcessDefinitionById(sourceTask.getProcessDefinitionId());
    // source activity
    this.jumpInfo.setSourceActivityId(sourceTask.getTaskDefinitionKey());
    this.jumpInfo.setSourceActivity(
        processDefinitionEntity.findActivity(this.jumpInfo.getSourceActivityId()));

    HistoricTaskInstanceEntity sourceHistoryTask =
        Context.getCommandContext()
            .getHistoricTaskInstanceEntityManager()
            .findHistoricTaskInstanceById(this.jumpInfo.getSourceTaskId());
  }
Ejemplo n.º 23
0
  /**
   * 流程跟踪图
   *
   * @param processInstanceId 流程实例ID
   * @return 封装了各种节点信息
   */
  public List<Map<String, Object>> traceProcess(String processInstanceId) throws Exception {
    Execution execution =
        runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult(); // 执行实例
    Object property = PropertyUtils.getProperty(execution, "activityId");
    String activityId = "";
    if (property != null) {
      activityId = property.toString();
    }
    ProcessInstance processInstance =
        runtimeService
            .createProcessInstanceQuery()
            .processInstanceId(processInstanceId)
            .singleResult();
    ProcessDefinitionEntity processDefinition =
        (ProcessDefinitionEntity)
            ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
    List<ActivityImpl> activitiList = processDefinition.getActivities(); // 获得当前任务的所有节点

    List<Map<String, Object>> activityInfos = new ArrayList<Map<String, Object>>();
    for (ActivityImpl activity : activitiList) {

      boolean currentActiviti = false;
      String id = activity.getId();

      // 当前节点
      if (id.equals(activityId)) {
        currentActiviti = true;
      }

      Map<String, Object> activityImageInfo =
          packageSingleActivitiInfo(activity, processInstance, currentActiviti);

      activityInfos.add(activityImageInfo);
    }

    return activityInfos;
  }
Ejemplo n.º 24
0
  public ProcessDefinitionEntity resolveProcessDefinition(
      ProcessDefinitionEntity processDefinition) {
    String processDefinitionId = processDefinition.getId();
    String deploymentId = processDefinition.getDeploymentId();
    processDefinition = processDefinitionCache.get(processDefinitionId);
    if (processDefinition == null) {
      DeploymentEntity deployment =
          Context.getCommandContext().getDeploymentEntityManager().findDeploymentById(deploymentId);
      deployment.setNew(false);
      deploy(deployment, null);
      processDefinition = processDefinitionCache.get(processDefinitionId);

      if (processDefinition == null) {
        throw new ActivitiException(
            "deployment '"
                + deploymentId
                + "' didn't put process definition '"
                + processDefinitionId
                + "' in the cache");
      }
    }
    return processDefinition;
  }
Ejemplo n.º 25
0
  /**
   * 根据任务ID和节点ID获取活动节点 <br>
   *
   * @param taskId 任务ID
   * @param activityId 活动节点ID <br>
   *     如果为null或"",则默认查询当前活动节点 <br>
   *     如果为"end",则查询结束节点 <br>
   * @return
   * @throws Exception
   */
  private ActivityImpl findActivitiImpl(String taskId, String activityId) throws Exception {
    // 取得流程定义
    ProcessDefinitionEntity procDef = this.findProcDefEntityByTaskId(taskId);

    // 获取当前活动节点ID
    if (StringUtil.isStrEmpty(activityId)) {
      activityId = this.findTaskById(taskId).getTaskDefinitionKey();
    }

    // 根据流程定义,获取该流程实例的结束节点
    if (activityId.toUpperCase().equals("END")) {
      for (ActivityImpl activityImpl : procDef.getActivities()) {
        List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();
        if (pvmTransitionList.isEmpty()) {
          return activityImpl;
        }
      }
    }

    // 根据节点ID,获取对应的活动节点
    ActivityImpl activityImpl = ((ProcessDefinitionImpl) procDef).findActivity(activityId);

    return activityImpl;
  }
Ejemplo n.º 26
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";
  }
  protected void addProcessImage() {
    ProcessDefinitionEntity processDefinitionEntity =
        (ProcessDefinitionEntity)
            ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(processDefinition.getId());

    // Only show when graphical notation is defined
    if (processDefinitionEntity != null) {

      boolean didDrawImage = false;

      if (ExplorerApp.get().isUseJavascriptDiagram()) {
        try {

          final InputStream definitionStream =
              repositoryService.getResourceAsStream(
                  processDefinition.getDeploymentId(), processDefinition.getResourceName());
          XMLInputFactory xif = XMLInputFactory.newInstance();
          XMLStreamReader xtr = xif.createXMLStreamReader(definitionStream);
          BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

          if (bpmnModel.getFlowLocationMap().size() > 0) {

            int maxX = 0;
            int maxY = 0;
            for (String key : bpmnModel.getLocationMap().keySet()) {
              GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(key);
              double elementX = graphicInfo.getX() + graphicInfo.getWidth();
              if (maxX < elementX) {
                maxX = (int) elementX;
              }
              double elementY = graphicInfo.getY() + graphicInfo.getHeight();
              if (maxY < elementY) {
                maxY = (int) elementY;
              }
            }

            Panel imagePanel = new Panel(); // using panel for scrollbars
            imagePanel.addStyleName(Reindeer.PANEL_LIGHT);
            imagePanel.setWidth(100, UNITS_PERCENTAGE);
            imagePanel.setHeight(100, UNITS_PERCENTAGE);
            URL explorerURL = ExplorerApp.get().getURL();
            URL url =
                new URL(
                    explorerURL.getProtocol(),
                    explorerURL.getHost(),
                    explorerURL.getPort(),
                    explorerURL.getPath().replace("/ui", "")
                        + "diagram-viewer/index.html?processDefinitionId="
                        + processDefinition.getId()
                        + "&processInstanceId="
                        + processInstance.getId());
            Embedded browserPanel = new Embedded("", new ExternalResource(url));
            browserPanel.setType(Embedded.TYPE_BROWSER);
            browserPanel.setWidth(maxX + 350 + "px");
            browserPanel.setHeight(maxY + 220 + "px");

            HorizontalLayout panelLayoutT = new HorizontalLayout();
            panelLayoutT.setSizeUndefined();
            imagePanel.setContent(panelLayoutT);
            imagePanel.addComponent(browserPanel);

            panelLayout.addComponent(imagePanel);

            didDrawImage = true;
          }

        } catch (Exception e) {
          LOGGER.error("Error loading process diagram component", e);
        }
      }

      if (didDrawImage == false && processDefinitionEntity.isGraphicalNotationDefined()) {

        StreamResource diagram =
            new ProcessDefinitionImageStreamResourceBuilder()
                .buildStreamResource(processInstance, repositoryService, runtimeService);

        if (diagram != null) {
          Label header = new Label(i18nManager.getMessage(Messages.PROCESS_HEADER_DIAGRAM));
          header.addStyleName(ExplorerLayout.STYLE_H3);
          header.addStyleName(ExplorerLayout.STYLE_DETAIL_BLOCK);
          header.addStyleName(ExplorerLayout.STYLE_NO_LINE);
          panelLayout.addComponent(header);

          Embedded embedded = new Embedded(null, diagram);
          embedded.setType(Embedded.TYPE_IMAGE);
          embedded.setSizeUndefined();

          Panel imagePanel = new Panel(); // using panel for scrollbars
          imagePanel.setScrollable(true);
          imagePanel.addStyleName(Reindeer.PANEL_LIGHT);
          imagePanel.setWidth(100, UNITS_PERCENTAGE);
          imagePanel.setHeight(100, UNITS_PERCENTAGE);

          HorizontalLayout panelLayoutT = new HorizontalLayout();
          panelLayoutT.setSizeUndefined();
          imagePanel.setContent(panelLayoutT);
          imagePanel.addComponent(embedded);

          panelLayout.addComponent(imagePanel);
        }
      }
    }
  }
Ejemplo n.º 28
0
  public void deploy(DeploymentEntity deployment, Map<String, Object> deploymentSettings) {
    log.debug("Processing deployment {}", deployment.getName());

    List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
    Map<String, ResourceEntity> resources = deployment.getResources();
    Map<String, BpmnModel> bpmnModelMap = new HashMap<String, BpmnModel>();

    final ProcessEngineConfigurationImpl processEngineConfiguration =
        Context.getProcessEngineConfiguration();
    for (String resourceName : resources.keySet()) {

      log.info("Processing resource {}", resourceName);
      if (isBpmnResource(resourceName)) {
        ResourceEntity resource = resources.get(resourceName);
        byte[] bytes = resource.getBytes();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

        BpmnParse bpmnParse =
            bpmnParser
                .createParse()
                .sourceInputStream(inputStream)
                .setSourceSystemId(resourceName)
                .deployment(deployment)
                .name(resourceName);

        if (deploymentSettings != null) {

          // Schema validation if needed
          if (deploymentSettings.containsKey(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED)) {
            bpmnParse.setValidateSchema(
                (Boolean)
                    deploymentSettings.get(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED));
          }

          // Process validation if needed
          if (deploymentSettings.containsKey(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED)) {
            bpmnParse.setValidateProcess(
                (Boolean) deploymentSettings.get(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED));
          }

        } else {
          // On redeploy, we assume it is validated at the first deploy
          bpmnParse.setValidateSchema(false);
          bpmnParse.setValidateProcess(false);
        }

        bpmnParse.execute();

        for (ProcessDefinitionEntity processDefinition : bpmnParse.getProcessDefinitions()) {
          processDefinition.setResourceName(resourceName);

          if (deployment.getTenantId() != null) {
            processDefinition.setTenantId(
                deployment.getTenantId()); // process definition inherits the tenant id
          }

          String diagramResourceName =
              getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);

          // Only generate the resource when deployment is new to prevent modification of deployment
          // resources
          // after the process-definition is actually deployed. Also to prevent resource-generation
          // failure every
          // time the process definition is added to the deployment-cache when diagram-generation
          // has failed the first time.
          if (deployment.isNew()) {
            if (processEngineConfiguration.isCreateDiagramOnDeploy()
                && diagramResourceName == null
                && processDefinition.isGraphicalNotationDefined()) {
              try {
                byte[] diagramBytes =
                    IoUtil.readInputStream(
                        processEngineConfiguration
                            .getProcessDiagramGenerator()
                            .generateDiagram(
                                bpmnParse.getBpmnModel(),
                                "png",
                                processEngineConfiguration.getActivityFontName(),
                                processEngineConfiguration.getLabelFontName(),
                                processEngineConfiguration.getClassLoader()),
                        null);
                diagramResourceName =
                    getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
                createResource(diagramResourceName, diagramBytes, deployment);
              } catch (
                  Throwable
                      t) { // if anything goes wrong, we don't store the image (the process will
                           // still be executable).
                log.warn(
                    "Error while generating process diagram, image will not be stored in repository",
                    t);
              }
            }
          }

          processDefinition.setDiagramResourceName(diagramResourceName);
          processDefinitions.add(processDefinition);
          bpmnModelMap.put(processDefinition.getKey(), bpmnParse.getBpmnModel());
        }
      }
    }

    // check if there are process definitions with the same process key to prevent database unique
    // index violation
    List<String> keyList = new ArrayList<String>();
    for (ProcessDefinitionEntity processDefinition : processDefinitions) {
      if (keyList.contains(processDefinition.getKey())) {
        throw new ActivitiException(
            "The deployment contains process definitions with the same key (process id atrribute), this is not allowed");
      }
      keyList.add(processDefinition.getKey());
    }

    CommandContext commandContext = Context.getCommandContext();
    ProcessDefinitionEntityManager processDefinitionManager =
        commandContext.getProcessDefinitionEntityManager();
    DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
    for (ProcessDefinitionEntity processDefinition : processDefinitions) {
      List<TimerEntity> timers = new ArrayList<TimerEntity>();
      if (deployment.isNew()) {
        int processDefinitionVersion;

        ProcessDefinitionEntity latestProcessDefinition = null;
        if (processDefinition.getTenantId() != null
            && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
          latestProcessDefinition =
              processDefinitionManager.findLatestProcessDefinitionByKeyAndTenantId(
                  processDefinition.getKey(), processDefinition.getTenantId());
        } else {
          latestProcessDefinition =
              processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
        }

        if (latestProcessDefinition != null) {
          processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
        } else {
          processDefinitionVersion = 1;
        }

        processDefinition.setVersion(processDefinitionVersion);
        processDefinition.setDeploymentId(deployment.getId());

        String nextId = idGenerator.getNextId();
        String processDefinitionId =
            processDefinition.getKey()
                + ":"
                + processDefinition.getVersion()
                + ":"
                + nextId; // ACT-505

        // ACT-115: maximum id length is 64 charcaters
        if (processDefinitionId.length() > 64) {
          processDefinitionId = nextId;
        }
        processDefinition.setId(processDefinitionId);

        if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
          commandContext
              .getProcessEngineConfiguration()
              .getEventDispatcher()
              .dispatchEvent(
                  ActivitiEventBuilder.createEntityEvent(
                      ActivitiEventType.ENTITY_CREATED, processDefinition));
        }

        removeObsoleteTimers(processDefinition);
        addTimerDeclarations(processDefinition, timers);

        removeExistingMessageEventSubscriptions(processDefinition, latestProcessDefinition);
        addMessageEventSubscriptions(processDefinition);

        removeExistingSignalEventSubScription(processDefinition, latestProcessDefinition);
        addSignalEventSubscriptions(processDefinition);

        dbSqlSession.insert(processDefinition);
        addAuthorizations(processDefinition);

        if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
          commandContext
              .getProcessEngineConfiguration()
              .getEventDispatcher()
              .dispatchEvent(
                  ActivitiEventBuilder.createEntityEvent(
                      ActivitiEventType.ENTITY_INITIALIZED, processDefinition));
        }

        scheduleTimers(timers);

      } else {
        String deploymentId = deployment.getId();
        processDefinition.setDeploymentId(deploymentId);

        ProcessDefinitionEntity persistedProcessDefinition = null;
        if (processDefinition.getTenantId() == null
            || ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
          persistedProcessDefinition =
              processDefinitionManager.findProcessDefinitionByDeploymentAndKey(
                  deploymentId, processDefinition.getKey());
        } else {
          persistedProcessDefinition =
              processDefinitionManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(
                  deploymentId, processDefinition.getKey(), processDefinition.getTenantId());
        }

        if (persistedProcessDefinition != null) {
          processDefinition.setId(persistedProcessDefinition.getId());
          processDefinition.setVersion(persistedProcessDefinition.getVersion());
          processDefinition.setSuspensionState(persistedProcessDefinition.getSuspensionState());
        }
      }

      // Add to cache
      DeploymentManager deploymentManager = processEngineConfiguration.getDeploymentManager();
      deploymentManager
          .getProcessDefinitionCache()
          .add(processDefinition.getId(), processDefinition);
      addDefinitionInfoToCache(processDefinition, processEngineConfiguration, commandContext);

      // Add to deployment for further usage
      deployment.addDeployedArtifact(processDefinition);

      createLocalizationValues(
          processDefinition.getId(),
          bpmnModelMap.get(processDefinition.getKey()).getProcessById(processDefinition.getKey()));
    }
  }
Ejemplo n.º 29
0
 public void setProcessDef(ProcessDefinitionEntity processDef) {
   this.processDef = processDef;
   this.processDefId = processDef.getId();
 }
Ejemplo n.º 30
0
  public FirstTaskForm execute(CommandContext commandContext) {
    ProcessDefinitionEntity processDefinitionEntity =
        Context.getProcessEngineConfiguration()
            .getDeploymentManager()
            .findDeployedProcessDefinitionById(processDefinitionId);

    if (processDefinitionEntity == null) {
      throw new IllegalArgumentException("cannot find processDefinition : " + processDefinitionId);
    }

    if (processDefinitionEntity.hasStartFormKey()) {
      return this.findStartEventForm(processDefinitionEntity);
    }

    ActivityImpl startActivity = processDefinitionEntity.getInitial();

    if (startActivity.getOutgoingTransitions().size() != 1) {
      throw new IllegalStateException(
          "start activity outgoing transitions cannot more than 1, now is : "
              + startActivity.getOutgoingTransitions().size());
    }

    PvmTransition pvmTransition = startActivity.getOutgoingTransitions().get(0);
    PvmActivity targetActivity = pvmTransition.getDestination();

    if (!"userTask".equals(targetActivity.getProperty("type"))) {
      logger.info("first activity is not userTask, just skip");

      return new FirstTaskForm();
    }

    FirstTaskForm firstTaskForm = new FirstTaskForm();
    firstTaskForm.setProcessDefinitionId(processDefinitionId);
    firstTaskForm.setExists(true);
    firstTaskForm.setTaskForm(true);

    String taskDefinitionKey = targetActivity.getId();
    logger.debug("activityId : {}", targetActivity.getId());
    firstTaskForm.setActivityId(taskDefinitionKey);

    TaskDefinition taskDefinition =
        processDefinitionEntity.getTaskDefinitions().get(taskDefinitionKey);

    Expression expression = taskDefinition.getAssigneeExpression();

    if (expression != null) {
      String expressionText = expression.getExpressionText();
      logger.debug("{}", expressionText);
      logger.debug("{}", startActivity.getProperties());
      logger.debug("{}", processDefinitionEntity.getProperties());
      firstTaskForm.setAssignee(expressionText);
    } else {
      logger.info("cannot find expression : {}, {}", processDefinitionId, taskDefinitionKey);
    }

    String initiatorVariableName =
        (String)
            processDefinitionEntity.getProperty(BpmnParse.PROPERTYNAME_INITIATOR_VARIABLE_NAME);
    firstTaskForm.setInitiatorName(initiatorVariableName);

    DefaultFormHandler formHandler = (DefaultFormHandler) taskDefinition.getTaskFormHandler();

    if (formHandler.getFormKey() != null) {
      String formKey = formHandler.getFormKey().getExpressionText();
      firstTaskForm.setFormKey(formKey);
    } else {
      logger.info("cannot formKey : {}, {}", processDefinitionId, taskDefinitionKey);
    }

    return firstTaskForm;
  }