Activiti的使用技巧

文章目录

  • Activiti的使用技巧
    • 1、环境的搭建:activiti-spring 7.0.0+连接池+mysql
      • 1.1 依赖如下:
      • 1.2 连接池和数据库配置:
      • 1.3 activiti的配置,通过config文件注入的方式:
    • 2、部署
      • 2.1 自动部署
      • 2.2 手动部署
      • 2.3 表单介绍
    • 3、创建流程表
    • 4、开始流程
    • 5、处理任务
      • 5.1 获取任务
      • 5.2 处理任务
    • 6、监听器设置:
      • 6.1 class方式:填写的是class全路径,具体的方法通过实现ExecutionListener,TaskListener判断实现
      • 6.2 expression方式:填写的是具体的方法,也就是class.method()
      • 6.3 delegateExpression方式:处理的是eventlistener,是处理对事件的监听,delegateExpression的意思是:class和events描述,delegate的意思是表达的方式是不是直接告诉Expression,有通过activiti。
    • 7、变量的设置:
    • 8、流程的操作
      • 8.1 委派任务
      • 8.2 根据指定人查询任务
      • 8.3 根据任务拥有者查询任务
      • 8.4 委派人完成任务
      • 8.5 将任务委派他人完成
      • 8.5 挂起流程实例
      • 8.6 删除流程实例
      • 8.7激活挂起的流程实例
      • 8.8 激活、挂起流程定义

Activiti的使用技巧

1、环境的搭建:activiti-spring 7.0.0+连接池+mysql

1.1 依赖如下:

    <properties>
        <java.version>1.11java.version>
    properties>

    <dependencies>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.activitigroupId>
            <artifactId>activiti-springartifactId>
            <version>7.0.0.GAversion>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.9version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.6version>
        dependency>

    dependencies>

1.2 连接池和数据库配置:

注意配置nullCatalogMeansCurrent=true,否则自动部署时,表无法创建成功。

spring:
  #业务核心数据源
  datasource:
    url: jdbc:mysql://localhost:3306/d201903290931?characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
    username: root
    password: 880808
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #druid配置
    druid:
      #initialSize
      initialSize: 10
      #minPoolSize
      minIdle: 10
      #maxPoolSize
      maxActive: 100
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 100
      #是否自动提交事务,如果应用中通过Spring或其他框架显示控制事务提交则可以设置为false,否则设置为true
      defaultAutoCommit: false
      #配置获取连接等待超时的时间
      maxWait: 10000
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒
      timeBetweenEvictionRunsMillis: 60000
      #配置一个连接在池中最小生存的时间,单位毫秒
      minEvictableIdleTimeMillis: 300000
      #连接检测属性配置
      testWhileIdle: true
      validationQuery: SELECT 'x' FROM DUAL
      validationQueryTimeout: 5000
      connectionProperties: oracle.net.CONNECT_TIMEOUT=3000;oracle.net.READ_TIMEOUT=5000
      removeAbandoned: true
      removeAbandonedTimeoutMillis: 300000
      testOnBorrow: false

1.3 activiti的配置,通过config文件注入的方式:

关注2点:自动部署的文件路径,监听器通过bean注入。

@Configuration
public class ActivitiConfig {
    @Autowired
    private MyExecutionListener myExecutionListener;
    @Autowired
    private MyTaskListener1 myTaskListener1;



    @Bean
    public ProcessEngine processEngine(DataSourceTransactionManager transactionManager, DataSource dataSource) throws IOException {
        SpringProcessEngineConfiguration configuration = new SpringProcessEngineConfiguration();
        //自动部署已有的流程文件
        Resource[] resources = new PathMatchingResourcePatternResolver().getResources(ResourceLoader.CLASSPATH_URL_PREFIX + "/processes/*.xml");
        configuration.setTransactionManager(transactionManager);
        configuration.setDataSource(dataSource);
        configuration.setDatabaseSchemaUpdate("true");
        configuration.setAsyncExecutorActivate(true);
        configuration.setHistoryLevel(HistoryLevel.FULL);
        configuration.setDeploymentResources(resources);
        Map<Object, Object> beans = new HashMap<>(10);
        beans.put("myExecutionListener", myExecutionListener);
        beans.put("myTaskListener1", myTaskListener1);
/*       beans.put("surveyProcessListener", surveyProcessListener);
        beans.put("lossVerificationProcessListener", lossVerificationProcessListener);
        beans.put("investigateProcessListener", investigateProcessListener);*/
        configuration.setBeans(beans);
        //configuration.setDbIdentityUsed(false);
        return configuration.buildProcessEngine();
    }

