Java源码示例:org.activiti.bpmn.converter.BpmnXMLConverter
示例1
@PostMapping("/{modelId}/deploy")
@ApiOperation("发布模型")
@Authorize(action = "deploy")
public ResponseMessage<Deployment> deployModel(@PathVariable String modelId) throws Exception {
Model modelData = repositoryService.getModel(modelId);
if (modelData == null) {
throw new NotFoundException("模型不存在!");
}
ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
String processName = modelData.getName() + ".bpmn20.xml";
Deployment deployment = repositoryService.createDeployment()
.name(modelData.getName())
.addString(processName, new String(bpmnBytes, "utf8"))
.deploy();
return ResponseMessage.ok(deployment).include(Deployment.class, "id", "name", "new");
}
示例2
/**
* 导出model的xml文件
* @throws IOException
* @throws JsonProcessingException
*/
public void export(String id, HttpServletResponse response) {
try {
org.activiti.engine.repository.Model modelData = repositoryService.getModel(id);
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);
IOUtils.copy(in, response.getOutputStream());
String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
response.flushBuffer();
} catch (Exception e) {
throw new ActivitiException("导出model的xml文件失败,模型ID="+id, e);
}
}
示例3
/**
* 根据Model部署流程
*/
@RequestMapping(value = "deploy/{modelId}")
public String deploy(@PathVariable("modelId") String modelId, RedirectAttributes redirectAttributes) {
try {
Model modelData = repositoryService.getModel(modelId);
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)).deploy();
redirectAttributes.addFlashAttribute("message", "部署成功,部署ID=" + deployment.getId());
} catch (Exception e) {
logger.error("根据模型部署流程失败:modelId={}", modelId, e);
}
return "redirect:/chapter20/model/list";
}
示例4
/**
* 导出model的xml文件
*/
@RequestMapping(value = "export/{modelId}")
public void export(@PathVariable("modelId") String modelId, HttpServletResponse response) {
try {
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);
IOUtils.copy(in, response.getOutputStream());
String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
response.flushBuffer();
} catch (Exception e) {
logger.error("导出model的xml文件失败:modelId={}", modelId, e);
}
}
示例5
/**
* 把BpmnModel转换为XML对象
* @throws Exception
*/
@Test
@Deployment(resources = "chapter6/dynamic-form/leave.bpmn")
public void testBpmnModelToXml() throws Exception {
// 验证是否部署成功
long count = repositoryService.createProcessDefinitionQuery().count();
assertEquals(1, count);
// 查询流程定义对象
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("leave").singleResult();
// 获取BpmnModel对象
BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
// 创建转换对象
BpmnXMLConverter converter = new BpmnXMLConverter();
// 把BpmnModel对象转换成字符(也可以输出到文件中)
byte[] bytes = converter.convertToXML(bpmnModel);
String xmlContent = new String(bytes);
System.out.println(xmlContent);
}
示例6
public BpmnModel getBpmnModelById(String processDefinitionId) {
if (processDefinitionId == null) {
throw new ActivitiIllegalArgumentException("Invalid process definition id : null");
}
// first try the cache
BpmnModel bpmnModel = bpmnModelCache.get(processDefinitionId);
if (bpmnModel == null) {
ProcessDefinition processDefinition = findDeployedProcessDefinitionById(processDefinitionId);
if (processDefinition == null) {
throw new ActivitiObjectNotFoundException("no deployed process definition found with id '" + processDefinitionId + "'", ProcessDefinition.class);
}
// Fetch the resource
String resourceName = processDefinition.getResourceName();
ResourceEntity resource = Context.getCommandContext().getResourceEntityManager()
.findResourceByDeploymentIdAndResourceName(processDefinition.getDeploymentId(), resourceName);
if (resource == null) {
if (Context.getCommandContext().getDeploymentEntityManager().findDeploymentById(processDefinition.getDeploymentId()) == null) {
throw new ActivitiObjectNotFoundException("deployment for process definition does not exist: "
+ processDefinition.getDeploymentId(), Deployment.class);
} else {
throw new ActivitiObjectNotFoundException("no resource found with name '" + resourceName
+ "' in deployment '" + processDefinition.getDeploymentId() + "'", InputStream.class);
}
}
// Convert the bpmn 2.0 xml to a bpmn model
BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
bpmnModel = bpmnXMLConverter.convertToBpmnModel(new BytesStreamSource(resource.getBytes()), false, false);
bpmnModelCache.add(processDefinition.getId(), bpmnModel);
}
return bpmnModel;
}
示例7
public DeploymentBuilder addBpmnModel(String resourceName, BpmnModel bpmnModel) {
BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
try {
String bpmn20Xml = new String(bpmnXMLConverter.convertToXML(bpmnModel), "UTF-8");
addString(resourceName, bpmn20Xml);
} catch (UnsupportedEncodingException e) {
throw new ActivitiException("Errot while transforming BPMN model to xml: not UTF-8 encoded", e);
}
return this;
}
示例8
protected BpmnModel getBpmnModel(String file) throws Exception {
BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(file);
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(xmlStream);
XMLStreamReader xtr = xif.createXMLStreamReader(in);
BpmnModel bpmnModel = xmlConverter.convertToBpmnModel(xtr);
return bpmnModel;
}
示例9
public DeploymentBuilder addBpmnModel(String resourceName, BpmnModel bpmnModel) {
BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
try {
String bpmn20Xml = new String(bpmnXMLConverter.convertToXML(bpmnModel), "UTF-8");
addString(resourceName, bpmn20Xml);
} catch (UnsupportedEncodingException e) {
throw new ActivitiException("Error while transforming BPMN model to xml: not UTF-8 encoded", e);
}
return this;
}
示例10
@Test
@Deployment
public void testLaneExtensionElement() {
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("swimlane-extension").singleResult();
BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
System.out.println(new String(xml));
Process bpmnProcess = bpmnModel.getMainProcess();
for (Lane l : bpmnProcess.getLanes()) {
Map<String, List<ExtensionElement>> extensions = l.getExtensionElements();
Assert.assertTrue(extensions.size() > 0);
}
}
示例11
public void testStartEventWithExecutionListener() throws Exception {
BpmnModel bpmnModel = new BpmnModel();
Process process = new Process();
process.setId("simpleProcess");
process.setName("Very simple process");
bpmnModel.getProcesses().add(process);
StartEvent startEvent = new StartEvent();
startEvent.setId("startEvent1");
TimerEventDefinition timerDef = new TimerEventDefinition();
timerDef.setTimeDuration("PT5M");
startEvent.getEventDefinitions().add(timerDef);
ActivitiListener listener = new ActivitiListener();
listener.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION);
listener.setImplementation("${test}");
listener.setEvent("end");
startEvent.getExecutionListeners().add(listener);
process.addFlowElement(startEvent);
UserTask task = new UserTask();
task.setId("reviewTask");
task.setAssignee("kermit");
process.addFlowElement(task);
SequenceFlow flow1 = new SequenceFlow();
flow1.setId("flow1");
flow1.setSourceRef("startEvent1");
flow1.setTargetRef("reviewTask");
process.addFlowElement(flow1);
EndEvent endEvent = new EndEvent();
endEvent.setId("endEvent1");
process.addFlowElement(endEvent);
byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
new BpmnXMLConverter().validateModel(new InputStreamSource(new ByteArrayInputStream(xml)));
Deployment deployment = repositoryService.createDeployment().name("test").addString("test.bpmn20.xml", new String(xml)).deploy();
repositoryService.deleteDeployment(deployment.getId());
}
示例12
@Test
public void testWarningError() throws UnsupportedEncodingException, XMLStreamException {
String flowWithoutConditionNoDefaultFlow = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<definitions id='definitions' xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:activiti='http://activiti.org/bpmn' targetNamespace='Examples'>"
+ " <process id='exclusiveGwDefaultSequenceFlow'> " + " <startEvent id='theStart' /> " + " <sequenceFlow id='flow1' sourceRef='theStart' targetRef='exclusiveGw' /> " +
" <exclusiveGateway id='exclusiveGw' name='Exclusive Gateway' /> "
+ // no default = "flow3" !!
" <sequenceFlow id='flow2' sourceRef='exclusiveGw' targetRef='theTask1'> " + " <conditionExpression xsi:type='tFormalExpression'>${input == 1}</conditionExpression> "
+ " </sequenceFlow> " + " <sequenceFlow id='flow3' sourceRef='exclusiveGw' targetRef='theTask2'/> " + // one
// would
// be
// OK
" <sequenceFlow id='flow4' sourceRef='exclusiveGw' targetRef='theTask2'/> " + // but
// two
// unconditional
// not!
" <userTask id='theTask1' name='Input is one' /> " + " <userTask id='theTask2' name='Default input' /> " + " </process>" + "</definitions>";
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(flowWithoutConditionNoDefaultFlow.getBytes()), "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(in);
BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
Assert.assertNotNull(bpmnModel);
List<ValidationError> allErrors = processValidator.validate(bpmnModel);
Assert.assertEquals(1, allErrors.size());
Assert.assertTrue(allErrors.get(0).isWarning());
}
示例13
protected void deployProcess(BpmnModel bpmnModel) {
byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
try {
Deployment deployment = processEngine.getRepositoryService().createDeployment().name("test").addString("test.bpmn20.xml", new String(xml)).deploy();
processEngine.getRepositoryService().deleteDeployment(deployment.getId());
} finally {
processEngine.close();
}
}
示例14
@Test
public void testConvertingAfterAutoLayout() {
final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ProcessWithCompensationAssociation.bpmn20.xml");
BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
BpmnModel bpmnModel1 = bpmnXMLConverter.convertToBpmnModel(new InputStreamProvider() {
@Override
public InputStream getInputStream() {
return inputStream;
}
}, false, false);
if (bpmnModel1.getLocationMap().size() == 0) {
BpmnAutoLayout bpmnLayout = new BpmnAutoLayout(bpmnModel1);
bpmnLayout.execute();
}
byte[] xmlByte = bpmnXMLConverter.convertToXML(bpmnModel1);
final InputStream byteArrayInputStream = new ByteArrayInputStream(xmlByte);
BpmnModel bpmnModel2 = bpmnXMLConverter.convertToBpmnModel(new InputStreamProvider() {
@Override
public InputStream getInputStream() {
return byteArrayInputStream;
}
}, false, false);
assertEquals(10, bpmnModel1.getLocationMap().size());
assertEquals(10, bpmnModel2.getLocationMap().size());
assertEquals(7, bpmnModel1.getFlowLocationMap().size());
assertEquals(7, bpmnModel2.getFlowLocationMap().size());
}
示例15
protected BpmnModel readXMLFile() throws Exception {
InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(getResource());
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(xmlStream, "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(in);
return new BpmnXMLConverter().convertToBpmnModel(xtr);
}
示例16
protected BpmnModel exportAndReadXMLFile(BpmnModel bpmnModel) throws Exception {
byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
System.out.println("xml " + new String(xml, "UTF-8"));
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(xml), "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(in);
return new BpmnXMLConverter().convertToBpmnModel(xtr);
}
示例17
@Test
@Deployment
public void testLaneExtensionElement() {
ProcessDefinition processDefinition = activitiRule.getRepositoryService().createProcessDefinitionQuery()
.processDefinitionKey("swimlane-extension").singleResult();
BpmnModel bpmnModel = activitiRule.getRepositoryService().getBpmnModel(processDefinition.getId());
byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
System.out.println(new String(xml));
Process bpmnProcess = bpmnModel.getMainProcess();
for (Lane l : bpmnProcess.getLanes()) {
Map<String, List<ExtensionElement>> extensions = l.getExtensionElements();
Assert.assertTrue(extensions.size() > 0);
}
}
示例18
public void testStartEventWithExecutionListener() throws Exception {
BpmnModel bpmnModel = new BpmnModel();
Process process = new Process();
process.setId("simpleProcess");
process.setName("Very simple process");
bpmnModel.getProcesses().add(process);
StartEvent startEvent = new StartEvent();
startEvent.setId("startEvent1");
TimerEventDefinition timerDef = new TimerEventDefinition();
timerDef.setTimeDuration("PT5M");
startEvent.getEventDefinitions().add(timerDef);
ActivitiListener listener = new ActivitiListener();
listener.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION);
listener.setImplementation("${test}");
listener.setEvent("end");
startEvent.getExecutionListeners().add(listener);
process.addFlowElement(startEvent);
UserTask task = new UserTask();
task.setId("reviewTask");
task.setAssignee("kermit");
process.addFlowElement(task);
SequenceFlow flow1 = new SequenceFlow();
flow1.setId("flow1");
flow1.setSourceRef("startEvent1");
flow1.setTargetRef("reviewTask");
process.addFlowElement(flow1);
EndEvent endEvent = new EndEvent();
endEvent.setId("endEvent1");
process.addFlowElement(endEvent);
byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
new BpmnXMLConverter().validateModel(new InputStreamSource(new ByteArrayInputStream(xml)));
Deployment deployment = repositoryService.createDeployment().name("test").addString("test.bpmn20.xml", new String(xml))
.deploymentProperty(DeploymentProperties.DEPLOY_AS_ACTIVITI5_PROCESS_DEFINITION, Boolean.TRUE)
.deploy();
repositoryService.deleteDeployment(deployment.getId());
}
示例19
public void testConvertXMLToModel() throws Exception {
BpmnModel bpmnModel = readXMLFile();
bpmnModel = exportAndReadXMLFile(bpmnModel);
byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
processEngine.getRepositoryService().createDeployment().name("test1").addString("test1.bpmn20.xml", new String(xml))
.deploymentProperty(DeploymentProperties.DEPLOY_AS_ACTIVITI5_PROCESS_DEFINITION, Boolean.TRUE)
.deploy();
String processInstanceKey = runtimeService.startProcessInstanceByKey("process").getId();
Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceKey).messageEventSubscriptionName("InterruptMessage").singleResult();
assertNotNull(execution);
}
示例20
@Test
public void testWarningError() throws UnsupportedEncodingException, XMLStreamException {
String flowWithoutConditionNoDefaultFlow = "<?xml version='1.0' encoding='UTF-8'?>" +
"<definitions id='definitions' xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:activiti='http://activiti.org/bpmn' targetNamespace='Examples'>" +
" <process id='exclusiveGwDefaultSequenceFlow'> " +
" <startEvent id='theStart' /> " +
" <sequenceFlow id='flow1' sourceRef='theStart' targetRef='exclusiveGw' /> " +
" <exclusiveGateway id='exclusiveGw' name='Exclusive Gateway' /> " + // no default = "flow3" !!
" <sequenceFlow id='flow2' sourceRef='exclusiveGw' targetRef='theTask1'> " +
" <conditionExpression xsi:type='tFormalExpression'>${input == 1}</conditionExpression> " +
" </sequenceFlow> " +
" <sequenceFlow id='flow3' sourceRef='exclusiveGw' targetRef='theTask2'/> " + // one would be OK
" <sequenceFlow id='flow4' sourceRef='exclusiveGw' targetRef='theTask2'/> " + // but two unconditional not!
" <userTask id='theTask1' name='Input is one' /> " +
" <userTask id='theTask2' name='Default input' /> " +
" </process>" +
"</definitions>";
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(flowWithoutConditionNoDefaultFlow.getBytes()), "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(in);
BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
Assert.assertNotNull(bpmnModel);
List<ValidationError> allErrors = processValidator.validate(bpmnModel);
Assert.assertEquals(1, allErrors.size());
Assert.assertTrue(allErrors.get(0).isWarning());
}
示例21
protected void deployProcess(BpmnModel bpmnModel) {
byte[] xml = new BpmnXMLConverter().convertToXML(bpmnModel);
try {
Deployment deployment = processEngine.getRepositoryService().createDeployment()
.name("test")
.deploymentProperty(DeploymentProperties.DEPLOY_AS_ACTIVITI5_PROCESS_DEFINITION, Boolean.TRUE)
.addString("test.bpmn20.xml", new String(xml))
.deploy();
processEngine.getRepositoryService().deleteDeployment(deployment.getId());
} finally {
processEngine.close();
}
}
示例22
/***
* 流程定义转换Model
*/
@PutMapping(value = "/convert-to-model/{processDefinitionId}")
@ApiOperation("流程定义转换模型")
@Authorize(action = Permission.ACTION_UPDATE)
public ResponseMessage<String> convertToModel(@PathVariable("processDefinitionId") String processDefinitionId)
throws UnsupportedEncodingException, XMLStreamException {
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
.processDefinitionId(processDefinitionId).singleResult();
if (null == processDefinition) {
throw new NotFoundException();
}
InputStream bpmnStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),
processDefinition.getResourceName());
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(in);
BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
BpmnJsonConverter converter = new BpmnJsonConverter();
com.fasterxml.jackson.databind.node.ObjectNode modelNode = converter.convertToJson(bpmnModel);
org.activiti.engine.repository.Model modelData = repositoryService.newModel();
modelData.setKey(processDefinition.getKey());
modelData.setName(processDefinition.getResourceName().substring(0, processDefinition.getResourceName().indexOf(".")));
modelData.setCategory(processDefinition.getDeploymentId());
ObjectNode modelObjectNode = new 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());
repositoryService.saveModel(modelData);
repositoryService.addModelEditorSource(modelData.getId(), modelNode.toString().getBytes("utf-8"));
return ResponseMessage.ok(modelData.getId());
}
示例23
/**
* 将部署的流程转换为模型
* @param procDefId
* @throws UnsupportedEncodingException
* @throws XMLStreamException
*/
@Transactional(readOnly = false)
public org.activiti.engine.repository.Model convertToModel(String procDefId) throws UnsupportedEncodingException, XMLStreamException {
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefId).singleResult();
InputStream bpmnStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),
processDefinition.getResourceName());
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(in);
BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
BpmnJsonConverter converter = new BpmnJsonConverter();
ObjectNode modelNode = converter.convertToJson(bpmnModel);
org.activiti.engine.repository.Model modelData = repositoryService.newModel();
modelData.setKey(processDefinition.getKey());
modelData.setName(processDefinition.getResourceName());
modelData.setCategory(processDefinition.getCategory());//.getDeploymentId());
modelData.setDeploymentId(processDefinition.getDeploymentId());
modelData.setVersion(Integer.parseInt(String.valueOf(repositoryService.createModelQuery().modelKey(modelData.getKey()).count()+1)));
ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, processDefinition.getName());
modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, modelData.getVersion());
modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, processDefinition.getDescription());
modelData.setMetaInfo(modelObjectNode.toString());
repositoryService.saveModel(modelData);
repositoryService.addModelEditorSource(modelData.getId(), modelNode.toString().getBytes("utf-8"));
return modelData;
}
示例24
/**
* 根据Model部署流程
*/
public String deploy(String id) {
String message = "";
try {
org.activiti.engine.repository.Model modelData = repositoryService.getModel(id);
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);
String processName = modelData.getName();
if (!StringUtils.endsWith(processName, ".bpmn20.xml")){
processName += ".bpmn20.xml";
}
// System.out.println("========="+processName+"============"+modelData.getName());
ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
Deployment deployment = repositoryService.createDeployment().name(modelData.getName())
.addInputStream(processName, in).deploy();
// .addString(processName, new String(bpmnBytes)).deploy();
// 设置流程分类
List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list();
for (ProcessDefinition processDefinition : list) {
repositoryService.setProcessDefinitionCategory(processDefinition.getId(), modelData.getCategory());
message = "部署成功,流程ID=" + processDefinition.getId();
}
if (list.size() == 0){
message = "部署失败,没有流程。";
}
} catch (Exception e) {
throw new ActivitiException("设计模型图不正确,检查模型正确性,模型ID="+id, e);
}
return message;
}
示例25
public static void importModel(RepositoryService repositoryService, File modelFile) throws IOException,
XMLStreamException
{
InputStreamReader reader = new InputStreamReader(new FileInputStream(modelFile), "utf-8");
String fileContent = IOUtils.readStringAndClose(reader, (int) modelFile.length());
BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(new StringStreamSourceEx(fileContent), false,
false);
String processName = bpmnModel.getMainProcess().getName();
if (processName == null || processName.isEmpty())
{
processName = bpmnModel.getMainProcess().getId();
}
Model modelData = repositoryService.newModel();
ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, processName);
modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
modelData.setMetaInfo(modelObjectNode.toString());
modelData.setName(processName);
modelData.setKey(modelFile.getName());
repositoryService.saveModel(modelData);
repositoryService.addModelEditorSource(modelData.getId(), fileContent.getBytes("utf-8"));
Logger.getLogger(ModelUtils.class)
.info(String.format("importing model file: %s", modelFile.getCanonicalPath()));
}
示例26
/**
* 转换流程定义为模型
* @param processDefinitionId
* @return
* @throws UnsupportedEncodingException
* @throws XMLStreamException
*/
@RequestMapping(value = "/process/convert-to-model/{processDefinitionId}")
public String convertToModel(@PathVariable("processDefinitionId") String processDefinitionId)
throws UnsupportedEncodingException, XMLStreamException {
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
.processDefinitionId(processDefinitionId).singleResult();
InputStream bpmnStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),
processDefinition.getResourceName());
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8");
XMLStreamReader xtr = xif.createXMLStreamReader(in);
BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
BpmnJsonConverter converter = new BpmnJsonConverter();
ObjectNode modelNode = converter.convertToJson(bpmnModel);
Model modelData = repositoryService.newModel();
modelData.setKey(processDefinition.getKey());
modelData.setName(processDefinition.getResourceName());
modelData.setCategory(processDefinition.getDeploymentId());
ObjectNode modelObjectNode = new 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());
repositoryService.saveModel(modelData);
repositoryService.addModelEditorSource(modelData.getId(), modelNode.toString().getBytes("utf-8"));
return "redirect:/chapter20/model/list";
}
示例27
/**
* 把XML转换成BpmnModel对象
* @throws Exception
*/
@Test
@Deployment(resources = "chapter6/dynamic-form/leave.bpmn")
public void testXmlToBpmnModel() throws Exception {
// 验证是否部署成功
long count = repositoryService.createProcessDefinitionQuery().count();
assertEquals(1, count);
// 根据流程定义获取XML资源文件流对象
/*ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("leave").singleResult();
String resourceName = processDefinition.getResourceName();
InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);*/
// 从classpath中获取
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("chapter6/dynamic-form/leave.bpmn");
// 创建转换对象
BpmnXMLConverter converter = new BpmnXMLConverter();
// 创建XMLStreamReader读取XML资源
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(inputStream);
// 把XML转换成BpmnModel对象
BpmnModel bpmnModel = converter.convertToBpmnModel(reader);
// 验证BpmnModel对象不为空
assertNotNull(bpmnModel);
Process process = bpmnModel.getMainProcess();
assertEquals("leave", process.getId());
}
示例28
public BpmnParse execute() {
try {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
BpmnXMLConverter converter = new BpmnXMLConverter();
boolean enableSafeBpmnXml = false;
String encoding = null;
if (processEngineConfiguration != null) {
enableSafeBpmnXml = processEngineConfiguration.isEnableSafeBpmnXml();
encoding = processEngineConfiguration.getXmlEncoding();
}
if (encoding != null) {
bpmnModel = converter.convertToBpmnModel(streamSource, validateSchema, enableSafeBpmnXml, encoding);
} else {
bpmnModel = converter.convertToBpmnModel(streamSource, validateSchema, enableSafeBpmnXml);
}
// XSD validation goes first, then process/semantic validation
if (validateProcess) {
ProcessValidator processValidator = processEngineConfiguration.getProcessValidator();
if (processValidator == null) {
LOGGER.warn("Process should be validated, but no process validator is configured on the process engine configuration!");
} else {
List<ValidationError> validationErrors = processValidator.validate(bpmnModel);
if(validationErrors != null && !validationErrors.isEmpty()) {
StringBuilder warningBuilder = new StringBuilder();
StringBuilder errorBuilder = new StringBuilder();
for (ValidationError error : validationErrors) {
if (error.isWarning()) {
warningBuilder.append(error.toString());
warningBuilder.append("\n");
} else {
errorBuilder.append(error.toString());
errorBuilder.append("\n");
}
}
// Throw exception if there is any error
if (errorBuilder.length() > 0) {
throw new ActivitiException("Errors while parsing:\n" + errorBuilder.toString());
}
// Write out warnings (if any)
if (warningBuilder.length() > 0) {
LOGGER.warn("Following warnings encountered during process validation: " + warningBuilder.toString());
}
}
}
}
bpmnModel.setEventSupport(new ActivitiEventSupport());
// Validation successful (or no validation)
createImports();
createItemDefinitions();
createMessages();
createOperations();
transformProcessDefinitions();
} catch (Exception e) {
if (e instanceof ActivitiException) {
throw (ActivitiException) e;
} else if (e instanceof XMLException) {
throw (XMLException) e;
} else {
throw new ActivitiException("Error parsing XML", e);
}
}
return this;
}
示例29
public BpmnParse execute() {
try {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
BpmnXMLConverter converter = new BpmnXMLConverter();
boolean enableSafeBpmnXml = false;
String encoding = null;
if (processEngineConfiguration != null) {
enableSafeBpmnXml = processEngineConfiguration.isEnableSafeBpmnXml();
encoding = processEngineConfiguration.getXmlEncoding();
}
if (encoding != null) {
bpmnModel = converter.convertToBpmnModel(streamSource, validateSchema, enableSafeBpmnXml, encoding);
} else {
bpmnModel = converter.convertToBpmnModel(streamSource, validateSchema, enableSafeBpmnXml);
}
// XSD validation goes first, then process/semantic validation
if (validateProcess) {
ProcessValidator processValidator = processEngineConfiguration.getProcessValidator();
if (processValidator == null) {
LOGGER.warn("Process should be validated, but no process validator is configured on the process engine configuration!");
} else {
List<ValidationError> validationErrors = processValidator.validate(bpmnModel);
if (validationErrors != null && !validationErrors.isEmpty()) {
StringBuilder warningBuilder = new StringBuilder();
StringBuilder errorBuilder = new StringBuilder();
for (ValidationError error : validationErrors) {
if (error.isWarning()) {
warningBuilder.append(error.toString());
warningBuilder.append("\n");
} else {
errorBuilder.append(error.toString());
errorBuilder.append("\n");
}
}
// Throw exception if there is any error
if (errorBuilder.length() > 0) {
throw new ActivitiException("Errors while parsing:\n" + errorBuilder.toString());
}
// Write out warnings (if any)
if (warningBuilder.length() > 0) {
LOGGER.warn("Following warnings encountered during process validation: " + warningBuilder.toString());
}
}
}
}
bpmnModel.setSourceSystemId(sourceSystemId);
bpmnModel.setEventSupport(new ActivitiEventSupport());
// Validation successful (or no validation)
// Attach logic to the processes (eg. map ActivityBehaviors to bpmn model elements)
applyParseHandlers();
// Finally, process the diagram interchange info
processDI();
} catch (Exception e) {
if (e instanceof ActivitiException) {
throw (ActivitiException) e;
} else if (e instanceof XMLException) {
throw (XMLException) e;
} else {
throw new ActivitiException("Error parsing XML", e);
}
}
return this;
}
示例30
protected BpmnModel readXMLFile() throws Exception {
InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(getResource());
StreamSource xmlSource = new InputStreamSource(xmlStream);
BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xmlSource, false, false, processEngineConfiguration.getXmlEncoding());
return bpmnModel;
}