Activiti – are you ready for BPMN 2.0?

From the beginning of this year I got quite involved in project called Activiti. It’s a “light-weight workflow and Business Process Management (BPM) Platform” (according to creators. The project is led by JBPM creators – Tom Bayens and Joram Barrez and is backed by Alfresco and several other companies. I also contributed some small features :) Activiti has already made some noise in BPM world – check thisthisor this, and of course InfoQ.
So, what’s the fuss all about? What makes Activiti special? Of course – it depends what are you comparing it with. My experience involves mainly working with open source BPEL implementation, but I think some points remain valid.

So, here is my list of distinctive features:

BPMN 2.0 support I took quite a lot of time for this spec to arrive, but it’s finally here. The biggest step ahead comparing with BPMN 1.x is execution model – no more BPEL, you can use the same diagram for modelling and execution, and it has proper xsd schema! Of course, it won’t solve all round-trip headaches, but I think it’s quite important improvement. XML describing BPMN 2.0 process consists of nodes definitions and transition definitions: Activiti is one of the first BPM engines offering BPMN 2.0 support. Currently not all nodes are supported, but the list includes:
* exclusive and paralell gateways  

  • timer boundary and intermediate events (timer start event almost ready)    

  • various tasks: script, user, service, manual, rules, receive    

  • error events and handling them    

  • subprocesses (both embedded or not)     Not all of these nodes are fully defined in spec – e.g. it does not describe how service task invocation should look like. Therefore, Activiti comes with a set of custom extensions. They are meant to be as non-intrusive as possible – to make processes more portable. One of most commonly used are ones for describing service task behaviour: Another useful extension enables to associate html form and candidate user with user task: One of nice features of BPMN 2.0 is also providing xml schema for describing process diagram – aka Diagram Interchange. This enables good engines (such as Activiti ;)) to generate process diagram just on the basis of xml definition – which makes importing processes modelled in some external tool much easier. It looks like this: Maybe not too beautiful, but usable.

Goal of supporting full BPM cycle

Do you (still) believe that future tools for creating business processes will allow users to get rid of developers? I do not… Unless of course, business people will learn how to code ;) Otherwise what we’ll be left with are some nice zero-coding tools which look great on 15minutes (or event 2hours if they’re exprensive enough) but after running into real-life problems will demand extensive hacking.
Activiti pursues different goal, and proposes developing process cycle layer. Key points of this proposition are:

  • zero coding solutions won’t work
  • analysts are needed to model the process, developers are needed to create executable processes, and operations are needed to deploy and monitor them
  • each of these groups have their own set of tools which they’re familiar with
  • so let’s not reinvent the wheel but encourage them to collaborate but use their set of tools

So, how to achieve this? By creating another web application, of course ;) It’s name is Activiti Cycle and it’s meant to encourage collaboration between business, developers and operations, while allowing each of them to use their own, specific tools in their daily job. It’s more like a federated repository of BPM assets, such as Visio Diagrams, BPMN process definitions, maven process projects, deployment packages and so on. These artifacts can be linked, commented and tracked by various process stakeholders and also transformed.

Easy to embed and extend, also by quasi-REST API

One of biggest pains of BPEL based solutions is that they force you to integrate with the rest of you app using webservices. Fortunately, this is no longer the case. You can embed activiti engine in your (for example) Spring application just by importing few jars and configuring it as any other Spring component:
This is of course great for running processes that handle some Java tasks. What about user tasks? Activiti comes with decent webapps for handling human tasks and monitoring process state: Activiti Explorer – screens shows the list of tasks for a given user:  

Activiti Probe – screen shows monitoring process instance:  

But what if you want to/have to use some other frontend technology? Webapps that I mentioned before are really thin clients – all logic is hidden behind Activiti’s quasi-REST API (I use the word quasi not to be beaten by RESTafarians who will surely point out that Activiti API is just RPC over HTTP…). That means you can embed Activiti in you webapps/OSGi container/any other environment and integrate with frontend webapps using handy JSON/HTTP communication. Which looks more or less like this:

Using (defacto) standards When you create application using Activiti chances are high that you know many (if not all) building blocks & techniques:

  • development? Eclipse plugin & maven
  • connecting components together? you can choose: spring or (for JEE6 lovers) CDI
  • testing? just do your normal TDD (you do it, right? ;)) using Activiti JUnit testing utils

Eclipse plugin includes visual modeler, which enables you to draw executable BPMN 2.0 processes, and fill all needed properties:

It uses Diagram Interchange format, so process diagram layout will remain the same when displaying process diagram in other applications. Testing is also pretty easy, as Activiti comes with good JUnit support. One of small, but important features is ability to simulate the clock – very handy when dealing with long running tasks.

Good integration capabilities

Activiti comes with capabilities allowing for integration with three most popular open source integration frameworks:

  • Mule ESB – integration is written by MuleSoft
  • SpringIntegration, contributed by SpringSource
  • last but cetainly not least: Apache Camel – which is contributed by TouK ;) – it’s still work in progress, but I hope to write a blog post soon about integrating Camel & Activiti

This allows to build processes that are closer to orchestration than simple workflows, containing only (or mostly) human tasks. Each of these integration frameworks comes with a vast collection of adapters using all popular (and not so popular) communication protocols. This allows process engine to concentrate on the process, and not on the communication details.

Summary I think it’s quite impressive set of features for a product that is less than year old. And what are Activiti plans for the future? Tom Bayens recently announced that Activiti is going to support some sort of Adaptive Case Management – which is one of top buzzwords in process world. Other goals include:

  • asynchronous continuations
  • moving towards full support of BPMN 2.0
  • extending Activiti Cycle – check Bernd’s Ruecker screencast showing Activiti Cycle approach to handling collaboration between analysts, developers and admins – it’s quite impressive

As for me, I’m finishing adding support for start timer tasks and hope to post something on Activiti-Camel intergration and running Activiti in OSGi environment soon – especially Apache Servicemix – so stay tuned. If you’ve found Activiti interesting, please start with 10 minutes 

Getting started guide, and if you know Polish, you can also have a look at my slides from Warsaw JUG presentation Thanks for reading my first post on this blog – hope you liked it.

You May Also Like

How to use mocks in controller tests

Even since I started to write tests for my Grails application I couldn't find many articles on using mocks. Everyone is talking about tests and TDD but if you search for it there isn't many articles.

Today I want to share with you a test with mocks for a simple and complete scenario. I have a simple application that can fetch Twitter tweets and present it to user. I use REST service and I use GET to fetch tweets by id like this: http://api.twitter.com/1/statuses/show/236024636775735296.json. You can copy and paste it into your browser to see a result.

My application uses Grails 2.1 with spock-0.6 for tests. I have TwitterReaderService that fetches tweets by id, then I parse a response into my Tweet class.


class TwitterReaderService {
Tweet readTweet(String id) throws TwitterError {
try {
String jsonBody = callTwitter(id)
Tweet parsedTweet = parseBody(jsonBody)
return parsedTweet
} catch (Throwable t) {
throw new TwitterError(t)
}
}

private String callTwitter(String id) {
// TODO: implementation
}

private Tweet parseBody(String jsonBody) {
// TODO: implementation
}
}

class Tweet {
String id
String userId
String username
String text
Date createdAt
}

class TwitterError extends RuntimeException {}

TwitterController plays main part here. Users call show action along with id of a tweet. This action is my subject under test. I've implemented some basic functionality. It's easier to focus on it while writing tests.


class TwitterController {
def twitterReaderService

def index() {
}

def show() {
Tweet tweet = twitterReaderService.readTweet(params.id)
if (tweet == null) {
flash.message = 'Tweet not found'
redirect(action: 'index')
return
}

[tweet: tweet]
}
}

Let's start writing a test from scratch. Most important thing here is that I use mock for my TwitterReaderService. I do not construct new TwitterReaderService(), because in this test I test only TwitterController. I am not interested in injected service. I know how this service is supposed to work and I am not interested in internals. So before every test I inject a twitterReaderServiceMock into controller:


import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(TwitterController)
class TwitterControllerSpec extends Specification {
TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)

def setup() {
controller.twitterReaderService = twitterReaderServiceMock
}
}