    @Bean
    public RepositoryService repositoryService(ProcessEngine processEngine) {
        return processEngine.getRepositoryService();
    }

    @Bean
    public RuntimeService runtimeService(ProcessEngine processEngine) {
        return processEngine.getRuntimeService();
    }

    @Bean
    public TaskService taskService(ProcessEngine processEngine) {
        return processEngine.getTaskService();
    }

    @Bean
    public HistoryService historyService(ProcessEngine processEngine) {
        return processEngine.getHistoryService();
    }

    @Bean
    public ManagementService managementService(ProcessEngine processEngine) {
        return processEngine.getManagementService();
    }

    //@Bean
    //public IdentityService identityService(ProcessEngine processEngine) {
//        return processEngine.getIdentityService();
//    }

}

当无法注入的时候,可以使用通用类,直接注入:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author xmaxing
 * @description
 * @date 2019-03-29 16:45
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    // Spring应用上下文环境
    @Autowired
    private static ApplicationContext applicationContext;
    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     *
     * @param applicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }
    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    /**
     * 获取对象
     *
     * @param name
     * @return Object
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

}

2、部署

2.1 自动部署

springboot会自动部署,就可以直接开始流程处理了。

1554040161025

2.2 手动部署

    @Override
    public boolean devlopActiviti(String folderPath, HashMap<String, String> map) {
        Deployment deploy = repositoryService.createDeployment()// 创建一个部署构建器
                .addClasspathResource(folderPath + File.separator + map.get("id") + ".bpmn")// 从类路径一次只能添加一个文件
                .addClasspathResource(folderPath + File.separator + map.get("id") + ".png")// 流程图片
                .name(map.get("name")).category(map.get("category")).deploy();

        LOGGER.info("流程名称【 {}】", deploy.getName());
        LOGGER.info("流程id【{}】", deploy.getId());
        LOGGER.info("流程类别【{}】", deploy.getCategory());

        return true;
    }

    @Override
    public boolean deployActivitiByZip(String folderPath, HashMap<String, String> map) {
        InputStream in = this.getClass().getClassLoader()
                .getResourceAsStream("folderPath" + File.separator + map.get("id") + ".bpmn");
        ZipInputStream zipInputStream = new ZipInputStream(in);
        Deployment deploy = repositoryService.createDeployment()// 创建一个部署构建器
                .addZipInputStream(zipInputStream).name(map.get("name")).category(map.get("category")).deploy();

        LOGGER.info("流程名称【 {}】", deploy.getName());
        LOGGER.info("流程id【{}】", deploy.getId());
        LOGGER.info("流程类别【{}】", deploy.getCategory());
        return true;
    }

测试

    @Test
    public void deplomentActiviti() {
        String folderPath = "study/activiti/diagrams/leaveBill";
        HashMap<String, String> map = new HashMap<>();
        map.put("name", "请假流程");// 名称
        map.put("id", "leaveBill");// id
        map.put("category", "办公流程");// 类别
       

2.3 表单介绍

ACT_RE_DEPLOYMENT(部署对象表)
ACT_RE_PROCDEF(流程定义表)
ACT_GE_BYTEARRAY(资源文件表)
ACT_GE_PROPERTY(主键生成表)


ACT_RE_*: 'RE'表示repository。 这个前缀的表包含了流程定义和流程静态资源 (图片,规则,等等)。
ACT_RU_*: 'RU'表示runtime。 这些运行时的表,包含流程实例,任务,变量,异步任务,等运行中的数据。 Activiti只在流程实例执行过程中保存这些数据, 在流程结束时就会删除这些记录。 这样运行时表可以一直很小速度很快。
ACT_ID_*: 'ID'表示identity。 这些表包含身份信息,比如用户,组等等。
ACT_HI_*: 'HI'表示history。 这些表包含历史数据,比如历史流程实例, 变量,任务等等。
ACT_GE_*: 'GE'表示general。通用数据, 用于不同场景下,如存放资源文件。

资源库流程规则表
   1) act_re_deployment 部署信息表
   2) act_re_model  流程设计模型部署表
   3) act_re_procdef  流程定义数据表

运行时数据库表
   1) act_ru_execution运行时流程执行实例表
   2) act_ru_identitylink运行时流程人员表,主要存储任务节点与参与者的相关信息
   3) act_ru_task运行时任务节点表
   4) act_ru_variable运行时流程变量数据表

历史数据库表
    1) act_hi_actinst 历史节点表
    2) act_hi_attachment历史附件表
    3) act_hi_comment历史意见表
    4) act_hi_identitylink历史流程人员表
    5) act_hi_detail历史详情表,提供历史变量的查询
    6) act_hi_procinst历史流程实例表
    7) act_hi_taskinst历史任务实例表
    8) act_hi_varinst历史变量表

组织机构表
    1) act_id_group用户组信息表
    2) act_id_info用户扩展信息表
    3) act_id_membership用户与用户组对应信息表
    4) act_id_user用户信息表

这四张表很常见,基本的组织机构管理,关于用户认证方面建议还是自己开发一套,组件自带的功能太简单,使用中有很多需求难以满足

通用数据表
    1) act_ge_bytearray二进制数据表
    2) act_ge_property属性数据表存储整个流程引擎级别的数据,初始化表结构时,会默认插入三条记录。

3、创建流程表

startevent–>usertask1–>usertask2–>endevent

  <process id="listenerTask1" name="任务监听器流程" isExecutable="true">
    <startEvent id="startevent" name="Start">
      <extensionElements>
        <activiti:executionListener event="start" expression="${myExecutionListener.processStart(execution)}">activiti:executionListener>
      extensionElements>
    startEvent>
    <endEvent id="endevent1" name="End">endEvent>
    <userTask id="usertask1" name="User Task" activiti:assignee="#{createLoginName}">
      <extensionElements>
        <activiti:taskListener event="complete" expression="${myTaskListener1.taskComplete(task)}">
          <activiti:field name="arg">
            <activiti:string>activiti:string>
          activiti:field>
        activiti:taskListener>
      extensionElements>
    userTask>
    <sequenceFlow id="flow1" sourceRef="startevent" targetRef="usertask1">sequenceFlow>
    <sequenceFlow id="flow2" sourceRef="usertask1" targetRef="endevent1">sequenceFlow>
    <userTask id="usertask2" name="User Task" activiti:assignee="#{checkBywhom}">userTask>
    <sequenceFlow id="flow3" sourceRef="usertask1" targetRef="usertask2">sequenceFlow>
    <endEvent id="endevent2" name="End">endEvent>
    <sequenceFlow id="flow4" sourceRef="usertask2" targetRef="endevent2">sequenceFlow>
  process>

4、开始流程

    @Override
    public boolean startActiviti(String processDefinitionKey, HashMap<String, Object> map) {
        // 取得流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, map);

        LOGGER.info("流程(流程执行对象实例)id【{}】", processInstance.getId());// execution对象
        LOGGER.info("流程实例id:【{}】", processInstance.getProcessInstanceId());// processInstance对象
        LOGGER.info("流程定义id【{}】", processInstance.getProcessDefinitionId());// 默认为最新的id
        return true;
    }
    @Test
    public void startActiviti() {
        String processDefinitionKey = "listenerTask1";
        // 设置变量
        HashMap<String, Object> map = new HashMap<>();
        map.put("createLoginName", "31smart.geng.123");
        activitiService.startActiviti(processDefinitionKey, map);
    }

注意:流程实例ID(process的ID),流程定义ID(process的定义描述ID),执行对象ID(process的具体task的ID),processDefinitionKey为流程的定义的名称。

1554042042906

2019-03-31 22:27:18.776  INFO 1528 --- [           main] c.e.d.service.Impl.ActivitiServiceImpl   : 流程(流程执行对象实例)id【175001】
2019-03-31 22:27:18.776  INFO 1528 --- [           main] c.e.d.service.Impl.ActivitiServiceImpl   : 流程实例id:【175001】
2019-03-31 22:27:18.777  INFO 1528 --- [           main] c.e.d.service.Impl.ActivitiServiceImpl   : 流程定义id【listenerTask1:10:160009】

5、处理任务

5.1 获取任务

    @Override
    public boolean getTaskByLoginName(String processDefinitionKey, String loginName) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        List<Task> list = taskQuery.processDefinitionKey(processDefinitionKey).taskAssignee(loginName).list();

        for (Task task : list) {
            LOGGER.info("任务处理人【{}】", task.getAssignee());
            LOGGER.info("流程名称【{}】", task.getName());
            LOGGER.info("任务id【{}】", task.getId());
            LOGGER.info("流程定义id【{}】", task.getProcessDefinitionId());
            LOGGER.info("执行对象id【{}】", task.getExecutionId());
        }
        return true;
    }
    @Override
    public List<Task> getTaskByDeploymentId(String deploymentId, String processDefinitionKey, String executionId,
                                            String loginName) {
        List<Task> list = taskService.createTaskQuery().processDefinitionKey(processDefinitionKey)
                .deploymentId(deploymentId).taskAssignee(loginName).executionId(executionId).list();
        // 获取当前人的
        return list;
    }

5.2 处理任务

   @Override
    public boolean startActivitiAndFinsh(String processDefinitionKey, HashMap<String, Object> map) {
        // 取得流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, map);

        LOGGER.info("流程(流程执行对象实例)id【{}】", processInstance.getId());// execution对象
        LOGGER.info("流程实例id:【{}】", processInstance.getProcessInstanceId());// processInstance对象
        LOGGER.info("流程定义id【{}】", processInstance.getProcessDefinitionId());// 默认为最新的id
        LOGGER.info("流程实例id【{}】", processInstance.getSuperExecutionId());
        List<Task> tasks = this.getTaskByDeploymentId(processInstance.getDeploymentId(), processDefinitionKey,
                processInstance.getId(), (String) map.get("createLoginName"));

        for (Task task : tasks) {
            this.finshTask(task.getId());
        }

        return true;
    }
    @Test
    public void finshTask() {
        String taskId = "137507";
        // 设置变量
        HashMap<String, Object> map = new HashMap<>();
        map.put("checkBywhom", "3001smart.geng.123");
        activitiService.finshTask(taskId,map);
//        activitiService.finshTask(taskId);
    }

6、监听器设置:

6.1 class方式:填写的是class全路径,具体的方法通过实现ExecutionListener,TaskListener判断实现

  <process id="listenerTask" name="任务监听器流程" isExecutable="true">
    <startEvent id="startevent" name="Start">
      <extensionElements>
        <activiti:executionListener event="start" class="com.example.demo13.service.ActivitiListener">activiti:executionListener>
      extensionElements>
    startEvent>
    <endEvent id="endevent1" name="End">endEvent>
    <userTask id="usertask1" name="User Task" activiti:assignee="#{createLoginName}">
      <extensionElements>
        <activiti:taskListener event="complete" class="com.example.demo13.service.MyTaskListener">
          <activiti:field name="arg">
            <activiti:string>activiti:string>
          activiti:field>
        activiti:taskListener>
      extensionElements>
public class ActivitiListener implements ExecutionListener,TaskListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(ActivitiServiceImpl.class);

    private static final long serialVersionUID = 6200534335483960408L;

    private Expression arg;



    public Expression getArg() {
        return arg;
    }

    public void setArg(Expression arg) {
        this.arg = arg;
    }

    @Override
    public void notify(DelegateExecution execution) {
        String eventName = execution.getEventName();
        // start
        if ("start".equals(eventName)) {
            LOGGER.info("start=========");
            HashMap<String, Object> map = new HashMap<>();
        } else if ("end".equals(eventName)) {
            LOGGER.info("end=========");
        } else if ("take".equals(eventName)) {
            LOGGER.info("take=========");
        }

    }

    @Override
    public void notify(DelegateTask delegateTask) {

        // 实现TaskListener中的方法
        String eventName = delegateTask.getEventName();
        LOGGER.info("任务监听器:{}", arg.getValue(delegateTask));
        if ("create".endsWith(eventName)) {
            LOGGER.info("create=========");
        } else if ("assignment".endsWith(eventName)) {
            LOGGER.info("assignment========");
        } else if ("complete".endsWith(eventName)) {

            LOGGER.info("complete===========");
        } else if ("delete".endsWith(eventName)) {
            LOGGER.info("delete=============");
        }

    }

}

6.2 expression方式:填写的是具体的方法,也就是class.method()

  <process id="listenerTask1" name="任务监听器流程" isExecutable="true">
    <startEvent id="startevent" name="Start">
      <extensionElements>
        <activiti:executionListener event="start" expression="${myExecutionListener.processStart(execution)}">activiti:executionListener>
      extensionElements>
    startEvent>
    <endEvent id="endevent1" name="End">endEvent>
    <userTask id="usertask1" name="User Task" activiti:assignee="#{createLoginName}">
      <extensionElements>
        <activiti:taskListener event="complete" expression="${myTaskListener1.taskComplete(task)}">
          <activiti:field name="arg">
            <activiti:string>activiti:string>
          activiti:field>
        activiti:taskListener>
      extensionElements>

类需要添加到bean()

        Map<Object, Object> beans = new HashMap<>(10);
        beans.put("myExecutionListener", myExecutionListener);
        beans.put("myTaskListener1", myTaskListener1);
/*       beans.put("surveyProcessListener", surveyProcessListener);
        beans.put("lossVerificationProcessListener", lossVerificationProcessListener);
        beans.put("investigateProcessListener", investigateProcessListener);*/
        configuration.setBeans(beans);
@Service
public class MyExecutionListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(ActivitiServiceImpl.class);

    public void processStart(DelegateExecution execution) {
        LOGGER.info("start===================================================================");

    }

}
@Service
public class MyTaskListener1 {
    private static final Logger LOGGER = LoggerFactory.getLogger(ActivitiServiceImpl.class);

    private Expression arg;

    public Expression getArg() {
        return arg;
    }

    public void setArg(Expression arg) {
        this.arg = arg;
    }

    public void taskComplete(DelegateTask task) {
//        LOGGER.info("任务监听器:{}", arg.getValue(delegateTask));

        LOGGER.info("任务监听器:complete===========");

    }

}

6.3 delegateExpression方式:处理的是eventlistener,是处理对事件的监听,delegateExpression的意思是:class和events描述,delegate的意思是表达的方式是不是直接告诉Expression,有通过activiti。

示例如下:

    <extensionElements>
      <activiti:eventListener events="ACTIVITY_CANCELLED" delegateExpression="${surveyProcessListener}">activiti:eventListener>
    extensionElements>
 <extensionElements>
    <activiti:eventListener class="org.activiti.engine.test.MyEventListener" />
    <activiti:eventListener delegateExpression="${testEventListener}" events="JOB_EXECUTION_SUCCESS,JOB_EXECUTION_FAILURE" />
  extensionElements>
  <extensionElements>
    <activiti:eventListener class="org.activiti.engine.test.MyEventListener" entityType="task" />
    <activiti:eventListener delegateExpression="${testEventListener}" events="ENTITY_CREATED" entityType="task" />
  extensionElements>
Supported values for the entityType are: attachment, comment, execution, identity-link, job, process-instance, process-definition, task.
@Service
public class SurveyProcessListener implements ActivitiEventListener {}

    @Override
    public void onEvent(ActivitiEvent event) {
        //如果流程取消
        if (ActivitiEventType.ACTIVITY_CANCELLED == event.getType()) {
            // TODO: 2019-03-08 流程取消,发送各种消息,
            String processInstanceId = event.getProcessInstanceId();
            log.info("surveyProcessListener.onEvent.ACTIVITY_CANCELLED, processInstanceId:{}", processInstanceId);
        }

    }

    @Override
    public boolean isFailOnException() {
        return false;
    }
}

7、变量的设置:

在代理监听器里无法注入RuntimeService或者taskService,使用bean注入,或者使用delegateTask.setVariable

            ((RuntimeService)SpringContextUtil.getBean("runtimeService")).setVariable(delegateTask.getExecutionId(),"checkBywhom", "x00000000xoo");
           runtimeService.setVariable(delegateTask.getExecutionId(),"checkBywhom", "xxoo");
delegateTask.setVariable("checkBywhom", "xxxxxxx");
            LOGGER.info("complete===========");
  @Override
    public boolean setVariableByExcutionId(String executionId, boolean isLocal, HashMap<String, Object> map) {
        /*
         * runtimeService.setVariablesLocal(executionId, variableName, value);
         *
         * 设置本执行对象的变量,该作用域只在当前的executionId中 runtimeService.setVariableLocal(executionId,
         * variableName, value);
         *
         * 可以设置对个变量,放在map中
         */
        if (isLocal) {
            runtimeService.setVariablesLocal(executionId, map);
        } else {
            runtimeService.setVariables(executionId, map);
        }
        return true;
    }

    @Override
    public Map<String, Object> getVariableByExcutionId(String executionId, boolean isLocal) {
        Map<String, Object> variablesMap = new HashMap<String, Object>();
        if (isLocal) {
            variablesMap = runtimeService.getVariablesLocal(executionId);
        } else {
            variablesMap = runtimeService.getVariables(executionId);
        }
        return variablesMap;
    }

    @Override
    public boolean setVariableByTaskId(String taskId, String objectName, Object object) {
        taskService.setVariable(taskId, objectName, object);
        return true;
    }
    @Override
    public boolean setVariableByTaskId(String taskId, boolean isLocal, HashMap<String, Object> map) {
        /*
         * taskService.setVariable(taskId, variableName, value);
         *
         * 设置本执行对象的变量,该作用域只在当前的executionId中 taskService.setVariableLocal(taskId,
         * variableName, value); 可以设置对个变量,放在map中
         */
        if (isLocal) {
            taskService.setVariablesLocal(taskId, map);
        } else {
            taskService.setVariables(taskId, map);
        }
        return true;
    }

    @Override
    public Map<String, Object> getVariableByTaskId(String taskId, boolean isLocal) {
        Map<String, Object> variablesMap = new HashMap<String, Object>();
        if (isLocal) {
            variablesMap = taskService.getVariablesLocal(taskId);
        } else {
            variablesMap = taskService.getVariables(taskId);
        }
        return variablesMap;
    }
    @Override
    public <T> T getVariableByTaskId(String taskId, String objectName, Class<T> tClass) {
        T bean = (T) taskService.getVariable(taskId, objectName);
        return bean;
    }


    @Override
    public boolean delegateTask(String taskId, String loginName) {
        taskService.delegateTask(taskId, loginName);
        return true;
    }

