activiti 中經常使用的操做

activiti中提供了7個經常使用的對象(repositoryService, runtimeService, taskService, historyService, formService, identityService, managementService),7個對象均可以經過ProcessEngine來得到,activiti的操做有這7個對量來完成,下面介紹工做流開發中經常使用的操做。java

一、發佈流程spring

流程的發佈有多種方式,能夠根據zip, 源碼等方式發佈json

(1)zip形式發佈ide

//加載默認配置文件,查看源碼能夠看到resources = classLoader.getResources("activiti.cfg.xml");,會默認加載activiti.cfg.xml文件, 若是配置文件不是以這個文件命名的,須要以ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("Activititest.cfg.xml").buildProcessEngine(); 這種方式


ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
	/*
	 * 經過zip 發佈流程
	 */
	@Test
	public void deploymentProcessDefinitionBy_Zip(){
		InputStream in = this.getClass().getClassLoader().getResourceAsStream("diagrams/helloworld.zip");
		ZipInputStream zipInputStream = new ZipInputStream(in);
		Deployment deployment = processEngine.getRepositoryService()
				.createDeployment()
				.name("請假流程")
				.addZipInputStream(zipInputStream)
				.deploy();
		
		System.out.println("id = "+ deployment.getId());
		System.out.println("流程名稱 = "+ deployment.getName());
	}

(2)源碼形式發佈ui

// 須要注意的地方是getResourceAsStream 的路徑問題,/diagrams/ 前面的/ 何時要何時不要,須要注意
@Test
public void deployProcess(){
InputStream inputStream = this.getClass().getResourceAsStream("/diagrams/processVariables.bpmn");
InputStream inputStreamPng = this.getClass().getResourceAsStream("/diagrams/processVariables.png");
		
		Deployment deploy = processEngine.getRepositoryService()
			.createDeployment()
			.name("流程定義")
			.addInputStream("processVariables.bpmn", inputStream)
			.addInputStream("processVariables.png", inputStreamPng)
			.deploy();
		System.out.println("id = "+ deploy.getId());
		System.out.println("name = "+ deploy.getName());
	}

    以上流程發佈以後會在 act_re_deploment 和act_re_procdef 插入數據,act_re_procdef 表示流程的定義,包括版本,流程定義ID、流程的Name,Key等信息,act_re_deploment 表裏面存放流程部署的信息,部署的種類,名稱和流程發佈的ID等信息。this

一、流程啓動code

      流程啓動有多種方式,能夠根據RunService提供的API 去選擇適合本身的流程啓動orm

     按照流程定義的ID啓動xml

ProcessInstance processInstance = runtimeService
                .startProcessInstanceById(processDefinitionId, businessKey, variables);

    businessKey 是流程鏈接業務的通常是用過流程定義的ID+用戶表單ID,如流程定義ID爲publicIPApplication:1:4,表單ID爲111,那麼businessKey 爲:publicIPApplication:1:4-111 對象

     variables 是Map<String, Object> 類型,存放流程過程當中須要的變量信息

二、獲取流程部署信息

