SpringBoot集成Activiti之在线设计器

流程设计是工作流的入口,开发者可以通过eclipse插件等来设计流程,但是用户并不会使用。所以可以在线设计的流程才是我们想要的,幸好activiti提供了在线设计功能,我们只需要把它集成到我们项目中就行了。

最终效果

image.png

集成Actviti

添加依赖

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.walle</groupId>
    <artifactId>activity-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>activity-service</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-boot-admin.version>2.1.1</spring-boot-admin.version>
        <spring-cloud.version>Greenwich.RC2</spring-cloud.version>
        <activiti.version>5.22.0</activiti.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!-- Activiti 启动器 -->
        <dependency>
            <groupId>org.activiti</groupId>
            <artifactId>activiti-spring-boot-starter-basic</artifactId>
            <version>${activiti.version}</version>
        </dependency>
        <!-- Activiti 流程图 -->
        <dependency>
            <groupId>org.activiti</groupId>
            <artifactId>activiti-diagram-rest</artifactId>
            <version>${activiti.version}</version>
        </dependency>
        <!-- Activiti 在线设计 -->
        <dependency>
            <groupId>org.activiti</groupId>
            <artifactId>activiti-modeler</artifactId>
            <version>${activiti.version}</version>
        </dependency>
        <dependency>
            <groupId>com.ctrip.framework.apollo</groupId>
            <artifactId>apollo-client</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.walle</groupId>
            <artifactId>common-service</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-dependencies</artifactId>
                <version>${spring-boot-admin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

下载Activiti源码包

下载地址:https://www.activiti.org/get-started

解压下载的源码包后我们看到目录结构如下

1547090999141.png

创建数据库

在activiti-5.22.0/database/create 文件夹中找到对应数据库的sql文件 然后创建相关数据库。数据库表说明

另外,为了方便管理模型,我们才创建业务表来管理模型SQL如下

CREATE TABLE `ts_business_define` (
  `business_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `business_code` varchar(100) DEFAULT NULL COMMENT '业务代码',
  `business_name` varchar(255) DEFAULT NULL COMMENT '业务名称',
  `proc_def_id` varchar(64) DEFAULT NULL COMMENT '流程定义ID',
  `model_id` varchar(64) DEFAULT NULL COMMENT '模型ID',
  `delete_status` int(11) DEFAULT '0' COMMENT '删除标记0=正常1=已删除',
  `create_by` bigint(20) DEFAULT '0' COMMENT '创建人',
  `create_byname` varchar(50) DEFAULT '0' COMMENT '创建人姓名',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `modify_by` bigint(20) DEFAULT NULL COMMENT '修改人',
  `modify_byname` varchar(50) DEFAULT NULL COMMENT '修改人姓名',
  `modify_time` datetime DEFAULT NULL COMMENT '修改时间',
  PRIMARY KEY (`business_id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4;

导入静态文件

将activiti-5.22.0/war/activiti-explorer.war解压

1547097974975.png

将文件夹内 diagram-viewer,editor-app,modeler.html拷贝到项目中resource/public目录下如图

1547098070832.png

这里需要修改editor-app/app-cfg.js 来设置项目跟路径 我们设置为空就可以

ACTIVITI.CONFIG = {
    // 'contextRoot' : '/activiti-explorer/service',
    'contextRoot' : '',
};

导入模型相关操作Controller

解压activiti-5.22.0\libs\activiti-modeler-5.22.0-sources.jar,将StencilsetRestResource.java,

ModelEditorJsonRestResource.java,ModelSaveRestResource.java三个文件拷贝到controller目录

下载汉化文件

汉化文件,下载文件并放在resource目录下

禁用登录验证

Activiti中自动集成了security的权限验证,当我们访问接口的时候会弹出登录界面,所以我们需要禁用掉登录验证

在启动类中添加注解

@SpringBootApplication
@EnableAutoConfiguration(exclude = {
        org.activiti.spring.boot.SecurityAutoConfiguration.class,               org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class
})
public class ActivityServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ActivityServiceApplication.class, args);
    }

}

创建模型

到此为止,我们的集成工作就基本完成了,我们可以通过浏览器访问http://localhost:8080/model/create

就可以新建一个模型了如图

1547100441136.png

模型管理

通过以上集成我们可以创建一个新的模型,然后我们会获取到一个模型ID 然后根据ID我们可以部署流程之类,现在我们通过一些简单的改造,来实现页面上对模型的操作和部署,并且和我们的业务关联起来。

业务关联模型

我们可以看到,模型管理界面的地址是http://localhost:8080/modeler.html?modelId=120005,这里需要一个模型ID的参数,我们可以把模型ID和业务定义关联起来,代码如下

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private BusinessDefineService businessDefineService;

    @PostMapping("getModelId")
    public ResultResponse getModel(Long businessId, HttpServletRequest request, HttpServletResponse response) {
        try {
            BusinessDefine businessDefine = businessDefineService.getById(businessId);
            String modelId = businessDefine.getModelId();
            if (StringUtils.isBlank(modelId)) {
                modelId = createModel(businessId);
            }
            return ResultResponse.ofSuccess(modelId);
        } catch (Exception e) {
            log.error("",e);
            return ResultResponse.ofError(e.getMessage());
        }
    }

    public String createModel(Long businessId) {
        try {
            String modelName = "modelName";
            String modelKey = "modelKey";
            String description = "description";

            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

            RepositoryService repositoryService = processEngine.getRepositoryService();

            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, modelName);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(modelName);
            modelData.setKey(modelKey);

            //保存模型
            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));

            BusinessDefine businessDefine = businessDefineService.getById(businessId);
            businessDefine.setModelId(modelData.getId());
            businessDefineService.update(businessDefine);
            return modelData.getId();
        } catch (Exception e) {
            return null;
        }
    }