Now it's time to think what scenarios I need to test. This line from TwitterReaderService is the most important:


Tweet readTweet(String id) throws TwitterError

You must think of this method like a black box right now. You know nothing of internals from controller's point of view. You're only interested what can be returned for you:

  • a TwitterError can be thrown
  • null can be returned
  • Tweet instance can be returned

This list is your test blueprint. Now answer a simple question for each element: "What do I want my controller to do in this situation?" and you have plan test:

  • show action should redirect to index if TwitterError is thrown and inform about error
  • show action should redirect to index and inform if tweet is not found
  • show action should show found tweet

That was easy and straightforward! And now is the best part: we use twitterReaderServiceMock to mock each of these three scenarios!

In Spock there is a good documentation about interaction with mocks. You declare what methods are called, how many times, what parameters are given and what should be returned. Remember a black box? Mock is your black box with detailed instruction, e.g.: I expect you that if receive exactly one call to readTweet with parameter '1' then you should throw me a TwitterError. Rephrase this sentence out loud and look at this:


1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }

This is a valid interaction definition on mock! It's that easy! Here is a complete test that fails for now:


import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(TwitterController)
class TwitterControllerSpec extends Specification {
TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)

def setup() {
controller.twitterReaderService = twitterReaderServiceMock
}

def "show should redirect to index if TwitterError is thrown"() {
given:
controller.params.id = '1'
when:
controller.show()
then:
1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }
0 * _._
flash.message == 'There was an error on fetching your tweet'
response.redirectUrl == '/twitter/index'
}
}

| Failure: show should redirect to index if TwitterError is thrown(pl.refaktor.twitter.TwitterControllerSpec)
| pl.refaktor.twitter.TwitterError
at pl.refaktor.twitter.TwitterControllerSpec.show should redirect to index if TwitterError is thrown_closure1(TwitterControllerSpec.groovy:29)

You may notice 0 * _._ notation. It says: I don't want any other mocks or any other methods called. Fail this test if something is called! It's a good practice to ensure that there are no more interactions than you want.

Ok, now I need to implement controller logic to handle TwitterError.


class TwitterController {

def twitterReaderService

def index() {
}

def show() {
Tweet tweet

try {
tweet = twitterReaderService.readTweet(params.id)
} catch (TwitterError e) {
log.error(e)
flash.message = 'There was an error on fetching your tweet'
redirect(action: 'index')
return
}

[tweet: tweet]
}
}

My tests passes! We have two scenarios left. Rule stays the same: TwitterReaderService returns something and we test against it. So this line is the heart of each test, change only returned values after >>:


1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }

Here is a complete test for three scenarios and controller that passes it.


import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(TwitterController)
class TwitterControllerSpec extends Specification {

TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)

def setup() {
controller.twitterReaderService = twitterReaderServiceMock
}

def "show should redirect to index if TwitterError is thrown"() {
given:
controller.params.id = '1'
when:
controller.show()
then:
1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }
0 * _._
flash.message == 'There was an error on fetching your tweet'
response.redirectUrl == '/twitter/index'
}

def "show should inform about not found tweet"() {
given:
controller.params.id = '1'
when:
controller.show()
then:
1 * twitterReaderServiceMock.readTweet('1') >> null
0 * _._
flash.message == 'Tweet not found'
response.redirectUrl == '/twitter/index'
}


def "show should show found tweet"() {
given:
controller.params.id = '1'
when:
controller.show()
then:
1 * twitterReaderServiceMock.readTweet('1') >> new Tweet()
0 * _._
flash.message == null
response.status == 200
}
}

class TwitterController {

def twitterReaderService

def index() {
}

def show() {
Tweet tweet

try {
tweet = twitterReaderService.readTweet(params.id)
} catch (TwitterError e) {
log.error(e)
flash.message = 'There was an error on fetching your tweet'
redirect(action: 'index')
return
}

if (tweet == null) {
flash.message = 'Tweet not found'
redirect(action: 'index')
return
}

[tweet: tweet]
}
}

The most important thing here is that we've tested controller-service interaction without logic implementation in service! That's why mock technique is so useful. It decouples your dependencies and let you focus on exactly one subject under test. Happy testing!