8、流程的操作

8.1 委派任务

	 /**
     * 委派任务
     *
     * @param taskId
     * @param loginName
     * @return
     */
    boolean delegateTask(String taskId, String loginName);

    @Override
    public boolean delegateTask(String taskId, String loginName) {
        taskService.delegateTask(taskId, loginName);
        return true;
    }

	 /**
     * 指定代办人
     */
    @Test
    public void delegateTask() {
        String taskId = "2511";
        String loginName = "0003";
        activitiService.delegateTask(taskId, loginName);
    }

8.2 根据指定人查询任务

    /**
     * 根据指定人查询任务
     *
     * @param processDefinitionKey
     * @param assignee
     * @return
     */
    boolean getTaskByAssignee(String processDefinitionKey, String assignee);


    @Override
    public boolean getTaskByAssignee(String processDefinitionKey, String assignee) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 任务列表
        List<Task> list = taskQuery.processDefinitionKey(processDefinitionKey).taskAssignee(assignee).list();// 指定办理人
        for (Task task : list) {
            LOGGER.info("任务处理人【{}】", task.getAssignee());
            LOGGER.info("流程名称【{}】", task.getName());
            LOGGER.info("任务id【{}】", task.getId());
            LOGGER.info("流程定义id【{}】", task.getProcessDefinitionId());
            LOGGER.info("执行对象id【{}】", task.getExecutionId());
        }
        return true;
    }


    @Test
    public void getTaskByAssignee() {
        String processDefinitionKey = "delegateTask";
        String assignee = "0003";
        activitiService.getTaskByAssignee(processDefinitionKey, assignee);
    }

