Activiti动态流程&Activiti Modeler、diagram-viewer

activiti工作流demo,数据库使用mysql,spring + mybatis + activiti。适合入门学习使用,把系统跑起来,流程走一遍,看数据库内表数据的变化。

一、spring整合activiti

  1. pom.xml
<properties>
    <activiti.version>5.22.0</activiti.version>
    <spring.version>4.3.23.RELEASE</spring.version>
    <jackson.version>2.7.5</jackson.version>
</properties>
<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-modeler</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-engine</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-explorer</artifactId>
        <version>${activiti.version}</version>
        <exclusions>
            <exclusion>
                <groupId>org.vaadin.addons</groupId>
                <artifactId>dcharts-widget</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-rest</artifactId>
        <version>${activiti.version}</version>
    </dependency>
    <!--集成diagram-view跟踪流程-->
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-diagram-rest</artifactId>
        <version>${activiti.version}</version>
    </dependency>
</dependencies>
  1. config.properties
#jdbc
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://127.0.0.1:3306/activiti?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf8
jdbc_username=root
jdbc_password=111111
validationQuery=SELECT 1
  1. ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-3.0.xsd
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	">

    <!-- 启用注解 -->
    <context:annotation-config />

    <!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 -->
    <context:component-scan base-package="com.aaron.**.service">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <!--可以配置多个资源文件 -->
            <list>
                <value>classpath:config.properties</value>
            </list>
        </property>
        <property name="fileEncoding">
            <value>utf-8</value>
        </property>
    </bean>

    <!-- 配置数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc_driverClassName}" />
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />
        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- 监控数据库 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
        <property name="dataSource" ref="dataSource" />
        <!-- 设置建表策略,如果没有表,自动创建表 -->
        <property name="databaseSchemaUpdate" value="true" />
        <property name="jobExecutorActivate" value="false"/>
        <property name="history" value="full"/>
         <!-- 配置事务管理器,统一事务 -->
        <property name="transactionManager" ref="transactionManager" />
        <property name="activityFontName" value="微软雅黑" />
        <property name="annotationFontName" value="微软雅黑" />
        <property name="labelFontName" value="微软雅黑" />
    </bean>
    <!-- 创建流程引擎对象 -->
    <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
        <property name="processEngineConfiguration" ref="processEngineConfiguration" />
    </bean>


    <!-- 由流程引擎对象,提供的方法,创建项目中使用的Activiti工作流的Service -->
    <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService" />
    <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService" />
    <bean id="taskService" factory-bean="processEngine" factory-method="getTaskService" />
    <bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService" />
    <bean id="formService" factory-bean="processEngine" factory-method="getFormService" />
    <bean id="identityService" factory-bean="processEngine" factory-method="getIdentityService" />

    <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />


    <!--start mybatis配置-->
    <!-- myBatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 配置数据库表对应的java实体类 -->
        <property name="typeAliasesPackage" value="com.aaron.**.model" />
        <!-- mapper扫描 -->
        <property name="mapperLocations" value="classpath:com/aaron/**/*.xml" />
    </bean>
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
        <constructor-arg ref="sqlSessionFactory" />
    </bean>
    <!--end mybatis配置-->
</beans>

  1. ApplicationContext-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation=
		"http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd	
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
		>
	
	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<constructor-arg value="UTF-8" />
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<mvc:default-servlet-handler/>
	<!-- 扫描 -->
	<context:component-scan base-package="com.aaron.**.controller">
	   <!--<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Service" />
		&lt;!&ndash;排除@Configuration注解,否则会被扫描到两次&ndash;&gt;
		<context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration" />-->
	</context:component-scan>

</beans>

  1. mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"  
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

	<settings>
		<setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 -->
		<setting name="useGeneratedKeys" value="true" />
		<setting name="defaultExecutorType" value="REUSE" />
		<setting name="logImpl" value="LOG4J"></setting>
		<!-- map 保存 null 值 -->
		<setting name="callSettersOnNulls" value="true"></setting>
		<setting name="logImpl" value="Log4j"></setting>
		<!--使用驼峰命名法转换字段-->
		<!--<setting name="mapUnderscoreToCamelCase" value="true" />-->
	</settings>

</configuration>

二、动态创建流程

直接上代码

@Autowired
private RepositoryService repositoryService;
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;

