Friday, December 19, 2008

A very basic JBPM tutorial - Hello World

According to the documentation
a minimal deployment of JBPM needs the following jars:
  • jbpm-jpdl-3.3.0.GA.jar
  • commons-logging.jar
  • dom4j.jar
To start off we create the process definition. It consists of a start and end state and an additional intermediate state.

<process-definition xmlns="urn:jbpm.org:jpdl-3.2" name="simple">

<start-state name="Start">
<transition name="trHelloWorld" to="HelloWorld"></transition>
</start-state>

<state name="HelloWorld">
<event type="node-enter">
<action class="HelloWorldActionHandler" name="recharge"></action>
</event>
<transition name="trEnd" to="End"></transition>
</state>

<end-state name="End"></end-state>

</process-definition>


The state with name HelloWorld executes an action when the node-enter event is fired by the process executuion engine. The Action is implemented as Java code:

import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

public class HelloWorldActionHandler implements ActionHandler {
private static final long serialVersionUID = 1L;

public void execute(ExecutionContext context) throws Exception {
System.out.println("Hello World!");
}
}


For the definition of the process nothing more is needed. It can be run outside of containers and does not need a database for non persistent processes. To start the process you have to load the definition and create a concrete ProcessInstance:

import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;

public class SimpleProcess {
public static void main(String[] args) {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlResource("process-def.xml");
ProcessInstance instance = new ProcessInstance(processDefinition);
displayStatus(instance);
instance.signal();
displayStatus(instance);
instance.signal();
displayStatus(instance);
}

private static void displayStatus(ProcessInstance instance) {
String nodeName = instance.getRootToken().getNode().getName();
System.out.println("You are now in node: " + nodeName);
}
}


To trigger a transition the method signal() is called on the process instance. An action handler can leave the state by calling context.leaveNode().

No comments: