activiti是不错的工作流,最近发现5.12中可以通过在运行期间动态生成一个BPMN的流程模型,因为一般来说,是通过如activiti designer这样的工具,去画好一个BPMN图的,现在可以通过代码的方法去生成了.acitivti 核心工作组的老外提供了一个完整的DEMO来演示,
详细代码在:https://github.com/frederikheremans/activiti-dynamic-process中,
下面小结下,代码其实很简单,如下:
@Test
public void testDynamicDeploy() throws Exception {
//创建bpmn模型
BpmnModel model = new BpmnModel();
Process process = new Process();
model.addProcess(process);
process.setId("my-process");
//创建bpmn元素
process.addFlowElement(createStartEvent());
process.addFlowElement(createUserTask("task1", "First task", "fred"));
process.addFlowElement(createUserTask("task2", "Second task", "john"));
process.addFlowElement(createEndEvent());
process.addFlowElement(createSequenceFlow("start", "task1"));
process.addFlowElement(createSequenceFlow("task1", "task2"));
process.addFlowElement(createSequenceFlow("task2", "end"));
// 2.生成BPMN自动布局
new BpmnAutoLayout(model).execute();
// 3. 部署这个BPMN模型
Deployment deployment = activitiRule.getRepositoryService().createDeployment()
.addBpmnModel("dynamic-model.bpmn", model).name("Dynamic process deployment")
.deploy();
// 4. 启动流程实例
ProcessInstance processInstance = activitiRule.getRuntimeService()
.startProcessInstanceByKey("my-process");
// 5 发起任务
List tasks = activitiRule.getTaskService().createTaskQuery()
.processInstanceId(processInstance.getId()).list();
Assert.assertEquals(1, tasks.size());
Assert.assertEquals("First task", tasks.get(0).getName());
Assert.assertEquals("fred", tasks.get(0).getAssignee());
// 6. 保存bpmn流程图
InputStream processDiagram = activitiRule.getRepositoryService()
.getProcessDiagram(processInstance.getProcessDefinitionId());
FileUtils.copyInputStreamToFile(processDiagram, new File("target/diagram.png"));
// 7. 保存为bpmn.xml的xml类型文件
InputStream processBpmn = activitiRule.getRepositoryService()
.getResourceAsStream(deployment.getId(), "dynamic-model.bpmn");
FileUtils.copyInputStreamToFile(processBpmn,
new File("target/process.bpmn20.xml"));
}
//创建task
protected UserTask createUserTask(String id, String name, String assignee) {
UserTask userTask = new UserTask();
userTask.setName(name);
userTask.setId(id);
userTask.setAssignee(assignee);
return userTask;
}
//创建箭头
protected SequenceFlow createSequenceFlow(String from, String to) {
SequenceFlow flow = new SequenceFlow();
flow.setSourceRef(from);
flow.setTargetRef(to);
return flow;
}
protected StartEvent createStartEvent() {
StartEvent startEvent = new StartEvent();
startEvent.setId("start");
return startEvent;
}
protected EndEvent createEndEvent() {
EndEvent endEvent = new EndEvent();
endEvent.setId("end");
return endEvent;
}
其实上面的注解已经比较清楚了.首先是 BpmnModel model = new BpmnModel();
创建一个BPMN模型;然后Process process = new Process();这里创建一个process,
并把这个process加到bpmn模型中去,当然要设置其id了;
然后用 process.addFlowElement去不断创建BPMN中的每一个元素;
可以看到包括start,end,task,sequence等元素都可以通过new的方法分别创建;
并且用new BpmnAutoLayout(model).execute();对BPMN元素进行自动布局;
3,4,5部分则比较好理解了;6和7则都是生成BPMN的实际jpg图和生成实际的XML文件
最后会生成的BPMN图为: