activiti 中常用的操作

activiti中提供了7个常用的对象(repositoryService, runtimeService, taskService, historyService, formService, identityService, managementService),7个对象都可以通过ProcessEngine来获得,activiti的操作有这7个对量来完成,下面介绍工作流开发中常用的操作。

1、发布流程

流程的发布有多种方式,可以根据zip, 源码等方式发布

(1)zip形式发布

//加载默认配置文件,查看源码可以看到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)源码形式发布

// 需要注意的地方是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等信息。

1、流程启动

      流程启动有多种方式,可以根据RunService提供的API 去选择适合自己的流程启动

     按照流程定义的ID启动

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> 类型,存放流程过程中需要的变量信息

2、获取流程部署信息

//获取流程部署信息
    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;
    }

3、获取任务的连线信息

// 根据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;
    }

4、获取批注信息

/**获取批注信息,传递的是当前任务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;
    }

5、暂停流程

/* 
     * 
     * 根据流程实例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;

    }

6、激活流程

 /*
     * 激活流程实例
     */
    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;
    }

7、读取正在运行流程图

/*
     * 
     * 读取资源
     */
    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;
    }

8、读取流程定义的流程图

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;
    }

9、获取流程变量

// 获取任务变量
    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;
    }

 

转载于:https://my.oschina.net/u/1433803/blog/888673

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值