//獲取流程部署信息
    public Map<String, Object> findDeploymentList(String category, int page, int pageSize) {
        List<Map<String, Object>> objectList = new ArrayList<Map<String, Object>>();
        logger.info("獲取流程部署信息");
        List<Deployment> deploymentList = new ArrayList<Deployment>();
        long count = 0;
        if (null != category && !"".equals(category)) {
            deploymentList = repositoryService.createDeploymentQuery().deploymentCategory(category)
                    .orderByDeploymenTime().desc() //按照發布的時間生序排序
                    .listPage((page - 1) * pageSize, pageSize); // activiti 提供的分頁
            count = repositoryService.createDeploymentQuery().deploymentCategory(category).count();

        } else {
            deploymentList = repositoryService.createDeploymentQuery().orderByDeploymenTime().desc() //按照發布的時間生序排序
                    .listPage((page - 1) * pageSize, pageSize);
            count = repositoryService.createDeploymentQuery().count();
        }

        logger.info("獲取流程部署部分屬性信息");
        for (Deployment deployment : deploymentList) {
            Map<String, Object> objectMap = new HashMap<String, Object>();
            objectMap.put("id", deployment.getId());
            objectMap.put("name", deployment.getName());
            objectMap.put("category", deployment.getCategory());
            objectMap.put("deploymentTime", deployment.getDeploymentTime());

            logger.info("獲取流程定義信息");
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery()
                    .deploymentId(deployment.getId()).singleResult();
            objectMap.put("pdid", pd.getId());

            logger.info("獲取流程部署人信息");
            // 這個地方須要獲取流程部署人信息,我這邊是新建一張表用來存放流程部署人信息和部署信息
            ActivitiDeploymentCreator creator = deploymentCreatorService
                    .getDeploymentCreatorByDeploymentId(deployment.getId());
            if (null != creator) {
                objectMap.put("creator", creator.getCreator());
                objectMap.put("creatorId", creator.getCreatorId());
            } else {
                objectMap.put("creator", null);
                objectMap.put("creatorId", null);
            }

            objectList.add(objectMap);
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("data", objectList);
        resultMap.put("count", count);
        return resultMap;
    }

三、獲取任務的連線信息

// 根據taskid 獲取 任務連線的名稱信息
    public List<String> findOutComeListByTaskId(String taskId) {
        //返回存放連線的名稱集合
        List<String> list = new ArrayList<String>();
        //1:使用任務ID,查詢任務對象
        Task task = taskService.createTaskQuery()//
                .taskId(taskId)//使用任務ID查詢
                .singleResult();
        //2:獲取流程定義ID
        String processDefinitionId = task.getProcessDefinitionId();
        //3:查詢ProcessDefinitionEntiy對象
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) repositoryService
                .getProcessDefinition(processDefinitionId);
        //使用任務對象Task獲取流程實例ID
        String processInstanceId = task.getProcessInstanceId();
        //使用流程實例ID,查詢正在執行的執行對象表,返回流程實例對象
        ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
                .processInstanceId(processInstanceId)//使用流程實例ID查詢
                .singleResult();
        //獲取當前活動的id
        String activityId = pi.getActivityId();
        //4:獲取當前的活動
        ActivityImpl activityImpl = processDefinitionEntity.findActivity(activityId);
        //5:獲取當前活動完成以後連線的名稱
        List<PvmTransition> pvmList = activityImpl.getOutgoingTransitions();
        if (pvmList != null && pvmList.size() > 0) {
            for (PvmTransition pvm : pvmList) {
                String name = (String) pvm.getProperty("name");
                if (StringUtils.isNotBlank(name)) {
                    list.add(name);
                } else {
                    list.add("默認提交");
                }
            }
        }
        return list;
    }

四、獲取批註信息

/**獲取批註信息,傳遞的是當前任務ID,獲取歷史任務ID對應的批註*/
    public List<Comment> findCommentByProcessInstanceId(String processInstanceId) {
        List<Comment> list = new ArrayList<Comment>();
        //使用當前的任務ID,查詢當前流程對應的歷史任務ID
        //使用當前任務ID,獲取當前任務對象
        //        Task task = taskService.createTaskQuery()//
        //                .taskId(taskId)//使用任務ID查詢
        //                .singleResult();
        //獲取流程實例ID
        //        String processInstanceId = task.getProcessInstanceId();
        //使用流程實例ID,查詢歷史任務,獲取歷史任務對應的每一個任務ID
        //              List<HistoricTaskInstance> htiList = historyService.createHistoricTaskInstanceQuery()//歷史任務表查詢
        //                              .processInstanceId(processInstanceId)//使用流程實例ID查詢
        //                              .list();
        //              //遍歷集合,獲取每一個任務ID
        //              if(htiList!=null && htiList.size()>0){
        //                  for(HistoricTaskInstance hti:htiList){
        //                      //任務ID
        //                      String htaskId = hti.getId();
        //                      //獲取批註信息
        //                      List<Comment> taskList = taskService.getTaskComments(htaskId);//對用歷史完成後的任務ID
        //                      list.addAll(taskList);
        //                  }
        //              }
        list = taskService.getProcessInstanceComments(processInstanceId);
        return list;
    }

五、暫停流程

