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

目录

    • 一、spring整合activiti
    • 二、动态创建流程
    • 三、集成Activiti Modeler
    • 四、整合diagram-viewer跟踪流程
    • 五、[demo源码](https://github.com/haochenchn/activitidemo)
    • 六、遇到的问题

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

一、spring整合activiti

  1. pom.xml

    5.22.0
    4.3.23.RELEASE
    2.7.5


    
        com.fasterxml.jackson.core
        jackson-databind
        ${jackson.version}
    
    
        org.activiti
        activiti-modeler
        ${activiti.version}
    
    
        org.activiti
        activiti-engine
        ${activiti.version}
    
    
        org.activiti
        activiti-explorer
        ${activiti.version}
        
            
                org.vaadin.addons
                dcharts-widget
            
        
    
    
        org.activiti
        activiti-rest
        ${activiti.version}
    
    
    
        org.activiti
        activiti-diagram-rest
        ${activiti.version}
    

  1. config.properties
#jdbc
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://127.0.0.1:3306/activiti?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8
jdbc_username=root
jdbc_password=111111
validationQuery=SELECT 1
  1. ApplicationContext.xml



    
    

    
    
        
    

    
        
            
            
                classpath:config.properties
            
        
        
            utf-8
        
    

    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

    
        
    

    
        
        
        
        
        
         
        
        
        
        
    
    
    
        
    


    
    
    
    
    
    
    

    


    
    
    
        
        
        
        
        
        
    
    
        
    
    


  1. ApplicationContext-mvc.xml


	
	
		
			
				
			
		
	
	
	
	
	   
	



  1. mybatis-config.xml




	
		
		
		
		
		
		
		
		
		
	



二、动态创建流程

直接上代码

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

/*任务节点*/
protected UserTask createUserTask(String id, String name, String candidateGroup) {
    List candidateGroups=new ArrayList();
    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 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文件


    JSONPFilter
    com.aaron.activiti.servlet.JsonpCallbackFilter


    JSONPFilter
    /*

  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”

你可能感兴趣的:(activiti)