Small steps with big feet
jBPM4 real-life example: The Train Ticket Demo (part 2: coding the business process)
In the previous article I’ve showed how a business process born from a real-life problem can be modeled using the Signavio web-based jBPM editor. The end result consists of a BPMN model that is understandable by all parties involved, which is stored on the hard disk as a JPDL file that is executable on the jBPM process engine.
Today, we’ll explore the second step in the BPM lifecycle, the actual development of the business process. When the business analyst delivers a first draft of the BPMN model, the developers team can get into action. After all, a business process is always business-specific, which means that no BPM product can ever cover every aspect of the business out-of-the-box (altough some do promise this).
Business-specific logic
The main strength of jBPM is its embeddability into any Java environment. Whereas many BPM products are big black-box servers, jBPM is at its core just a simple Java library that just fits into any architecture. This means that writing your business specific logic boils down to writing regular Java, no magic involved. All the rules that apply to writing normal Java applications are applicable to writing logic for your business process, which means that you don’t need to learn yet another language to actually go forward.
Since jBPM is Just A Java Library (TM), this also means you can just write regular (J)Unit test (or TestNG, or whatever gets you going) to actually test the business process logic. Once again, nothing in my sleeves, no magic involved. The business process described in the previous article is graphically shown below:
The BPMN model generated by the Signavio editor can be imported straight into the Eclipse based Graphical Process Designer (GPD) – remember the end of the screencast of the previous article. The GPD allows you to implement the business logic graphically or in the JPDL source format. For me personally, the JPDL source editing has always been my preferred choice (once you know your way around, it’s extremely fast), but you can pick whatever you like.
One of the goals of the JPDL format, which is an XML language by the way, is to have a lanuage that is as concise, readable and as rich as possible. Take a look at the JPDL version of the process above, now enhanced with Java logic by the dev team:
<process name="ticketProcess" xmlns="http://jbpm.org/4.0/jpdl">
<start name="start">
<transition to="Calculate quote"/>
</start>
<custom name="Calculate quote" class="org.jbpm.trainticketdemo.action.CalculateQuoteAction">
<transition to="Check customer credit"/>
</custom>
<custom name="Send price quote to customer" class="org.jbpm.trainticketdemo.action.SendQuoteToCustomerAction">
<transition to="Accept quote"/>
</custom>
<custom name="Send reject message" class="org.jbpm.trainticketdemo.action.SendQuoteToCustomerAction">
<transition to="cancel"/>
</custom>
<decision name="Check customer credit">
<handler class="org.jbpm.trainticketdemo.decision.CheckCustomerDecision" />
<transition name="credit OK" to="Send price quote to customer"/>
<transition name="credit NOK" to="Send reject message"/>
</decision>
<task assignee="#{cellPhoneNr}" name="Accept quote">
<transition to="charge customer"/>
<transition name="timeout" to="cancel">
<timer duedate="1 day"/>
</transition>
</task>
<custom name="charge customer" class="org.jbpm.trainticketdemo.action.ChargeCustomerAction">
<transition to="end"/>
</custom>
<end-cancel name="cancel"/>
<end name="end"/>
</process>
Notice how easy to read this process format is, and compare it with other formats (I’m not saying which, but it tends to end with ‘PEL’).
You can easily see how easy it is to attach business-specific logic to the business process:
<custom name="Calculate quote" class="org.jbpm.trainticketdemo.action.CalculateQuoteAction"> <transition to="Check customer credit"/> </custom>
The CalculateQuoteAction class is a just regular POJO that implements an interface defined by the jBPM API:
public class CalculateQuoteAction implements ActivityBehaviour {
private QuoteService quoteService;
public CalculateQuoteAction() {
this.quoteService = EjbUtil.getQuoteService();
}
public void execute(ActivityExecution execution) {
String from = (String) execution.getVariable("from");
String to = (String) execution.getVariable("to");
String cellphoneNr = (String) execution.getVariable("cellNr");
Quote quote = quoteService.calculateQuote(from, to, cellphoneNr);
execution.setVariable("quote", quote);
}
}
The ActivityBehaviour interface defines one method ‘execute‘ which will be called by the process engine once the business process engine arrives in this activity.
Remember, the real calculation is done on a system already implemented by the train operator (see process diagram), so the logic is very easy here:
- retrieve the input variables (from, to, cellphone number) from the process instance (the variables are stored in the process instance when the process is started, see the unit test later)
- calculate a price quote by calling a remote EJB service (wrapped in the EjbUtil class). Here it is an EJB service, but it can really be virtually anything you can imagine doing in Java code.
- store the resulting price quote as a process variable in the process instance.
The parallel gateway (decision) which will determine which path to follow in the process, depending on the customer credit, is also very simple:
public class CheckCustomerDecision implements DecisionHandler {
private static final String OK_DECISION = "credit OK";
private static final String NOT_OK_DECISION = "credit NOK";
public String decide(OpenExecution execution) {
Quote quote = (Quote) execution.getVariable(ProcessVariable.QUOTE);
User user = getUser(quote);
if (user != null && hasEnoughCredit(user, quote)) {
return OK_DECISION;
}
return NOT_OK_DECISION;
}
...
And I can go on quite a long time by pasting these snippets. If you want to see all the handlers and activities, just take a look at out svn repo.
Typically, each business-specific class will not have many lines of code. If this is not the case, then you probably can remodel your process to something less complex and better understandable. Every node in the diagram should have one responsibility, ideally. In practice, you’ll notice that after a while you’ll be able to start reusing these little POJO classes.
Also note how SOA-ready these little classes are: in a SOA environment the business specific code will typically be nothing more than just calls to services (which is the case with the examples above). jBPM will help you greatly here, since you can write Java code (and connect to any service reachable by Java technology) and you don’t have to wrap services in a webservice for example.
The last construct I want to explain is the task:
<task <strong>assignee="#{cellPhoneNr}"</strong> name="Accept quote">
<transition to="charge customer"/>
<transition name="timeout" to="cancel">
<timer duedate="1 day"/>
</transition>
</task>
A lot is going on here:
- The task is assigned to the cellphone number which is one of the inputs of the process. Notice the use of expressions (#{…}) here, which make the process XML very readable.
- The process will wait for a task completion event forever, if it wasn’t for the timer construct on line 4. After a day, the timer fires and the ‘timeout’ transition will be taken (which will go to a cancel-end). This way, no process instances will be running longer than a day.
The Unit Test
Like I said in the previous paragraph, the huge benefit of jBPM is that everything is plain Java. So writing a unit test is very recognizable:
public void testTrainTicketProcessWithEnoughCredit() {
// First we deploy the latest version of the train ticket process
NewDeployment deployment = repositoryService.createDeployment();
deployment.addResourceFromClasspath("../process.jpdl.xml");
deployment.deploy();
// Start a new Process instance
Map<String, String> vars = new HashMap<String, String>();
vars.put(ProcessVariable.FROM, "Brussels");
vars.put(ProcessVariable.TO, "Antwerp");
vars.put(ProcessVariable.CELLPHONE_NUMBER, testUser.getCellphoneNr());
ProcessInstance pi = executionService.startProcessInstanceByKey("ticketProcess", vars);
// Since I have enough money, the 'Accept Quote' task should be assigned to the test user's cellphone nr
List<Task> tasks = taskService.findPersonalTasks(testUser.getCellphoneNr());
assertTrue("Nr of tasks for cellphone nr = " + tasks.size(), tasks.size() == 1);
// or we can use the new Query API
Task task = taskService.createTaskQuery()
.assignee(testUser.getCellphoneNr())
.uniqueResult();
assertEquals(tasks.get(0).getName(), task.getName());
// After task completion, the process is finished
taskService.completeTask(task.getId());
assertProcessInstanceEnded(pi);
// We always clean up after ourselves
repositoryService.deleteDeploymentCascade(deployment.getId());
}
See the svn repo for the full source.
If you haven’t seen the new jBPM API yet, do take a closer look at the unit test code and the comment lines I added. As you can see, the process is kickstarted by calling the executionService, providing it a process definition name and a collection of variables (from, to, and the cellphone nr).
To actually run the unit test, you’ll need to configure the jBPM process engine. This configuration has ondergone a serious facelift with respect to jBPM3 (where the config could get messy):
<jbpm-configuration> <import resource="jbpm.default.cfg.xml"/> <import resource="jbpm.tx.hibernate.cfg.xml"/> <import resource="jbpm.jpdl.cfg.xml"/> <import resource="jbpm.identity.cfg.xml"/> <import resource="jbpm.businesscalendar.cfg.xml"/> <import resource="jbpm.jobexecutor.cfg.xml"/> </jbpm-configuration>
This config gives us an environment with Hibernate, transactions and a job executor. Couldn’t be easier, right?
The Unit Test in Action
Of course, as I promised I will prove all the articles in this series with real source code, and screencasts. Click on the picture below to view the next screencast. In this movie, the unit test of above is shown to actually execute within Eclipse (Maven would also work).
What’s next
We’ve already tackled the process modeling and the first go at adding custom business logic. In the next article, we’ll take a closer look at the jBPM web-console and how it can be used for prototyping business processes before actually building the real application.
Stay tuned!
jBPM 4 real-life example: The Train Ticket Demo (part 1: modeling the process with BPMN)
For many technical people, the choice for jBPM is a no-brainer. But more than often framework or product decisions are not made by the tech audience, but by managers, project leads, etc. In most cases these people have other criteria than mere technical advantages. Sadly, this can lead to a choice for products which are not developer-friendly and are not appealing to the dev crowd. The goal of the article is to demonstrate that jBPM can offer anything you’d expect from a typical BPM product(read: big vendor BPM black-boxes products) and much more, of course
.
This article is the first in a series of articles (probably five or six parts) in which I’ll show that jBPM has all the shiny features for both developers and non-technical people. We’ll start from the very beginning (modeling a process), do unit testing, prototyping, BAM, BI and in the end we’ve built ourselves a scalable, high-performant application that could go straight into production. The goal of the article is to show to both sides of the playground that jBPM not only offers shiny development features, but also that it can be used to build any BPM-driven application out there. With all the features that non-technical people adore.
Tom Baeyens smoke tested the demo application in his talk on JBoss World. He received a lot of positive feedback there, and we appreciate any feedback on this and the next articles. All the source code will be put online with the articles, so don’t hesitate to show it to all your co-workers or to convince your managers
The business process explained
Picture this: it’s a rainy work-Monday-morning and somehow the wake-up alarm didn’t go off. You’re barely arrive in time in the train station and you remember you don’t have a train ticket. You could go and buy one at the automatic vending machines, but looking at the crowd there, you just know that you’ll never be able to catch your train. You also could look for the train conductor and buy a ticket from him, but often the tickets costs way more than when you buy it upfront. A last option is to not buy a ticket, and look around anxiously every time you hear someone coming, fearing it is someone official checking the tickets. …. Ah choices, choices, choices …. it feels like it’s going to be a long long week!
The problem here is that the ways of buying a train ticket is just soooo old-fashioned and not well-suited for this fast-moving world. The business process we’ll be using throughout the articles solves this problem. More precisely, we’ll model and develop a jBPM process that will handle for us a train ticket sale, using only a cellphone! So even if you are running late, just sending a text message will get you a valid ticket.
Note that we’ve named our ticket sale handling platform ‘jBPM on Rails’, since it seems fancy today to add the ‘rails’ suffix
The business process is graphically shown below (click for a bigger version). Most of it will be described in detail in a next article, but here’s a short summary
- The business process is started when a ticket request is received from a cellphone
- Using the start and end train stations used in the ticket request text message, a price quote will be calculated. The calculation of price quotes is something that already is implemented by the train operator, so we’ll call an external service to actually get the quote.
- If the customer associated with the cellphone has not enough credit on his/her balance, a rejection message is send.
- If the credit is OK, the quote is sent to the customer.
- An ‘accept task’ will now be automatically created.
- The customer can complete this task by sending an acceptance text message.
- Finally the customer is billed and the process finishes. The customer now has a valid ticket.
Modeling for and by the business
The story of every business process starts with the creation of the business process diagram. Often this is done by domain experts (business analysts), but this could be anyone in reality (I’ve seen developers doing the modeling … but this doesn’t mean I agree with it
). Creating a business process takes time. It involves communication with business end-users, other businesses which are interacted with, stakeholders of a company, etc. Typically, the process that you model today will not look anyhting like the same process, next year.
The jBPM 4 platform just offers you this kind of tool. Through our close collaboration with Signavio, modeling a process has never been easier. The Signavio web editor is shipped with the jBPM distribution (since jBPM 4.1) and can be installed in on a web server in less than a minute.

The following screencast shows the creation of the Train Ticket business process by a business analyst. You can see that process modelers only need a web browser to start modeling the process. The Signavio editor uses the widespread BPMN notation, which is known by virtually every business analyst out there. People can collaborate easily on the same process through the browser. The BPMN diagram is eventually saved on the hard disk in the native jBPM JPDL file format, which can be imported into the jBPM Graphical Process Designer (GPD).
What’s next
In the next article, we’ll cover the next phase of the BPM lifecycle: development. We’ll use the process definition produced by the Signavio editor and enhance it with Java logic in Eclipse and the GPD. We’ll show how easy it is to test business processes in plain Java unit tests and how easy jBPM embeds with any Java technology.
Stay tuned for more!
Related
jun 09: jBPM goes web-based modeling
aug 09: Web-based BPMN modeling with jBPM and Signavio
Custom Business Intelligence reporting with jBPM4 (‘What’s new’ part 5)
People who have tried the new jBPM4 web console will have noticed that there is a ‘reporting’ tab which renders two reports that are shipped with the jBPM4 distribution.

But few people know that these reports are in fact completely customizeable. We have deliberately included only a few reports in the distribution, because we believe that no business process report is valuable without custom business domain data. Using the Eclipse BIRT tooling, it is possible to take a look at the report templates we ship in the distribution. These reports can then be easily customized or completely new reports can be created.
Don’t be overwhelmed by the features of BIRT when you try it out the first time, BIRT has some excellent tutorials which will get you going quickly. Once you tasted the power of BIRT, you’ll be creating hi-quality reports in no time! After all, it’s not a coincidence that BIRT is an industry-leading tool for reporting.
In the upcoming jBPM 4.1 release we have included 2 new sample report templates. One report is actually used in the 4.1 console and the other one serves as an example of a report with a custom input form. Once JBPM-2453 is fixed, the second template will also be included in the distribution (probably jBPM 4.2).
Click on the picture below to see a very small demo of the new jBPM4 report templates which are shown in Eclipse BIRT and in the jBPM web console. The demo also shows that starting some new process instances will change the report generated by the console.
Enjoy!
Interesting blog by Khaled Ben Driss (French)
Every morning, during the obligatory coffee injection, I randomly surf the web using jBPM keywords. Due to DZone, java.blogs, Google alert, etc. there isn’t much to find that wasn’t already published on the other channels.
But today I managed to find a blogpost dating back to last month, which had apparently slipped through. So I’m relinking it here, to give it the attention it deserves. The article gives a high-level overview of jBPM4 and compares it with some properties of jBPM3. In my opinion, the quality of the articles is great (or is it my French?), so give the other (jBPM) articles also a read. Enjoy!
http://net-progress.blogspot.com/2009/07/jbpm-4-tutorial-jbpm-4-simplifie-son.html
Announcement: Web-based BPMN modeling with jBPM and Signavio!
About a month ago, I wrote about the collaboration between jBPM and Signavio.
I got many enthousiastic reactions on this announcement, so I’m extremely excited to be able to announce today that the Signavio editor will be bundled with upcoming jBPM 4.1 release. The target release date of jBPM 4.1 is next month, 1st of September … yes, that’s less than a month away!
Also, for those of you who will attend JBoss World next month, don’t miss the presentation of Tom Baeyens. I’m quite convinced he’ll have more of this fine news up his sleeve.
To show that we mean serious business, here’s a sneak peek of the Signavio editor used to create a BPMN model which is stored as jBPM JPDL. Many thanks to the Signavio and Oryx people for the top-notch collaboration!
Click the image below for a 7 minute video screencast. The screencast shows the creation of a simple BPMN process, which is then used in a JBPM unit test.
regards,
Joram
jBPM 4.0: basic taskform tutorial (what’s new – part 4)
Introduction
The jBPM framework is often used in an embedded way, where the BPM models are an integral part of the application architecture. Often, this means the creation of custom screens which interact with the BPM engine to communicate with end-users. But there is a whole spectrum of applications which don’t need a full-blown architecture to transform a real-life business process into executable computer code (like intranet webapps or a complex algorithm that needs to be executed on certain points in time).
In this post, I’ll show you how easy it is to assemble such a webapplication, using jBPM 4.0 taskforms and the jBPM console. So no integration with custom code today. We’ll start with a simple business process and enhance it with taskforms to ‘generate’ ourselves a basic but usable webapp.
Important: a taskform example is shipped with the jBPM 4.0 distribution. However, a code change just before the release invalidated the example which means that the official distribution doesn’t show how task forms should be used. The example in this post will replace the taskform example in the 4.1 release. So up till then, this is the only ‘semi-official’ taskform example
Also note that the shipped taskform integration is a first release. It doesn’t look very sexy for the moment, but we’ll definitely put some love in it in one of the next releases!
Prerequisites
You should have run the jBPM 4.0 ‘demo.setup’. This means that a working Eclipse 3.5 with GPD and a JBoss 5.0.0 AS server with the jBPM console is installed.
If not, please follow the documentation in the jBPM user guide.
You also should have a mail server running on port 25. The quickest way is to use my fake email server (based on Dumbster). Just run the jar as root (since you need to bind on a port lower than 1024):

Business process explained
In this tutorial, we’ll implement the same business process as in the official taskform example. The process starts when a vacation requestform is filled in. The manager will then either reject or accept the request and both outcomes trigger the sending of an e-mail to the employee that filled in the first form.

It is easy to see that this is an intranet application that any company can use, but it is significantly simplified for tutorial purposes.
The end result will look like this:
The real deal
Download the source of this process. This is a Maven2 based project. Just unzip it and import it into Eclipse (using m2Eclipse). The XML version of the process above looks like this:
<process name="taskformExample" xmlns="http://jbpm.org/4.0/jpdl">
<start form="be/jorambarrez/jbpm4/demo/taskform/request_vacation.ftl" name="start">
<transition to="verify_request"/>
</start>
<task candidate-users="peter,mary" form="be/jorambarrez/jbpm4/demo/taskform/verify_request.ftl" name="verify_request">
<transition name="accept" to="Send acceptance e-mail"/>
<transition name="reject" to="Send rejection e-mail"/>
</task>
<mail name="Send rejection e-mail">
<to addresses="${employee_email}"/>
<subject>Your vacation request has been rejected</subject>
<text>Your vacation request for ${number_of_days} has been rejected. Reason: ${reason}</text>
<transition to="vacation_rejected"/>
</mail>
<mail name="Send acceptance e-mail">
<to addresses="${employee_email}"/>
<subject>Your vacation request has been accepted</subject>
<text>Success: your vacation request for ${number_of_days} has been accepted.</text>
<transition to="vacation_accepted"/>
</mail>
<end name="vacation_rejected"/>
<end name="vacation_accepted"/>
</process>
Note that the process is started using the start form request_vacation.ftl. This is a simple HTML freemarker template which looks like this:
<html>
<body>
<form action="${form.action}" method="POST" enctype="multipart/form-data">
<h3>How many days would you like to go on vacation?</h3>
<select name="number_of_days">
<option value="3">3 days</option>
<option value="5">5 days</option>
<option value="10">10 days</option>
</select>
<br/>
<br/>
Your name: <input type="text" name="employee_name" /><br/>
Your email address: <input type="text" name="employee_email" /><br/>
<br/>
<br/>
<input type="submit" name="Done"/>
</form>
</body>
</html>
Every value of a form input (ie select, text input, etc.) will be added to the process instance as a process variable. In this example, the values number_of_days, employee_name and employee_email will be stored into the process instance as a process variable. This also works the other way around. In the second node, the manager must approve the vacation request, using the verify_request.ftl form. All the process variables stored in the process instance are available in the form (eg. number_of_days)
<form action="${form.action}" method="POST" enctype="multipart/form-data">
<h3>Your employee, ${employee_name} would like to go on vacation</h3>
Number of days: ${number_of_days}<br/>
<hr>
In case you reject, please provide a reason:<br/>
<input type="textarea" name="reason"/><br/>
<#list outcome.values as transition>
<input type="submit" name="outcome" value="${transition}">
</#list>
</form>
If you take a look at the process xml, you’ll see that these variable expressions are also usable for the e-mail that is sent afterwards:
<mail name="Send acceptance e-mail">
<to addresses="${employee_email}"/>
<subject>Your vacation request has been accepted</subject>
<text>Success: your vacation request for ${number_of_days}has been accepted.</text>
<transition to="vacation_accepted"/>
</mail>
Running the example
The example process now needs to be deployed to the database that is used by the jBPM console. An advanced way of deploying this process is shown in the example project, where the process is deployed through the remote EJB command service which is installed on the JBoss sever during the demo.setup. Typically, you’ll use the standard jBPM service API (ie the repositoryService and the executionService) instead of the command service directly. So this code is meant for power-users only
DeploymentImpl deployment = createDeployment(); RemoteCommandExecutor commandExecutor = retrieveCommandExecutor(); DeployCmd deployCmd = new DeployCmd(deployment); commandExecutor.execute(deployCmd);
Do note that during the creation of the deployment, you’ll need to add all the forms to the deployment. We’re looking into ways of simplifying this in a next release.
deployment.addResourceFromClasspath("be/jorambarrez/jbpm4/demo/taskform/process.jpdl.xml");
deployment.addResourceFromClasspath("be/jorambarrez/jbpm4/demo/taskform/process.png");
deployment.addResourceFromClasspath("be/jorambarrez/jbpm4/demo/taskform/verify_request.ftl");
deployment.addResourceFromClasspath("be/jorambarrez/jbpm4/demo/taskform/request_vacation.ftl");
Run the Main.java class and go to http://localhost:8080/jbpm-console. Log in as alex/password. Go to the Processes > Process Definitions > Definition List view. Our process will be added to the list of definitions (last one in the list):

Now, select the taskformExample-1 process. Click on the Process Instances tab and press Start. The start form will be displayed. Only when the form is submitted, a process instance will be created.
Click on Submit Query. Now log out the console and log in as Peter. If you’ve paid attention, you’ve seen that the Verify Request task can be done be Peter or Mary. Log in a Peter (with password = ‘password’) and go to the Tasks > Task Management > Task List view.

The task is currently unassigned (but Peter and Mary are candidates for the tasks). Click the Claim button to move this tasks to Peter’s personal tasks. Go to the Personal Tasks tab and click View. The second task form is shown:
Clicking accept or reject will cause the task to be completed. The process instance will move on and reach one of the mail nodes. The mail activity will be triggered, the mail server will receive the mail and the process instance ends and is removed from the database.

And that’s it. Your very first taskform-enabled business process! Any feedback on the taskforms or console is appreciated!
jBPM 4.0 released!
Yes, you are reading the title correct… just a few minutes ago we’ve pulled the curtains and released the next generation of our beloved framework in the wild.
I will repeat it once again for those whose jaw has fallen to the ground: jBPM 4.0 is released!
We’ve deliberately squeezed it out before the weekend, so that all of you can toy with it without having to think about work. So go get it while it’s still fresh.
More details can be found at Tom’s website:
http://processdevelopments.blogspot.com/2009/07/jbpm-40-is-out.html
Let’s get the party started!
Open source appreciation
When I started working on jBPM, there were two main reasons for doing it:
- It keeps you sharp (the whole world is looking at your code)
- It gives you a warm, fuzzy feeling inside
- It looks good on your resumé
Heck, I even got my current job because of it.
It is very difficult to explain to non-developers why someone would sacrifice precious spare time to do the same as what they’re doing during the day, but now for free. I believe however, that the main reason is developer-pride. Developers are show-offs who pridely want to show the world their skills. And perhaps to make it a better place, that too.
So when this week I got this plaque and t-shirt (the red stuff on the left) for the work I’ve done past year on jBPM, my developer-pride was fed huge time

I really must give kudos to JBoss for this (and I’m not saying this because its my current employer). It’s a small effort for them, but I’m sure many people hugely appreciate the gesture.
So, if you’re a developer and you’ve got some spare time, don’t hesitate and start your open-source adventure today. Preferably with JBoss (and jBPM) if I’d have something to say about it
jBPM4 Hello World
Update 1 feb 2010: hello world update for jBPM 4.3
As promised in my previous post, I’ll show you how easy it is to start using the new jBPM4 API.
I’ll use the mother of all demo’s and implement a process that prints ‘Hello World’ to the screen. One of the core strengths of jBPM has always been the embeddability in several environments (SE, Spring, EJB, etc), so today I’ll show how to create a SE application that uses jBPM as a regular library. I’m going to do the demo with the CR1 release, but the example should be quite protable to the 4.0GA release.
Download the (Maven) example here.
If you want to do it yourself, follow these steps:
- (non-Maven users): download the distribution and unzip it somewhere
- (non-Maven users): in Eclipse, add jbpm.jar the lib folder of the unzipped distribution to the project classpath.
(maven-users): create an empty maven project and add the following dependency to your pom.xml:
<dependency> <groupId>org.jbpm.jbpm4</groupId> <artifactId>jbpm-jpdl</artifactId> <version>4.0.CR1</version> </dependency>
- Now we’ll create the ‘logic’ of our process. Create a class called Printer :
package be.jorambarrez.jbpm4.helloworld;
public class Printer {
public void printHelloWorld() {
System.out.println("<---------------->");
System.out.println(" HELLO WORLD!");
System.out.println("<---------------->");
}
}
- Create the HelloWorld process. The process uses a Java activity here to call the ‘printHelloWorld’ method on our ‘business logic’.
<process name="helloWorld" xmlns="http://jbpm.org/4.0/jpdl"> <start> <transition to="printHelloWorld"/> </start> <java class="be.jorambarrez.jbpm4.helloworld.Printer" method="printHelloWorld" name="printHelloWorld"> <transition to="theEnd"/> </java> <end name="theEnd" /> </process>
which looks like this if you have installed the GPD:

For JPDL4, one of the main goals is process readability. If you take a look at this process or any of the shipped example processes, you’ll notice that this has worked out quite fine.
- Create a minimal jBPM config (jbpm.cfg.xml)
<jbpm-configuration> <import resource="jbpm.default.cfg.xml"/> <import resource="jbpm.tx.hibernate.cfg.xml"/> <import resource="jbpm.jpdl.cfg.xml"/> </jbpm-configuration>
The imports shown here contain a default configuration. If needed, you can remove the imports and configure jBPM for your own environment.
- Create a basic Hibernate config called jbpm.hibernate.cfg.xml(I’m using HSQLDB, but any DB supported by Hibernate will do):
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="hibernate.connection.url">jdbc:hsqldb:mem:.</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">create-drop</property> <mapping resource="jbpm.repository.hbm.xml" /> <mapping resource="jbpm.execution.hbm.xml" /> <mapping resource="jbpm.history.hbm.xml" /> <mapping resource="jbpm.task.hbm.xml" /> <mapping resource="jbpm.jpdl.hbm.xml" /> <mapping resource="jbpm.identity.hbm.xml" /> </session-factory> </hibernate-configuration>
Note: if you are using 4.0GA (instead of CR1), remove the ‘jbpm.jpdl.hbm.xml’ line from the hibernate mapping.
and add the correct driver to your classpath. With Maven and HSQLDB, add this dependency to your pom.xml.
<dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.7</version> </dependency>
- Finally, create a main method which constructs the ProcessEngine
ProcessEngine processEngine = new Configuration().setResource("my.jbpm.cfg.xml").buildProcessEngine();
and retrieve the needed services:
RepositoryService repositoryService = processEngine.getRepositoryService(); ExecutionService executionService = processEngine.getExecutionService();
which we can use to deploy our hello world process and start a process instance
repositoryService.createDeployment()
.addResourceFromClasspath("hello_world.jpdl.xml")
.deploy();
executionService.startProcessInstanceByKey("helloWorld");
After the Hibernate loading, you’ll see the Hello World message from the Printer class.
That’s it, your very first jBPM4 Hello World process. With this setup, you can start playing with the different activities or change the configuration. Do note how easy it is to embed this code into other environments (Spring, EJB, …) due to the fact that jBPM is ‘just another Java library’. Although the hello world process is extremely simple, all the setup around it (jBPM and Hibernate config) are exactly the same as for any arbitrary complex process.
Stay tuned for more posts about jBPM4!
jBPM4: What’s new (part 3)?
The new (rock-solid) service API
When making the transition from jBPM3 to jBPM4, the most remarkable change is probably the new service API.
In jBPM3, it was not always clear where to look for a certain operation. Some operations were found on the JbpmContext, or on the GraphSession, or on the TaskManagement interface, or yet some other class. So there definitely was an API, but the growth of jBPM both in Slocs and adoption in the past years have transformed it into a maze for many people who wanted to learn jBPM.
In jBPM4, the jBPM team has drastically moved away from these shackles of legacy and has chosen a simpler approach with a less steep learning curve: the service API. Every jBPM story (webapp, standalone, shared BPM server, etc.) starts with a ProcessEngine. As the name implies, the ProcessEngine is the key for doing the actual BPM stuff. But like the engine of your car, you need components to control and guide your engine (gears, brakes, etc) or the engine will do nothing. So basically what you’ll do is create a process engine from a given jBPM config (jbpm.cfg.xml) and acquire from it the services.

- RepositoryService: allows managing static process data: deploying process definitions, enable/disabling them, query them, etc.
- ExecutionService: exposes operations concerning the runtime executions (ie process instances and sub-executions): starting process instances, variable management, retrieving and deleting executions, etc.
- TaskService: this service will probably be used the most, since it gives access to the most crucial part of BPM, Human Interactions. Everything you ever wanted to do with human tasks is done through this service: creating tasks (ad-hoc is supported!), querying, assigning them, task completion, etc. You’ll notice that, in comparison with jBPM3, task management has been given a complete redesign which makes tasks easier to access, query and filter.
- HistoryService: in jBPM4, a clean separation has been made between the runtime and historical data. The previous services all had more or less something to do with active executions of a process, whereas the historyService is only concerned with things of the past. Through this service, historical data (such as completed process instances or executed activities) can be easily queried. This service also gives access to some statistical calculations which are done by the engine. There is no real prior component for this in jBPM3, so be sure to check it out!
- ManagementService: the last service is the one that’ll be used only by ‘management apps’ (eg the jBPM console). This services allows for example to query jobs and execute them (without the needing a job executor), but typically you’ll not use it in end-user software.
Note: the Query API which I discussed in part 2, is also accessible through these services.
The services are designed such that every practical jBPM use case is covered by it. All the API services are tested by us at our QA lab against several databases (HsqlDB, MySQL, PostgreSQL and Oracle for the moment, but we’ll expand this very soon), different Java versions (jdk 5 & 6) and JBoss AS versions. So when you use this new API, you can be sure it is stable as a mountain goat (is this a valid expression?).
But jBPM-power users shouln’t be afraid that this ‘easier’ jBPM API leads to less power. The service API is in fact an abstraction on top of the CommandService facade approach, which was already in the more recent versions of jBPM3. In fact, every service operations translates into a Command, which is executed in the well-known try-catch-finally block of jBPM. Take a look at the source of DefaultCommandService if you want to know more. You can easily retrieve the CommandService to get access to the full power of the jBPM engine:
processEngine.get(CommandService.class)
Power users will know what to do with it
Stay tuned for the next post, where I’ll show you how easy it is to create a Hello World process with jBPM4 and the service API.