这里我们进行了一下判断,业务是否关联了模型,如果关联返回模型ID 如果没关联,创建一个新的模型并返回Id并关联业务

部署模型

通过业务定义获取模型,然后部署模型

/**
     * 根据Model部署流程
     */
    @PostMapping(value = "deploy")
    public ResultResponse deploy(Long businessId) {
        try {

            BusinessDefine businessDefine = businessDefineService.getById(businessId);
            if (StringUtils.isBlank(businessDefine.getModelId())) {
                throw new SystemException("请先设计模型");
            }
            Model modelData = repositoryService.getModel(businessDefine.getModelId());
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes, "UTF-8")).deploy();
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
            businessDefine.setProcDefId(processDefinition.getId());
            businessDefineService.update(businessDefine);
            return ResultResponse.ofSuccess();
        } catch (Exception e) {
            log.error("部署模型", e.getMessage(), e);
            return ResultResponse.ofError(e.getMessage());
        }
    }

导出流程

 /**
     * 导出model的xml文件
     */
    @GetMapping(value = "export")
    public void export(Long businessId, HttpServletResponse response) {
        try {
            BusinessDefine businessDefine = businessDefineService.getById(businessId);
            if (StringUtils.isBlank(businessDefine.getModelId())) {
                throw new SystemException("请先设计模型");
            }
            String modelId = businessDefine.getModelId();
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
            BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
            byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);

            ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
            OutputStream outputStream = response.getOutputStream();
            IOUtils.copy(in, outputStream);
            String filename = bpmnModel.getMainProcess().getId() + ".bpmn.xml";
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"utf-8") );
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            log.error("导出model的xml文件失败:{}",e.getMessage(), e);
        }
    }

导入流程

通过xml导入流程会生成流程定义,但是不会创建模型,所以我们要通过流程定义创建模型

导入流程定义


    @PostMapping("import")
    public ResultResponse importXml(@RequestParam("file") MultipartFile file,Long businessId) {

        try {
            BusinessDefine businessDefine = businessDefineService.getById(businessId);
            InputStream fileInputStream = file.getInputStream();
            Deployment deployment = repositoryService.createDeployment()
                                    .addInputStream(businessDefine.getBusinessName() +".bpmn", fileInputStream)
                                    .deploy();
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
            String modelId = changeProcessToModel(processDefinition);
            businessDefine.setProcDefId(processDefinition.getId());
            businessDefine.setModelId(modelId);
            businessDefineService.update(businessDefine);
            return ResultResponse.ofSuccess();
        } catch (Exception e) {
            log.error("导入流程定义失败:{}",e.getMessage(),e);
            return ResultResponse.ofError(e.getMessage());
        }
    }

通过流程生成模型


    /**
     * 流程转化为可编辑模型
     *
     * @param processDefinition
     */

    public String changeProcessToModel(ProcessDefinition processDefinition) {

        Model modelData = repositoryService.newModel();
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // 初始化Model
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode modelObjectNode = objectMapper.createObjectNode();
        modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, processDefinition.getName());
        modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
        modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, processDefinition.getDescription());
        modelData.setMetaInfo(modelObjectNode.toString());
        modelData.setName(processDefinition.getName());
        modelData.setKey(processDefinition.getKey());

        // 保存模型
        repositoryService.saveModel(modelData);
        String deploymentId = processDefinition.getDeploymentId();
        String processDefineResourceName = null;
        // 通过deploymentId取得某个部署的资源的名称
        List<String> resourceNames = processEngine.getRepositoryService().getDeploymentResourceNames(deploymentId);
        if (resourceNames != null && resourceNames.size() > 0) {
            for (String temp : resourceNames) {
                if (temp.indexOf(".bpmn") > 0) {
                    processDefineResourceName = temp;
                }
            }
        }
        InputStream bpmnStream = processEngine.getRepositoryService().getResourceAsStream(deploymentId, processDefineResourceName);
        createModelByInputStream(bpmnStream, modelData.getId());
        return modelData.getId();
    }

    public void createModelByInputStream(InputStream bpmnStream, String ModelID) {
        XMLInputFactory xif;
        InputStreamReader in = null;
        XMLStreamReader xtr = null;
        try {
            xif = XMLInputFactory.newFactory();
            in = new InputStreamReader(bpmnStream, "UTF-8");
            xtr = xif.createXMLStreamReader(in);
            BpmnModel bpmnModel = (new BpmnXMLConverter()).convertToBpmnModel(xtr);
            ObjectNode modelNode = new BpmnJsonConverter().convertToJson(bpmnModel);
            repositoryService.addModelEditorSource(ModelID, modelNode.toString().getBytes("UTF-8"));
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            if (xtr != null) {
                try {
                    xtr.close();
                } catch (XMLStreamException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bpmnStream != null) {
                try {
                    bpmnStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

完!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容