Thursday 19 April 2012

JMS with Spring configured in Java

Handling JMS using standard JMS API is a tedious task - you need to create a lot of boilerplate code.
Spring provides an abstraction layer that eases this pain.
In the following example I'm using ActiveMQ (which needs to be started before running any of the code below) but Spring works with other major JMS implementations as well.

In order to send a JMS message we can use JMS template. Here's our sender that's using it:


Spring beans needs to be configured in a context. Let's define Spring configuration in Java code:


JMS template must have a connection factory with a broker url and a destination (in our case it's a queue).
The XML configuration equivalent would look like:


Java configuration provides not only compile-time checking but in my opinion it is more straightforward and easier to control.
Unfortunately we can't escape XML completely, we need to turn on component scanning so that Spring will read configuration from classes in our package:


The example code that would run the sender:

Apart from the sender we can also create the receiver. One of the solutions is to make him asynchronous by implementing MessageListener interface.


The Spring config looks as follows:


Our receiver is set in the message listener container with the connection factory and the destination.
Receiver is missing the same XML configuration as sender, and the running code is analogical.

Here's the list of maven dependencies:

Monday 2 April 2012

Testing asynchronous calls with awaitility

Testing asynchronous systems is not an easy task. Let's take a simple example:


We have a class that creates file based on a given file name. The interesting thing is, that it does it asynchronously using a thread pool and returns immediately to the caller.

Let's try to create a test for it. Our first attempt could look like that:


The horrible thing about it is that Thread.sleep() invocation. Test should be fast, making them wait unnecessary is very poor solution. And what if the test sometimes fails because of overloaded hardware? Are we going to sleep even more?

To eliminate unneeded waiting, we may come up with a concept of validator:


We no longer need to sleep for a long time, but the code has been significantly polluted. Of course we can refactor our validator, make it more reusable but why reinvent the wheel? There is a nice and small library - awaitility - that will do the same for us.


In a very expressive way, we achieve the same result. Timeout, polling delay and polling interval are of course configurable.