The next step is to create a BPMN definitions element. Set the target namespace on it and add itto the newly created empty model instance.
definitions.setTargetNamespace("http://camunda.org/examples");
modelInstance.setDefinitions(definitions);
Usually you want to add a process to your model. This followsthe same 3 steps as the creation of the BPMN definitions element:
- Create a new instance of the BPMN element
- Set attributes and child elements of the element instance
- Add the newly created element instance to the corresponding parent element
To simplify this repeating procedure, you can use a helper method like this one.
protected <T extends BpmnModelElementInstance> T createElement(BpmnModelElementInstance parentElement, String id, Class<T> elementClass) {
T element = modelInstance.newInstance(elementClass);
element.setAttributeValue("id", id, true);
parentElement.addChildElement(element);
return element;
}
Validate the model against the BPMN 2.0 specification and convert it toan XML string or save it to a file or stream.
// validate the model
Bpmn.validateModel(modelInstance);
// convert to string
// write to output stream
Bpmn.writeModelToStream(outputStream, modelInstance);
// write to file
File file = new File(...);
Bpmn.writeModelToFile(file, modelInstance);
Example 1: Create a Simple Process With One User Task
With the basic helper methods from above it is very easy and straightforward to create simple processes. First, create aprocess with a start event, user task and an end event.
Example 2: Create a Simple Process With Two Parallel Tasks
Even more complex processes can be created with a few lines of code with the standard BPMN model API.
// create an empty model
BpmnModelInstance modelInstance = Bpmn.createEmptyModel();
Definitions definitions = modelInstance.newInstance(Definitions.class);
definitions.setTargetNamespace("http://camunda.org/examples");
modelInstance.setDefinitions(definitions);
// create elements
StartEvent startEvent = createElement(process, "start", StartEvent.class);
ParallelGateway fork = createElement(process, "fork", ParallelGateway.class);
UserTask task2 = createElement(process, "task2", UserTask.class);
task2.setName("User Task");
ParallelGateway join = createElement(process, "join", ParallelGateway.class);
EndEvent endEvent = createElement(process, "end", EndEvent.class);
// create flows
createSequenceFlow(process, startEvent, fork);
createSequenceFlow(process, fork, task1);
createSequenceFlow(process, fork, task2);
createSequenceFlow(process, task1, join);
createSequenceFlow(process, task2, join);
createSequenceFlow(process, join, endEvent);
// validate and write model to file
Bpmn.validateModel(modelInstance);