/*任务节点*/
protected UserTask createUserTask(String id, String name, String candidateGroup) {
    List<String> candidateGroups=new ArrayList<String>();
    candidateGroups.add(candidateGroup);
    UserTask userTask = new UserTask();
    userTask.setName(name);
    userTask.setId(id);
    userTask.setCandidateGroups(candidateGroups);
    return userTask;
}

/*连线*/
protected SequenceFlow createSequenceFlow(String from, String to, String name, String conditionExpression) {
    SequenceFlow flow = new SequenceFlow();
    flow.setSourceRef(from);
    flow.setTargetRef(to);
    flow.setName(name);
    if(StringUtils.isNotEmpty(conditionExpression)){
        flow.setConditionExpression(conditionExpression);
    }
    return flow;
}

/*排他网关*/
protected ExclusiveGateway createExclusiveGateway(String id) {
    ExclusiveGateway exclusiveGateway = new ExclusiveGateway();
    exclusiveGateway.setId(id);
    return exclusiveGateway;
}

/*开始节点*/
protected StartEvent createStartEvent() {
    StartEvent startEvent = new StartEvent();
    startEvent.setId("startEvent");
    return startEvent;
}

/*结束节点*/
protected EndEvent createEndEvent() {
    EndEvent endEvent = new EndEvent();
    endEvent.setId("endEvent");
    return endEvent;
}

public void createProcess() throws IOException {
    System.out.println(".........start...");

    // 1. Build up the model from scratch
    BpmnModel model = new BpmnModel();
    Process process=new Process();
    model.addProcess(process);
    final String PROCESSID ="process01";
    final String PROCESSNAME ="测试01";
    process.setId(PROCESSID);
    process.setName(PROCESSNAME);

    process.addFlowElement(createStartEvent());
    process.addFlowElement(createUserTask("task1", "节点01", "candidateGroup1"));
    process.addFlowElement(createExclusiveGateway("createExclusiveGateway1"));
    process.addFlowElement(createUserTask("task2", "节点02", "candidateGroup2"));
    process.addFlowElement(createExclusiveGateway("createExclusiveGateway2"));
    process.addFlowElement(createUserTask("task3", "节点03", "candidateGroup3"));
    process.addFlowElement(createExclusiveGateway("createExclusiveGateway3"));
    process.addFlowElement(createUserTask("task4", "节点04", "candidateGroup4"));
    process.addFlowElement(createEndEvent());

    process.addFlowElement(createSequenceFlow("startEvent", "task1", "", ""));
    process.addFlowElement(createSequenceFlow("task1", "task2", "", ""));
    process.addFlowElement(createSequenceFlow("task2", "createExclusiveGateway1", "", ""));
    process.addFlowElement(createSequenceFlow("createExclusiveGateway1", "task1", "不通过", "${pass=='2'}"));
    process.addFlowElement(createSequenceFlow("createExclusiveGateway1", "task3", "通过", "${pass=='1'}"));
    process.addFlowElement(createSequenceFlow("task3", "createExclusiveGateway2", "", ""));
    process.addFlowElement(createSequenceFlow("createExclusiveGateway2", "task2", "不通过", "${pass=='2'}"));
    process.addFlowElement(createSequenceFlow("createExclusiveGateway2", "task4", "通过", "${pass=='1'}"));
    process.addFlowElement(createSequenceFlow("task4", "createExclusiveGateway3", "", ""));
    process.addFlowElement(createSequenceFlow("createExclusiveGateway3", "task3", "不通过", "${pass=='2'}"));
    process.addFlowElement(createSequenceFlow("createExclusiveGateway3", "endEvent", "通过", "${pass=='1'}"));

    // 2. Generate graphical information
    new BpmnAutoLayout(model).execute();

    // 3. Deploy the process to the engine
    Deployment deployment = repositoryService.createDeployment().addBpmnModel(PROCESSID+".bpmn", model).name(PROCESSID+" Dynamic process deployment").deploy();

    // 4. Start a process instance
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(PROCESSID);

    // 5. Check if task is available
    List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list();
    System.out.println(tasks.size());

    // 6. Save process diagram to a file
    InputStream processDiagram = repositoryService.getProcessDiagram(processInstance.getProcessDefinitionId());
    FileUtils.copyInputStreamToFile(processDiagram, new File("target/"+PROCESSID+".png"));

    // 7. Save resulting BPMN xml to a file
    InputStream processBpmn = repositoryService.getResourceAsStream(deployment.getId(), PROCESSID+".bpmn");
    FileUtils.copyInputStreamToFile(processBpmn,new File("target/"+PROCESSID+".bpmn"));

    System.out.println(".........end...");
}