/* 
     * 
     * 根據流程實例ID,暫停流程實例
     */
    public JsonResult suspendProcessInstance(String processInstanceId) {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(120000);
        if (null != pi) {
            if (pi.isSuspended()) {
                jsonResult.setMessage("已經暫停,請勿重複提交");
            } else {
                runtimeService.suspendProcessInstanceById(processInstanceId);
                System.out.println("流程實例ID" + processInstanceId + "暫停");
                logger.info("流程實例ID" + processInstanceId + "暫停");
                jsonResult.setMessage("已經暫停");
            }
        } else {
            jsonResult.setMessage("正在運行的流程實例ID:" + processInstanceId + "不存在");
            jsonResult.setCode(14000);
        }

        return jsonResult;

    }

六、激活流程

/*
     * 激活流程實例
     */
    public JsonResult activiProcessInstance(String processInstanceId) {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(12000);
        String message = null;
        if (null != pi) {
            if (!pi.isSuspended()) {
                message = "已經激活,請勿重複提交";
            } else {
                runtimeService.activateProcessInstanceById(processInstanceId);
                message = "流程實例id" + processInstanceId + " 已激活";
                logger.warning(message);
            }
        } else {
            message = "流程實例id" + processInstanceId + "不存在";
            logger.warning(message);
        }

        jsonResult.setMessage(message);
        return jsonResult;
    }

七、讀取正在運行流程圖

/*
     * 
     * 讀取資源
     */
    public InputStream readProcessResource(String processInstanceId) {
        logger.info("獲取流程執行圖片");
        HistoricProcessInstance historicProcessInstance = historyService
                .createHistoricProcessInstanceQuery().processInstanceId(processInstanceId)
                .singleResult();
        if (null != historicProcessInstance.getEndTime()) {
            logger.info("流程實例已經結束");

        } else {
            logger.info("流程實例已經結束");
        }
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();
        BpmnModel bpmnModel = repositoryService
                .getBpmnModel(processInstance.getProcessDefinitionId());
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);
        // 不使用spring請使用下面的兩行代碼
        //    ProcessEngineImpl defaultProcessEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine();
        //    Context.setProcessEngineConfiguration(defaultProcessEngine.getProcessEngineConfiguration());

        // 使用spring注入引擎請使用下面的這行代碼
        processEngineConfiguration = processEngine.getProcessEngineConfiguration();
        Context.setProcessEngineConfiguration(
                (ProcessEngineConfigurationImpl) processEngineConfiguration);

        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration
                .getProcessDiagramGenerator();
        InputStream imageStream = diagramGenerator.generateDiagram(bpmnModel, "png",
                activeActivityIds, new ArrayList<String>(), "宋體", "宋體", null, 1.0);
        return imageStream;
    }

八、讀取流程定義的流程圖

public InputStream readProcessDefinitionResource(String processDefinitionId, int type) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefinitionId).singleResult();
        String resourceName = "";
        if (StatusUtil.FILE_IMAGE_TYPE == type) {
            resourceName = processDefinition.getDiagramResourceName();
        } else if (StatusUtil.FILE_XML_TYPE == type) {
            resourceName = processDefinition.getResourceName();
        }
        InputStream resourceAsStream = repositoryService
                .getResourceAsStream(processDefinition.getDeploymentId(), resourceName);

        return resourceAsStream;
    }

九、獲取流程變量

// 獲取任務變量
    public Map<String, Object> getTaskVaVariables(String taskId) {
        System.out.println(taskId);

        List<HistoricVariableInstance> historicVariableInstance = historyService
                .createHistoricVariableInstanceQuery().taskId(taskId).list();
        System.out.println(historicVariableInstance.size());

        //        HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        //        Map<String, Object> map = historicTaskInstance.getTaskLocalVariables();
        //        System.out.println(map.isEmpty());
        //        for(Entry<String, Object> entry: map.entrySet()){
        //            System.out.println(entry.getKey() + " = "+ entry.getValue());
        //        }
        //        return historicTaskInstance.getTaskLocalVariables();

        Map<String, Object> taskMap = new HashMap<String, Object>();

        for (HistoricVariableInstance hv : historicVariableInstance) {
            taskMap.put(hv.getVariableName(), hv.getValue());
        }

        return taskMap;
    }
相關文章
相關標籤/搜索