Small steps with big feet
jBPM4 real-life example: The Train Ticket Demo (part 4: the end application)
The path from a business process model towards an automated business process implementation is often a long one. After the initial process modeling in the Signavio editor, the initial development and prototyping, it is now time to start the actual development of our Train Ticket handling platform.
In reality, development will be mixed with additional discussions between IT and business, enhancements and changes in the BPMN process model and definitely some addtional prototyping will be needed. Here it may look like an easy transition between our prototype and our eventual and application, but do keep in mind that this phase is the one were most often future failures are born. It is of extreme importance to keep in mind that a business process is The Holiest of Holy of a given company. Therefore, business process implementations must be as close as possible to what the business expects, and this often takes time to synchronise all stakeholders involved.
In this article, I’ll present the implementation of the business process as described in the previous articles. The end result will be a high-performant, scalable (by means of clustering) train ticket handling platform, using standard Java EE components. This article will also show how easy it is to integrate jBPM with any given Java tech. As described in my previous article, let jBPM enrich your architecture!
Of course, as a open source project we have a reputation to keep up. All of what we discussed in the previous articles and this article is contained in the download at the bottom of this article. Many people have asked me for the executable demo and so here it finally is! Like I said before, don’t hesitate to show this demo to all the people you know!
Architecture Overview
The following picture shows a high-level overview of the architecture.
Most of it is probably clear by just looking at it, but I’ll summarize what’s going on here:
- The entrypoint to the application is a regular HTTP servlet. SMS gateways communicate between telecom operators using plain HTTP messages, so the choice for this technology is obvious.
- We have a cellphone emulator (swing rich client), aka the jBPM-Phone, at the left side. This cellphone runs on my local machine and it sends text messages to our Ticket Handling Platform using the same HTTP messages used by the SMS gateway. This way, we can test our logic, without actually paying for the text message transfer.
- The Servlet parses the incoming text messages and offers this to the TicketService, depending on the type of the message (a message that starts a new process, or one that triggers the task in a waiting process instance). See line 9 and 16.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
...
if (isTicketRequestMessage(msgContent)) {
TicketRequest ticketRequest = parse(msgContent, sendDate, senderNr);
if (ticketRequest != null) {
ticketService.handleTicketRequest(ticketRequest);
} else if (isTicketAcceptanceMessage(msgContent)) {
String acceptanceId = parseTicketAcceptanceMessage(msgContent);
if (acceptanceId != null) {
ticketService.handleTicketAcceptance(acceptanceId, senderNr);
} else {
LOG.warn("SMS message content invalid. Throwing it away.");
}
}
}
- The TicketService is a stateless EJB3 service. The incoming message will be used to start a new process instance of our well-known ticket handling process (see previous articles if you haven’t the slighest clue). This means that the TicketService will actually call one of the jBPM API services, nothing more. Note how easy we have integrated jBPM with the EJB3. No magic involved: this is plain Java code, people. See line 16, 27 and 34 in particular.
@Remote(TicketService.class)
@Local(TicketService.class)
@Stateless
public class TicketServiceImpl implements TicketService {
... // field declarations
public void handleTicketRequest(TicketRequest ticketRequest) {
Map<String, Object> vars = new HashMap<String, Object>();
vars.put(ProcessVariable.FROM, ticketRequest.getFrom());
vars.put(ProcessVariable.TO, ticketRequest.getTo());
vars.put(ProcessVariable.CELL_NR, ticketRequest.getCellPhoneNr());
ProcessInstance processInstance = executionService.startProcessInstanceByKey(TICKET_PROCESS, vars);
if (LOG.isInfoEnabled()) {
LOG.info("Ticket Process with process instance id " + processInstance.getId() + " started");
}
}
public void handleTicketAcceptance(String acceptId, String cellPhoneNr) {
// Look up the task through the jBPM API
Task task = taskService.createTaskQuery()
.processInstanceId("ticketProcess." + acceptId)
.assignee(cellPhoneNr)
.uniqueResult();
if (task!= null) {
taskService.completeTask(task.getId());
if (LOG.isInfoEnabled()) {
LOG.info("Task " + task.getId() + " completed by " + cellPhoneNr);
}
}
}
}
There are two important notes here:
- The TicketService is a regular service, nothing special there. Here I’ve chosen for an EJB3 approach, but you can well imagine this to be a Spring service, where the jBPM services are injected into the service. The important part here is that the ticketService is a plain service, just like any other (CRUD) service in the application. See my article on “where does jBPM fit into my architecture”.
- I’m using standard JEE components (servlet and EJB3), in a complete stateless way. This means that this architecture can scale up linearly with any given load (eg with a simple load balancer). Also note that the use of jBPM does not imply any limitation on scaling this architecture. jBPM is designed from scratch with concurrent executions in mind, and synchronisation is actually done at the database level. Every API call is self-contained, on which node in the cluster it is executed.
Notice that there is an additional component on the picture: the user registration app. This is a simple Seam application, that just allows for users to register their cellphone and add money to their account. For the moment, adding money is just filling in the form, but I’m sure you can imagine this to be done by MasterCard, or any other payment method.
Use The Source, Luke
If you want to just download the demo, then just scroll down to the next section. If you want to check out the source however, then these instructions are for you.
Check out the source for the Rich client emulator from our public svn repo:
svn co http://anonsvn.jboss.org/repos/jbpm/projects/demos/trainticket-demo/jbpm-phone/trunk/ jbpm-phone
Building the emulator is really easy, just do a standard maven build:
mvn clean install
The executable jar can be found in the target subfolder and is called jBPM-Phone-1.0.jar
Check out the source for the jbpm-on-rails platform from our svn repo:
svn co http://anonsvn.jboss.org/repos/jbpm/projects/demos/trainticket-demo/jbpm-on-rails/trunk/ jbpm-on-rails
The project is structured as a Maven-multiple-module with the following modules:
- domain: contains the simple domain model of the ticket handling application: a TicketRequest, a User and a Quote
- jboss-integration: contains some classes that are used to integrate easily with the JBoss AS, like binding the ProcessEngine to JNDI.
- process-logic: this module has the most interesting classes. Here you’ll find the custom activities, Decision handler, event listeners, etc.
- ejb: EJB module which contains the TicketService implementation as described above. Also contains the QuoteService EJB3, which emulates the external service shown in the architectural overview.
- war: contains the described servlet that handles incoming text messages from customers
- ear: wraps the ejb jar and the war in an ear that is deployable on the JBoss AS.
Building the project is done by just doing a standard maven build
mvn clean install
The resulting ear can be found under /ear/target. This ear is tested on a JBoss AS 4.2.3. I’m using some JBoss-specific extensions, so don’t expect it to run on other containers.
Download the demo
The complete application: a JBoss server (4.2.3) with the user registration app and the ticket handling application, together with the Rich client emulator can be downloaded here (+- 237 MB).
Follow these steps:
- (this is the most intensive step) Go to $UNZIPPED_FOLDER/jboss-4.2.3.GA/server/default/deploy open up the jbpmeditor.war file with any zip utility and open the web.xml file. Look for the fileSystemRootDirectory and change the value to an existing foler on your own hard disk. Currently, the value is set to /home/jbarrez/Desktop/signavio-repository. Take care that the web.xml file is actually rewritten in the zip file (not all tools can do this).
- go to $UNZIPPED_FOLDER/jboss-4.2.3.GA/bin and start up the JBoss server (./run.sh on linux)
- go to $UNZIPPED_FOLDER/ and execute the jar: java -jar jBPM-Phone-1.0.jar
- open your browser and go to http://localhost:8080/user_registration. You can log in with the emulator userid using 123456789/password and add some money to the emulator’s account.
- Play around with the emulator. A ticket request is sent by typing ‘TICKET CITYA CITYB’.
Screencast
You can see how all this looks in reality by viewing the following screencast. In the movie, you’ll see how to use the emulator (aka the jBPM-phone), how to add some money to the emulator’s balance and how the ticket handling server communicates nicely with the jBPM-phone. All of what you see in this movie, can be done by yourself by downloading the demo!
Enjoy!
jBPM4 real-life example: The Train Ticket Demo (part 3: prototyping with the jBPM console)
Business processes are hard to get right from the first try. This is logical, since business processes are hard coded in the mind of the business people and pouring all this knowledge into a model is hard. So typically, it takes some iterations through the BPM lifecyle until a process model is derived that somewhat matches with what the business actually is doing.
So where are we now in the Train Ticket story? We’ve modeled our process and we added business-specific logic to the business process. We’re still in the development phase, according to the BPM lifecycle. But in these days, nobody will ever rush into development straight away at this point. Agility is all the buzz nowadays, and there is no reason why it shouldn’t be.
In this article I’ll show how you can leverage the jBPM console to build a prototype of the final application. Of course, the jBPM console can do a whole lot more than prototyping (like basic process governance, reporting, etc), we’ll come back to these topics later. For this article, we’ll only highlight the prototyping capabilitites of the jBPM console.
Using the taskform functionality of the jBPM console, it is very easy to emulate user input and output without investing a lot of valuable development time. The use of these taskforms will allow you to show the interaction with the business process from the viewpoint of the end-user. It enables discussions between business and development, without actually building a complete application from scratch.
Agility in its purest form, who doesn’t love that?
Enriching the business process with taskforms
In a previous article, I already explained how to add a taskform to a business process. A task form is a HTML form which we can specify in the JPDL process definition, that captures the I/O towards and from the end-user. We’ll do the same here for the train ticket process, which is shown here again as reference:
There are 2 points of input/output in the process:
- The process is started when a cellphone text message is arrived. This text message contains the start and destination train stations.
- Once a price quote for the itinerary is calculated and the credit balance of the customer is verified, a text message is sent back with the price quote. An acceptance task is created for the customer. When the customer sends an acceptance message back, the process is continued by completing the task.
Whenever a process instance is started through the jBPM console, the ‘start’ activity is checked to have a start form. This form will be displayed before starting a process instance and the input variables of the form will be stored in the process instance so they can be used later on.
To attach a start form to a process definition, the start activity must be enhanced with a form attribute:
<start form="org/jbpm/trainticketdemo/trainticket_startform.ftl" g="11,105,48,48" name="start"> <transition to="Calculate quote"/> </start>
As shown in this snippet, the form is stored as a .ftl file somewhere in the project package tree. This file contains a basic HTML form and input text fields. Remember, the values of these input fields are later used as process variables.
<html>
<body>
<form action="${form.action}" method="POST" enctype="multipart/form-data">
<h3>Send SMS:</h3>
<table>
<tr>
<td>From:</td>
<td><input type="text" name="from" /></td>
</tr>
<tr>
<td>To:</td>
<td><input type="text" name="to" /></td>
</tr>
<tr>
<td>Source cellphone nr:</td>
<td><input type="text" name="cellPhoneNr" value="" /></td>
</tr>
</table>
<input type="submit" name="Send"/>
</form>
</body>
</html>
Filling in this form will store the from, to and cellPhoneNr variable in the process instance as a process variable.
Adding a taskform to the ‘accept quote’ task is done in exactly the same way:
<task assignee="#{cellPhoneNr}" form="org/jbpm/trainticketdemo/accept_quote.ftl" ...
In our final application, a text message will be sent to the customer before arriving in the acceptance task. In the jBPM console, we can emulate this behavior by using the taskform to display process information. Note the usage of expressions ${} to output process variables in the html taskform.
<html>
<body>
<form action="${form.action}" method="POST" enctype="multipart/form-data">
<h3>Accept Quote:</h3>
<table>
<tr>
<td>From:</td>
<td>${from}</td>
</tr>
<tr>
<td>To:</td>
<td>${to}</td>
</tr>
<tr>
<td>Price:</td>
<td><b>${quote.price}</b></td>
</tr>
</table>
<input type="submit" name="Accept"/>
</form>
</body>
</html>
Taskforms in action
That’s all there is to it. Just enrich your JPDL process definitions with some taskforms and deploy them to the jBPM database. Don’t forget to add them to the deployment next to the process definition xml by calling the deployment.addResourceFromClasspath(“org/jbpm/…”) operation.
The following screencast shows the end result of this iteration: a protoype of the application using the jBPM console and the taskform functionality.
What’s next?
In the next article, we’ll finally be able to build the real application.
Stay tuned!
(j)BPM: where does it fit architecturally?
“How does jBPM fit into my architecture?“
This question pops up regularly in my mailbox or on the jBPM user forum. Even when I was still a jBPM consultant, this question was the first line new customers asked me.
But there is no ‘all-in-one’ answer to this question. Like many answers in IT, the real answer is ‘it depends’. It depends on which frameworks you selected already. It depends on the expected load of the business processes. It depends on the existing systems which need to be accessed in the process. It depends if you want to centralize BPM knowledge in one application or not. And so on and so on …
jBPM is extremely flexible since our key feature is being embeddable in any Java technology out there. Pick your favorite framework, and I’m sure there is a way to fit in jBPM. But it’s the very same embeddability that often causes people architectural headaches. Mis- or underinformed people often want to take the easy path, and big BPM vendors know this.
A well-dressed sales guy will give a smooth presentation with colorful charts and he will promise you heaven and more. Of course, before acquiring the BPM system, you must first put (a lot of) cash on the table. That’s the way the world turns, right? And what are you getting: a big black-box server. You can send requests to it and it magically gives you the answer (hopefully it is the right one), hence the developer in the picture below that is painting on his screen. Paintings tend to look good from a distance, but you know that once you get close it tends to get blurry.
Big black-box servers don’t give you architectural headaches. No, on the contrary: they define how your architecture should look…
It could be me, but I like to keep things under control. I like to see what’s happening in my architecture, how it all fits together and which systems are communicating with each othe.. You know, that warm, fuzzy feeling you get once your own designed architecture keeps up with every load you throw at it. jBPM just gives you that openness en flexibility you need to build an architecture suited for your business, without having to suit your business to an architecture implied by a big black-box system.
Since jBPM is at its core just a simple Java library, there is no limitation on how you want to include it into your architecture. I’ll list a few of them here, but remember that jBPM will never be the limiting factor when designing your architecture. However, I do have my own ideas and experience. So, there is a definition I tend to use when people ask me about jBPM and architectures:
A business process *is* a part of the domain model, so ideally BPM should be non-intrusive and integratable with *every* architecture and technology. So let me reverse the question now: how does your domain model fit into your architecture?
Many people don’t see a business process as part of the domain model (remember my black-box story …), but it makes a lot of sense if you think about it. What is a domain model? Well, it is a representation of your business domain, of the raison d’être of your business of company. What is a business process? Well … it is a representation of how your business does something to create value. It is a representation of domain objects communication in some fixed way (a ‘flow’) to create some business-specific value.
So what does this mean in practice? It means that concepts like a Task (eg ‘send inquiry’), a Process Instance (a ticket sale) or an actor are at the same conceptual level as the domain model. Do note it doesn’t mean to scatter around your logic (like custom activitities, service invocations, etc.). Best practices in architecture design do still apply, and even more with jBPM (since they are applicable without restriction).
So by now I hope you can understand why we at jBPM don’t like the black-box-magical-server approach. A domain model is often scattered around many architectural layers or applications. Nobody asks questions when a domain object tends to be used accross different layers, and it is the same for the business process. If it makes sense in your architecture to not centralize a business process, then do it. It will make your architecture more understandable and easier.
Like I said, this means you can use jBPM in a lot of architectural styles:
- In some designs, a BPM layer is placed either above a service layer – I like to call this a scenario layer
- jBPM code is often wrapped the same way as a DAO (where I most of the times use the term PAO (Process Access Object). Services make calls to the PAO’s, just like they are accessing domain objects through the DAO’s. In a Spring environment, this is a true and tested approach.
- Or you could build a big centralized server that does only BPM operations. This looks very much like the black-box servers I mentioned before. In some architectures this makes sense (eg tax processing split over several clusters), but you now don’t get a black-box server, but an open system that shows you all its internals. No magic involved. If you want to wrap it in WS-*, REST or whatever gets you going, fine. You don’t get that kind of choice with typical BPM products.
- …
I’m sure that if you searched our user forum, you could triple this list in a few minutes.
Conclusion
This article is a bit of a side track in my current ‘jBPM4 real-life example: The Train Ticket Demo’ saga, but you’ll see that my ideas of this article are applied in the eventual Train Ticket Application (ie ‘jBPM on Rails’). Architecture designs tend to get a lot simpler if you look at BPM as part of the business domain. And jBPM just gives you that kind of control: flexibility and embeddability in any Java technlogy.
So, let BPM enrich your architecture, not cripple it.Use jBPM and free your architecture today!
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!











