流程设计是工作流的入口,开发者可以通过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();
}
}
}
}
完!
网友评论