8.3 根据任务拥有者查询任务

/**
 * 根据任务拥有者查询任务
 *
 * @param processDefinitionKey
 * @param owner
 * @return
 */
boolean getTaskByOwner(String processDefinitionKey, String owner);

    @Override
    public boolean getTaskByOwner(String processDefinitionKey, String owner) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 任务列表
        List<Task> list = taskQuery.processDefinitionKey(processDefinitionKey).taskOwner(owner).list();// 指定办理人
        for (Task task : list) {
            LOGGER.info("任务处理人【{}】", task.getAssignee());
            LOGGER.info("流程名称【{}】", task.getName());
            LOGGER.info("任务id【{}】", task.getId());
            LOGGER.info("流程定义id【{}】", task.getProcessDefinitionId());
            LOGGER.info("执行对象id【{}】", task.getExecutionId());
            LOGGER.info("任务拥有者【{}】", task.getOwner());
        }
        return true;
    }


    @Test
    public void getTaskByOwner() {
        String processDefinitionKey = "delegateTask";
        String owner = "0003";
        activitiService.getTaskByOwner(processDefinitionKey, owner);
    }

8.4 委派人完成任务

/**
 * 委派人完成任务
 *
 * @param taskId
 * @param map
 * @return
 */
boolean resolveTask(String taskId, Map<String, Object> map);

    @Override
    public boolean resolveTask(String taskId, Map<String, Object> map) {
        taskService.resolveTask(taskId, map);
        return true;
    }

    /**
     * 正在运行的任务表中被委派人办理任务后任务会回到委派人 ,历史任务表中也一样,只是多了一个人进行审批
     */
    @Test
    public void resolveTask() {
        String taskId = "2511";
        Map<String, Object> map = new HashMap<>();
        activitiService.resolveTask(taskId, map);
    }

8.5 将任务委派他人完成

/**
 * 将任务委派他人完成
 *
 * @param taskId
 * @param assignee
 * @return
 */
boolean trunTask(String taskId, String assignee);

    @Override
    public boolean trunTask(String taskId, String assignee) {
        taskService.setAssignee(taskId, assignee);
        return true;
    }

    /**
     * 任务转办,将任务交给其他人处理
     */
    @Test
    public void turnTask() {
        String taskId = "7511";
        String assignee = "0003";
        activitiService.trunTask(taskId, assignee);
    }

8.5 挂起流程实例

/**
 * 挂起流程实例
 *
 * @param processInstanceId
 * @return
 */
boolean suspendProcessInstanceById(String processInstanceId);

    @Override
    public boolean suspendProcessInstanceById(String processInstanceId) {
        runtimeService.suspendProcessInstanceById(processInstanceId);
        return true;
    }

    /**
     * 挂起流程
     */
    @Test
    public void suspendProcess() {
        //SuspensionState ACTIVE = new SuspensionStateImpl(1, "active"); 激活
        //  SuspensionState SUSPENDED = new SuspensionStateImpl(2, "suspended"); 挂起
        String processInstanceId = "70001";
        activitiService.suspendProcessInstanceById(processInstanceId);
    }

8.6 删除流程实例

/**
 * 删除流程实例
 *
 * @param processInstanceId
 * @param reason
 * @return
 */
boolean deleteProcessInstance(String processInstanceId, String reason);

    @Override
    public boolean deleteProcessInstance(String processInstanceId, String reason) {
        runtimeService.deleteProcessInstance(processInstanceId, reason);
        return true;
    }

    @Test
    public void deleteProcessInstance() {
        String processInstanceId = "70001";
        String reason = "删除原因";
        activitiService.deleteProcessInstance(processInstanceId, reason);
    }

8.7激活挂起的流程实例

/**
 * 激活流程实例(激活挂起的流程实例)
 *
 * @param processInstanceId
 * @return
 */
boolean activateProcessInstanceById(String processInstanceId);

    @Override
    public boolean activateProcessInstanceById(String processInstanceId) {
        runtimeService.activateProcessInstanceById(processInstanceId);
        return true;
    }

    @Test
    public void activateProcessInstanceById(){
        String processInstanceId = "70001";
        activitiService.activateProcessInstanceById(processInstanceId);
    }

8.8 激活、挂起流程定义

/**
 * 挂起流程定义
 *
 * @param processDefineKey
 * @param cascade
 * @return
 */
boolean suspendProcessDefineKey(String processDefineKey, boolean cascade);

/**
 * 激活流程定义
 *
 * @param processDefineKey
 * @param cascade
 * @return
 */
boolean activateProcessDefinitionByKey(String processDefineKey, boolean cascade);

    @Override
    public boolean suspendProcessDefineKey(String processDefineKey, boolean cascade) {
        repositoryService.suspendProcessDefinitionByKey(processDefineKey,cascade,new Date());
        return true;
    }

    @Override
    public boolean activateProcessDefinitionByKey(String processDefineKey,boolean cascade){
        repositoryService.activateProcessDefinitionByKey(processDefineKey,cascade,new Date());
        return true;
        
    @Test
    public void suspendProcessDefineBykey(){
        String processDefineKey = "";
        boolean cascade = true;
        activitiService.suspendProcessDefineKey(processDefineKey,cascade);
    }

你可能感兴趣的:(java,web,JAVA,WEB)