三、集成Activiti Modeler

  1. 下载源文件
    activiti5.22.0源码
  2. copy资源文件
    解压Activiti-master.zip,进入如下目录
Activiti-master\modules\activiti-webapp-explorer2\src\main\webapp

复制editor-app,diagram-viewer文件夹,以及modele.html到本地项目的resources下。
3. 复制服务端文件

Activiti-master\modules\activiti-modeler\src\main\java\org\activiti\rest\editor

复制ModelEditorJsonRestResource.java,ModelSaveRestResource.java,StencilsetRestResource.java到控制层文件夹下
4. 修改editor-app/app-cfg.js文件中请求的地址

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

该请求的控制类为ModelEditorJsonRestResource.java

@RequestMapping(value="/model/{modelId}/json", method = RequestMethod.GET, produces = "application/json")
  1. 拷贝stencilset.json到本地项目的resources下。
Activiti-master\modules\activiti-webapp-explorer2\src\main\resources\stencilset.json
  1. 跳转方法
@Autowired
private RepositoryService repositoryService;
/**
 * 新建一个空模型
 */
@RequestMapping(value = "/newModel")
public void newModel(HttpServletRequest request, HttpServletResponse response) {
    //初始化一个空模型
    Model model = repositoryService.newModel();
    ObjectMapper objectMapper = new ObjectMapper();
    //设置一些默认信息
    String name = "new-process";
    String description = "";
    int revision = 1;
    String key = "process";

    try {
        ObjectNode modelNode = objectMapper.createObjectNode();
        modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
        modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);

        model.setName(name);
        model.setKey(key);
        model.setMetaInfo(modelNode.toString());

        repositoryService.saveModel(model);
        String id = model.getId();

        //完善ModelEditorSource
        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);
        repositoryService.addModelEditorSource(id,editorNode.toString().getBytes("utf-8"));
        //跳转到流程编辑页面
        response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + id);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

创建一个新的空模型后带上模型id重定向到modeler.html,编辑完成后保存即可。

四、整合diagram-viewer跟踪流程

在第三节的基础上做处理。

  1. 提取activiti-diagram-rest 包中(目录如下)的四个文件放到controller目录
Activiti-master\modules\activiti-diagram-rest\src\main\java\org\activiti\rest\diagram\services
  1. 配置监听器,用户处理callback回调函数
  • 拷贝如下该目录的FilterServletOutputStream.java、GenericResponseWrapper.java、JsonpCallbackFilter.java到目录本地项目下:
Activiti-master\modules\activiti-webapp-explorer2\src\main\java\org\activiti\explorer\servlet

修改web.xml文件

<filter>
    <filter-name>JSONPFilter</filter-name>
    <filter-class>com.aaron.activiti.servlet.JsonpCallbackFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>JSONPFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
  1. 修改 diagram-viewer/index.html,把service去掉。
  var baseUrl = window.document.location.protocol + "//" + window.document.location.host + "/";
  var shortenedUrl = window.document.location.href.replace(baseUrl, "");
  baseUrl = baseUrl + shortenedUrl.substring(0, shortenedUrl.indexOf("/"));
  
  ActivitiRest.options = {
    processInstanceHighLightsUrl: baseUrl + "/process-instance/{processInstanceId}/highlights?callback=?",
    processDefinitionUrl: baseUrl + "/process-definition/{processDefinitionId}/diagram-layout?callback=?",
    processDefinitionByKeyUrl: baseUrl + "/process-definition/{processDefinitionKey}/diagram-layout?callback=?"
  };
  1. 修改 Diagram-viewer\js\ActivitiRest.js
  • 在这里要将ajax中原有的数据类型修改为json,有三个地方需要改。
$.ajax({
	url: url,
	dataType: 'json',
	cache: false,
	……
})
  1. 启动项目,显示我的流程
http://localhost:8080/activitidemo/diagram-viewer/index.html?processDefinitionId=process:3:2527&processInstanceId=2528

五、demo源码

六、遇到的问题

  1. 启动流程后任务名称中文乱码,跟踪流程时流程节点名称乱码
    解决办法:
  • 发布流程时指定编码方式
Deployment deployment = repositoryService.createDeployment()
                        .name(modelData.getName())
                        .addString(processName, new String(bpmnBytes,"UTF-8")).deploy();
  • 或者启动加入启动tomcat参数:-Dfile.encoding=“UTF-8”
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值