JBoss jBPM 3 is a flexible, extensible framework for process languages which uses graph oriented programming as a foundation. As the word says it, a graph based language represent some kind of execution which can be shown as a graph (Imagine a simple flow chart which explains the track of a business decision for example).

Business process management can be defined as a procedure in an organization: some of this procedures can be automated, some need human work.

Why we need a BPM in Java ?

the basic of an interaction with other systems is the exchange of information/messages

sendInformationToAreaB();

Response r = waitForResponseFromB();

What is the limitation with this ? the first limitation is that by itself this little code is not persistable, yes of course you can wrap it with some Object/Relational tool...but what about waiting states ? even if you implement it as a Thread you cannot persist a Java Thread.

The second one is that you might need a graphical representation of this......for example your Boss wants to take a look at your process...or even more, what about if business changes ? without a native graphical implementation of the process you have to do double work: re-engineering the Code and the Graph with your favourite tool.

So now let's get our hand dirty ! The first thing to do is to download a fresh copy of JBPM fron jBoss site. For this article we'll use jbpm-jpdl-suite-3.2.3.zip downloadable from www.jboss.org site.

This archive includes embedded application server (JBoss of course) and the graphical designer. Before entering in the details let's make clear one thing: usually BPM engines have a tight coupling with the graphical environment : meaning you have to use the graphical editor to draw or change your process. JBPM is basically a process management Api built on Hibernate (which maps the basic workflow tables) and it can live well without any graphical editor. It does exists a plugin built with Eclipse technology which lets you reverse-engineer your graphical process into an XML file, yet you can still design your process with a simple notepad and a Java compiler.

So keep separated the concept of the Graphical Process Designer (GPD), which will be used by analyst/ top managers to describe the process and the process it self which is only xml and pure Java. Nice separation of tasks between analysts and developers isn't it ? 

So we talked about XML: what is the process language of jBPM? there are more then one but just for beginning we'll concentrate on the most common: that is jPDL. JPDL is an XML structured language which has a specific process grammar to describe process definitions, nodes and transitions.

Meanwhile you read this article I guess you have finished downloading jbpm-jpdl-suite-3.2.3.zip. So unzip it and launch the designer.bat (or designer.sh for Unix/Linux users) under the "designer" folder.

Once Eclipse is started, launch the "New..." Menu and select new Process project

  JBPM tutorial

Then choose a convenient name for your Project and wait until you'll see your Project in the Package explored. Resist one more minute before looking at your process: open the JBPM library tag in the Package explorer: you'll see the libraries needed to run your process from a standalone application. Quite a lot, isn't it ? but only two of them are the core jBPM libraries, all the others are just dependancies.

  • jbpm-3.x.x.jar
  • jbpm-identity-3.x.x.jar

So if you plan to run your application on a JBoss application server these 2 are the only libraries you'll need to add to your war/ear file. We'll start with a simple process which describes an order management system.

process

 

The process is quite straightforward : once the process is started we meet a Task Node: in short a task node represents an activity that is performed by humans. This task will be in charge of user "buyer".

Once the order is performed we have a Decision Node where the process can lead to different Nodes based on the data at its disposal. In our case we check if the goods ordered are available. If they're not available the process is switched to a State Node named "GetFromStock". A State Node simply tells the process instance to wait and, in contrast to a task node, it doesn't create an activity in anybody's task list.

At last our goods needs to be shipped and this will be another task in charge to our Deliver Office. Once also this task is completed our process will come to a end.

 


 

Ok, so what's behind this picture ? jBPM uses jPDL to describe the process in XML format.

<process-definition xmlns="urn:jbpm.org:jpdl-3.2"
    name="simple">
    <swimlane name="buyer">
        <assignment actor-id="customer"></assignment>
    </swimlane>

    <swimlane name="deliverDepartment">
        <assignment actor-id="deliver-man"></assignment>
    </swimlane>

    <start-state name="start">
        <transition name="trPlaceOrder" to="PlaceOrder"></transition>
    </start-state>

    <task-node name="PlaceOrder">
        <task name="placeOrderTask" swimlane="buyer">
        </task>
        <transition name="" to="CheckAvailability"></transition>
    </task-node>

    <decision name="CheckAvailability">
        <handler class="com.sample.decision.VerifyOrder"></handler>
        <transition name="trDeliver" to="Deliver"></transition>
        <transition name="trGetFromStock" to="GetFromStock"></transition>
    </decision>

    <state name="GetFromStock">
        <event type="node-enter">
            <action class="com.sample.action.GetFromStockActionHandler"
                name="recharge"></action>
        </event>
        <transition name="checkAvailability" to="CheckAvailability"></transition>
    </state>

    <task-node name="Deliver">
        <task name="getFromStock" swimlane="deliverDepartment">
        </task>
        <transition name="trEnd" to="end"></transition>
    </task-node>

    <end-state name="end"></end-state>
</process-definition>

 

You can clearly see how the graphical elements have been translated into XML source code. jPDL in not too complicated, in short it will associate actions with handlers. Handlers are written as plain Java classes implementing business interfaces.

For example, the decision node CheckAvailability delegates to a DecisionHandler which path should be followed by our process. Here we'll use a very simple decision handler which compares two process variables in order to decide if there are enough good in the stock. In real world process, we'll likely query a Database in order to collect this information.  

package com.sample.decision;

import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.node.DecisionHandler;

public class VerifyOrder implements DecisionHandler {


    public String decide(ExecutionContext executionContext) throws Exception {

        Integer goodsOrdered = (Integer)executionContext.
                getContextInstance().getVariable("goodsOrdered");
        System.out.println("Goods ordered "+goodsOrdered.intValue());


        Integer goodsInStock = (Integer)executionContext.
                getContextInstance().getVariable("goodsInStock");
        System.out.println("Goods in stock "+goodsInStock.intValue());

        if (goodsOrdered.intValue() > goodsInStock.intValue()) {
            return "trGetFromStock";
        }
        else {
            return "trDeliver";
        }
    }

}

 


 

Decision Handler are not the only example of Handler provided by jBPM. We have also ActionHandlers which will be used in case we need to get supply for our goods from the Stock. Again here we need to implement the correct interface which will be fired on the event type "node-enter" for the Node "GetFromStock". 

package com.sample.action;

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

public class GetFromStockActionHandler implements ActionHandler {

    public void execute(ExecutionContext context) throws Exception {
        System.out.println("Getting goods from factory!");

        context.getContextInstance().
        setVariable("goodsInStock", new Integer(300));

        context.leaveNode();
    }

}

Here we need to implement the method execute which will be used to fire our business logic, in practice we fill up our stock and when done we leave the node as we've got nothing else to do.

The last thing we left our are swimlanes.

Swimlanes represents process roles and they're used to assign tasks to specific people. Unlike other components they aren't mapped visually in the process definition but they are added as techical detail.


Swimlanes can be one actor or a pooled group of actors: in our example we simply define 2 swimlanes: one for the buyer, who places the order, and one for the deliverDepartment which deliver the goods. Ok, now need a client to test our Process: this can be anything , a Servlet, an EJB or a plain Java Class as our sample. 

package com.sample;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

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

public class SimpleProcessTest {
    public static void main(String args[])throws Exception {
        new SimpleProcessTest().execute();
    }
    public void execute() throws Exception {

        // Extract a process definition from the processdefinition.xml file.
        ProcessDefinition processDefinition = ProcessDefinition.parseXmlResource("simple/processdefinition.xml");
        HashMap map = new HashMap();

        map.put("goodsOrdered",new Integer(100));
        map.put("goodsInStock",new Integer(50));

        // Create an instance of the process definition.
        ProcessInstance instance = new ProcessInstance(processDefinition,map);

        displayStatus(instance);

        instance.signal();

        displayStatus(instance);

        executeTask(instance);

        displayStatus(instance);

        executeTask(instance);
        displayStatus(instance);

    }

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

    }   
    /* This is a dummy method which prints out the list of TaskInstances  and completes all the single tasks   
     */  
    private void executeTask(ProcessInstance instance) {   

        Collection c = instance.getTaskMgmtInstance().getTaskInstances();   
        Iterator iter = c.iterator();   
        while (iter.hasNext()) {   

            TaskInstance taskInstance = (TaskInstance)iter.next();   

            if (!taskInstance.hasEnded())   
                taskInstance.end();   
            System.out.println("Found Task "+taskInstance.getName());   
            System.out.println("Task completed.");   
        }   


    }   

}

As you can see, we need to create an instance of ProcessDefinition to map our Process as a Java class. Once we've our ProcessDefinition we create a ProcessInstance which represents is our Customer Order, so for every Definition we've got many ProcessInstances.

Our client simply sends signals to our process telling to advance to the next node. When we've entered a Task Node we read the task list and we end our Task. In this case we use another class to map our Tasks, the TaskInstance class which holds all the information concerning our task.

Running our application will produce the following output:

We're in state start
We're in state PlaceOrder
Found task placeOrderTask in charge to customer
Goods ordered 100
Goods in stock 50
Getting goods from factory!
Goods ordered 100
Goods in stock 300
We're in state Deliver
Found task getFromStock in charge to deliver-man
We're in state end

Conclusion

JBoss jBPM provides a sophisticated platform for designing and developing workflows and business process management systems. Its framework of APIs, domain-specific language, and graphical modeling tool enables developers and business analysts to communicate and operate using a common platform. In this article, I discussed the high-level concepts of JBoss jBPM that will give you a place to start your journey towards a workflow-oriented future with BPM and Java.

Additional resources:
Download here the code from this example

0
0
0
s2smodern

Related articles available on mastertheboss.com

How do I fire an action every time a JBPM Node enters?

JBoss recipe of the day

JBoss Jbpm superstates

What is a superstate ? a Superstate is a group of nodes. Supersta

Jbpm Mail delivery

Almost every workflow needs a notification of the process activit

How do you embed Java code in your JPDL ?

  You can use a BeanShell expression to add a Java script in you

JBPM best practices

There's no perfect rule to model your workflow, it depends on the

How to delete/persist your JBPM process after restart ?

JBoss recipe of the day