activiti7---自定义流程图(springboot项目)

之前的文章中我们绘制流程图时,都是需要依赖IDEA的activiti7插件,不灵活。

本篇文章的目的是通过特定的数据结构,能实现前端页面自定义配置流程图。

1.yml文件

spring:
 datasource:
  url: jdbc:mysql://ip:3306/activiti7?useUnicode=true&useSSL=false&zeroDateTimeBehavior=convertToNull&characterEncoding=utf8&serverTimezone=GMT%2B8
  username : root
  password : root
  driver-class-name: com.mysql.jdbc.Driver

 activiti:
  #Activiti记录历史任务数据级别,full是最全的,方便日后查询使用
  history-level: full
  #创建数据库历史数据表
  db-history-used: true

2.pom文件(主要依赖)

        

       
        
            org.activiti
            activiti-spring-boot-starter
            7.0.0.SR1
        
        
        
            org.activiti
            activiti-image-generator
            5.22.0
        
        
            org.activiti
            activiti-bpmn-layout
            6.0.0.RC1
        

3.安全配置类

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@Order(1)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    /**
     * aciviti7默认整合springSecurity,这里全部放行
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }

}

4.流程图基本信息类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class WorkFlow {
    private Integer id;
    private  String name;
    private  String content;
}

5.流程图步骤类


import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.List;

@Data
@AllArgsConstructor
public class Step {
    private Integer id;
    private Integer workFlowId;
    private String name;
    private Integer type;
    private Integer orderId;
    //接下要执行的步骤,用于连线
    private List chlidOrderIds;
    private String conditionExpression;
    private String assignee;
    //0为人工任务,1为服务于任务
    //private Integer taskType;

}

6.流程的定义与部署

其它的查询任务,执行任务与之前的逻辑一致。

import com.example.springactiviti.entity.Step;
import com.example.springactiviti.entity.WorkFlow;
import org.activiti.bpmn.BpmnAutoLayout;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ProcessController3 {

    @Autowired
    private RepositoryService repositoryService;  //流程定义和流程部署相关功能

    @Autowired
    private ProcessEngine processEngine;  //流程引擎

    /**
     * 动态流程实例并输出png和xml
     *
     * @throws IOException
     */
    @GetMapping("/createDeployment3")
    public String createDeployment3() throws IOException {
        //模拟前端页面数据
        WorkFlow workFlow = new WorkFlow(1, "test", "流程测试");
        List stepList = new ArrayList<>();
        List childList1 = new ArrayList<>();
        childList1.add(2);
        Step s1 = new Step(1, workFlow.getId(), "start", 1, 1, childList1, null, null);
        List childList2 = new ArrayList<>();
        childList2.add(3);
        childList2.add(4);
        Step s2 = new Step(2, workFlow.getId(), "parallelGateway-fork", 2, 2, childList2, null, "a");
        List childList3 = new ArrayList<>();
        childList3.add(6);
        Step s3 = new Step(3, workFlow.getId(), "task1", 0, 3, childList3, null, "a");
        List childList4 = new ArrayList<>();
        childList4.add(5);
        Step s4 = new Step(4, workFlow.getId(), "task2", 0, 4, childList4, null, "a");
        List childList5 = new ArrayList<>();
        childList5.add(6);
        Step s5 = new Step(5, workFlow.getId(), "task22", 0, 5, childList5, null, "a");
        List childList6 = new ArrayList<>();
        childList6.add(7);
        Step s6 = new Step(6, workFlow.getId(), "parallelGateway-join", 3, 6, childList6, null, "a");
        List childList7 = new ArrayList<>();
        childList7.add(8);
        childList7.add(9);
        Step s7 = new Step(7, workFlow.getId(), "exclusiveGate", 4, 7, childList7, null, "a");
        List childList8 = new ArrayList<>();
        childList8.add(10);
        Step s8 = new Step(8, workFlow.getId(), "task3", 0, 8, childList8, "${flag=='true'}", "a");
        List childList9 = new ArrayList<>();
        childList9.add(10);
        Step s9 = new Step(9, workFlow.getId(), "task4", 0, 9, childList9, "${flag=='false'}", "a");
        List childList10 = new ArrayList<>();
        childList10.add(11);
        Step s10 = new Step(10, workFlow.getId(), "receiveTask", 6, 10, childList10, null, "a");
        Step s11 = new Step(11, workFlow.getId(), "end", 5, 11, new ArrayList<>(), null, "a");

        stepList.add(s1);
        stepList.add(s2);
        stepList.add(s3);
        stepList.add(s4);
        stepList.add(s5);
        stepList.add(s6);
        stepList.add(s7);
        stepList.add(s8);
        stepList.add(s9);
        stepList.add(s10);
        stepList.add(s11);


        //创建ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //得到RepositoryService
        RepositoryService repositoryService = processEngine.getRepositoryService();

        // 1. 建立模型
        BpmnModel model = new BpmnModel();
        Process process = new Process();
        model.addProcess(process);
        process.setId(workFlow.getName());
        process.setName(workFlow.getName());
        stepList.forEach(step -> {
            if (step.getType() == 1) {
                process.addFlowElement(createStartEvent());
            } else if (step.getType() == 5) {
                process.addFlowElement(createEndEvent());
            } else if (step.getType() == 2 || step.getType() == 3) {
                process.addFlowElement(createParallelGateway(step.getName(), step.getName()));

            } else if (step.getType() == 4) {
                process.addFlowElement(createExclusiveGateway(step.getName(), step.getName()));
            } else if (step.getType() == 6) {
                process.addFlowElement(createReceiveTask(step.getName(), step.getName()));
            } else {
                process.addFlowElement(createUserTask(step.getName(), step.getName(), step.getAssignee()));
            }
        });

        //连线
        stepList.forEach(step -> {
            List childList = step.getChlidOrderIds();
            childList.forEach(child -> {
                stepList.forEach(step1 -> {
                    if (step1.getOrderId() == child) {
                        if (step.getType() == 4) {
                            process.addFlowElement(createSequenceFlow(step.getName(), step1.getName(), step1.getConditionExpression()));
                        } else {
                            process.addFlowElement(createSequenceFlow(step.getName(), step1.getName(), null));
                        }
                    }
                });
            });
        });


        //定义并设置流程变量
        Map variables = new HashMap<>();
        variables.put("flag", 1 == 2);
        //deploy
        Deployment deployment = repositoryService.createDeployment().addBpmnModel("process/dynamic-model.bpmn", model).name("Dynamic process deployment").deploy();

        System.out.println("deploymentId:"+deployment.getId());
        //start
        ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey(workFlow.getName(), variables);
        System.out.println("processInstanceId:" + processInstance.getId());
        System.out.println("getProcessDefinitionId:"+processInstance.getProcessDefinitionId());

        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        //save as  png
        new BpmnAutoLayout(bpmnModel).execute();
        List highLightedActivities = processEngine.getRuntimeService().getActiveActivityIds(processInstance.getId());// 高亮节点
        List highLightedFlows = new ArrayList<>(); // 高亮连接线
        ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivities, highLightedFlows, "宋体", "宋体", "宋体", null, 1.0);
        FileUtils.copyInputStreamToFile(inputStream, new File("C:\\Users\\Administrator\\Desktop\\process.png"));
        //save sa  xml
        InputStream inputStreamXml = processEngine.getRepositoryService().getResourceAsStream(deployment.getId(), "process/dynamic-model.bpmn");
        FileUtils.copyInputStreamToFile(inputStreamXml, new File("C:\\Users\\Administrator\\Desktop\\process.bpmn.xml"));
        return processInstance.getId();
    }

    /**
     * 开始事件
     *
     * @return
     */
    StartEvent createStartEvent() {
        StartEvent startEvent = new StartEvent();
        startEvent.setId("start");
        return startEvent;
    }

    /**
     * 结束事件
     *
     * @return
     */
    EndEvent createEndEvent() {
        EndEvent endEvent = new EndEvent();
        endEvent.setId("end");
        return endEvent;
    }

    /**
     * 创建用户任务
     *
     * @param id
     * @param name
     * @param assignee
     * @return
     */
    UserTask createUserTask(String id, String name, String assignee) {
        UserTask userTask = new UserTask();
        userTask.setName(name);
        userTask.setId(id);
        userTask.setAssignee(assignee);
        return userTask;
    }

    /**
     * 创建接收任务
     *
     * @param id
     * @param name
     * @return
     */
    ReceiveTask createReceiveTask(String id, String name) {
        ReceiveTask receiveTask = new ReceiveTask();
        receiveTask.setId(id);
        receiveTask.setName(name);
        return receiveTask;
    }


    /**
     * 连线
     *
     * @param from
     * @param to
     * @return
     */
    SequenceFlow createSequenceFlow(String from, String to, String conditionExpression) {
        SequenceFlow sequenceFlow = new SequenceFlow();
        sequenceFlow.setSourceRef(from);
        sequenceFlow.setTargetRef(to);
        if (StringUtils.isNotBlank(conditionExpression)) {
            sequenceFlow.setConditionExpression(conditionExpression);
        }
        return sequenceFlow;
    }

    /**
     * 排他网关
     *
     * @param id
     * @param name
     * @return
     */
    ExclusiveGateway createExclusiveGateway(String id, String name) {
        ExclusiveGateway exclusiveGateway = new ExclusiveGateway();
        exclusiveGateway.setId(id);
        exclusiveGateway.setName(name);
        return exclusiveGateway;
    }

    /**
     * 并行网关
     *
     * @return
     */
    ParallelGateway createParallelGateway(String id, String name) {
        ParallelGateway parallelGateway = new ParallelGateway();
        parallelGateway.setId(id);
        parallelGateway.setName(name);
        return parallelGateway;

    }
}

 

7.效果图

activiti7---自定义流程图(springboot项目)_第1张图片

 

 

你可能感兴趣的:(工作流activiti7,activiti)