martes, octubre 25, 2011

Soy el rey de la mar tiburón Que te come a besos Pero yo soy el rey del mar tiburón El que te come mi amor (El Rey Tiburón - Maná))

Today I was googling about mocking when I have found next question:

"Injecting mock beans into spring context for testing. What I want to be able to do is via the HotswappableTargetSource override the bean definitions of select beans in my application context with my test versions and then run the test.
Then for each test case I'd like to specify which beans I want to be hot swappable and then each test must be able to create its own mock versions and swap those in, and be able to swap back again."

And there you can find a solution using ProxyFactoryBean and HotSwappableTargetSource. Well it is a solution for me a bit complicated, if I should do the same I would do using StaticApplicationContext class, because from my point of view, environment is more controlled and easy to understand. Of course the easiest solution is using Spring 3.1 Profile feature, but meanwhile it is a milestone/RC or simply because you will not be able to change Spring version, I will show you how to use StaticApplicationContext and how to inject mocked beans.

StaticApplicationContext is an implementation of ApplicationContext interface which supports programmatic registration of beans and messages, rather than reading bean definitions from external configuration sources. StaticApplicationContext has been created mainly for testing purpose. To solve the problem  we focus, some of registered beans will be the "real" beans, but others will be mocked beans with all their interactions.

For this example Mockito has been used. Let's see some code.

Imagine you have an application that should create users into a database. I suppose we would have a UserDao class for communicating with database and a UserService class to aggregate user operations. Moreover UserService class would not be alone, would be used in several modules; in fact all modules that requires user information.

Now it is time for testing. Unit test is simple, when you want to test UserService you set a mock of UserDao. Here no problem with Spring because it has not started to play yet.

But when you want to test whole system, may be you want that low-level classes like UserDao be mocked and also you want to run tests with Spring capabilities (for example developed BeanPostProcessors, Messaging, Spring AOP, ...). For solving this case you can create a test Spring context file, then you can create required mocks and set them manually. But as you can suppose another approach is using StaticApplicationContext.

The most important line is number 12 where we are injecting UserDao mock into Spring context. See that at line 11 we are also registering autowired annotation post processor. If  it was not registered, classes annotated with @Autowired would not work.

In current post I have explained how to inject mock beans into Spring Context for testing. Personally I don't like mixing mock beans with real beans in integration tests, I prefer only real beans in this kind of tests; but I can understand that in big modules where a system has multiple subsystems can be useful to isolate some modules from test. 

For example in my department we are developing clinical instruments which as you can imagine contains complex modules all related between them. When we are running some integration test, we are not available to connect to device, so communication module could be mocked. But in our case we are running integration tests with an emulator, but mocking some parts of our system could be another solution.

The example in this case is so simple I know, but in more complex scenarios you can create an application context referencing to real beans and passing it to StaticApplicationContext constructor so in static application context you only register mock beans.

This this would look:

Well now I have showed you how to register mock beans into a Spring Application Context using StaticApplicationContext instead of using HotSwappableTargetSource

Thank you very much for reading my blog.

Download Code.


lunes, octubre 17, 2011

Una terra promessa Un mondo diverso Dove crescere i nostri pensieri Noi non ci fermeremo Non ci stancheremo di cercare Il nostro camino (Terra Promessa - Eros Ramazzotti)


The essence of the Observer Pattern is to "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." GoF. Observer pattern is a subset of publish/subscribe pattern which allows a number of observer objects to see an event. 

This pattern can be used in different situations, but in summary we can say that Observer pattern can be applied when an object should be able to notify messages to other objects, and you don't want these objects  being tightly coupled. In my case I have used this pattern when an asynchronous event should be notified to one or more graphical component.

This pattern can be implemented using an adhoc solution or using java.util.Observer/Observable classes. But my projects are always developed with Spring whether they are web or desktop applications. So in current post I will explain how I implement Observer pattern with Spring.


Event handling in Spring ApplicationContext is provided through ApplicationEvent class and ApplicationListener interface. If a bean that implements ApplicationListener interface is deployed into the context, every time an ApplicationEvent is published to container, ApplicationListener receives it.

Spring comes with built-in events, like ContextStartedEvent, ContextStoppedEvent, but you can also create your own custom events.

For developing your own events, three classes are required, observer role, observable role and the event. Observers are those who receive events and must implement ApplicationListener class. Observable classes are responsible of publishing events and must implement ApplicationEventPublisherAware. Finally event class has to extend ApplicationEvent.


What I am going to implement is wikipedia example of Observer pattern ( but using Spring Events instead of Observer/Observable Java classes. The example is a basic publish/subscribe example where one String message is sent from one module to another one.

Let's create MessageEvent. This event contains a String that represents the message we want to send. It is a simple class that extends from ApplicationEvent.

Next class is the Observable class. This class must implements ApplicationEventPublisherAware. This interface defines a setter method with ApplicationEventPublisher as parameter. This parameter is used for publishing events.

In current implementation see that also implements Runnable interface so user can create from console input, asynchronous messages. Most important line is 26 where an event is created and published.

The Observer class is even simpler. Implements ApplicationListener interface. Method onApplicationEvent is called when an event is published. See that it is a generic interface, so no cast is required. This differs from java.util.Observer class.

In application context file, you register both ApplicationListener and ApplicationEventPublisherAware beans.

And finally a main class to test the system. A thread is created to execute multiple asynchronous events. 

So start the program and write something to console. You will see something like:

MessageEvent [message=hello]

I have entered "hello" message and thread name of event publisher is printed. Then event is sent and handler thread name is printed too. Finally the received event is shown. There is one thing that should call your attention. Both sender (Observable) and receiver (Observer) are executed in same thread; by default event listeners receive events synchronously. This means that publishEvent() method, blocks until all listeners have finished processing the event. This approach has many advantages (for example reusing transaction contexts, ...), but in some cases you will prefer that each event is executed in new thread, Spring also supports this strategy.

In Spring, class responsible of managing events is SimpleApplicationEventMulticaster. This class multicasts all events to all registered listeners, leaving it up to the listeners to ignore events that they are not interested in. Default behaviour is that all listeners are invoked in calling thread. 

Now I am going to explain how Spring Event Architecture is initialized and how you can modify. By default when ApplicationContext is started up, it calls initApplicationEventMulticaster method. This method verify if exists a bean with id applicationEventMulticaster of type ApplicationEventMulticaster. If it is the case defined ApplicationEventMulticaster is used, if not a new SimpleApplicationEventMulticaster with default configuration is created.

SimpleApplicationEventMulticaster has a setTaskExecutor which can be used for specifying which java.util.concurrent.Executor will execute events. So if you want that each event is executed in a different thread, a good approach would be using a ThreadPoolExecutor. As explained in last paragraph, now we must explicitly define SimpleApplicationEventMulticaster instead of using default ones. Let's implement:

First of all SimpleApplicationEventMulticaster must be defined as a bean with id applicationEventMulticaster. Then task pool is set, and we rerun our main class. And output will be:

MessageEvent [message=hello]

Note that now sender and receiver thread is different.

And of course you can create your own ApplicationEventMulticaster for more complex operations. You just have to implement ApplicationEventMulticaster and defining it with applicationEventMulticaster bean name, and events will be executed depending on your own strategy.

Hope that now your Spring desktop applications can take full advantage of Spring events for separating modules.


martes, octubre 11, 2011

You're so sexy sex sex sexy. Feel me now and stop the conversation. No, no, no don't stop the desire no, No, no, no, no! (Sexy - French Affair)


In current post I am going to explain how to implement and register a custom Spring MVC HttpMessageConverter object. Specifically a converter that binds objects to Yaml protocol. As starting point I am going to use the Rest application I implemented in previous post. That application is a simple Restful application where XML and JSON (Spring MVC already support them) are used. Because Spring MVC does not implement YamlMessageConverter, I am going to explain how to transform previous application from supporting XML and JSON to support Yaml.

Yaml is a human-readable data serialization format that takes concepts from programming languages such as C, Perl, and Python, and ideas from XML and the data format of electronic mail (RFC 2822).

SnakeYAML  is a YAML parser and emitter for the Java programming language, and will be used to implement our message converter.


Let's start with a UML class diagram of HttpMessageConverter that are going to be implemented.

HttpMessageConverter is a base interface that must be implemented. It is a strategy interface that specifies methods to convert objects from and to HTTP requests and responses. AbstractHttpMessageConverter is the abstract base class for most HttpMessageConverter implementation (both provided by springframework), and is our base class.

First developed class is an abstract class called AbstractYamlHttpMessageConverter. This class is responsible of generic operations that "should" be required by all Yaml parsers/emitters. In my case it deals with charset options, and transforms HttpInputMessage and HttpOutputMessage to and In fact it acts as a Template Pattern to read and write operations (readInternal and writeInternal methods).

Next abstract class is AbstractSnakeYamlHttpMessageConverter. This class is a base class for HttpMessageConverters that use SnakeYaml as Yaml binder. This class gets an instance of Yaml class (central class of SnakeYaml project).

And finally JavaBeanSnakeYamlHttpMessageConverter. This class uses SnakeYaml JavaBeans features for converting from object to Yaml and viceversa. SnakeYaml does not support annotations like Jackson (JSON) or Jaxb (XML), but if some day this feature is implemented, we should create a new class extending from AbstractSnakeYamlHttpMessageConverter with required change.


First of all is adding a new dependency to pom. In this case SnakeYaml.

Then three classes previously exposed should be developed.

First class is a generic Yaml converter where we are setting accepted media type, in this case application/yaml, and creating a Reader and Writer with required Charset. We are leaving to children classes the responsibility of implementing read and write code.

Next class is specific of API that will be used to bind classes to messages, in this case SnakeYaml. This class will be responsible of creating an instance of Yaml class (from SnakeYaml). As is warned in each thread must have its own instance; for this reason a ThreadLocal is used to carry out this restriction.

Final class is an implementation of read/write methods using SnakeYaml. As I have explained previously this class has a meaning because allows us changing SnakeYaml binding strategy (for example to annotation approach) and only worries to rewrite read/write operations.

Now it is time to register created message converter to AnnotationMethodHandlerAdapter. First thing you should do is not to use <mvc:annotation-driven>. This annotation registers default message converters and you are not able to modify them. So first step is comment or remove annotation-driven. Next step is declare DefaultAnnotationHandlerMapping bean and AnnotationMethodHandlerAdapter which registers http message converters. In our case only Yaml http message converter is added.


And now you can try application. Deploy it on a server, and using for example Rest Client, try http://localhost:8080/RestServer/characters/1 and you will receive a response like:

If you want you can use POST instead of GET to insert a new Character to our Map.

As you can see developing a Spring MVC HTTP Message Converter is so easy, in fact you must implement two basic operations, when a resource can be read or written and resource conversion.

Hope you found this post useful.

martes, octubre 04, 2011

Can't you see, It all makes perfect sense, Express in dollars and cents, Pounds shillings and pents, Can't you see, It all makes perfect sense (Perfect Sense Part II - Roger Waters)


From Wikipedia: REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed.

As you have read the most important thing in Rest architecture is the existance of a resource. This resource  can be anything (typically required information requested by client) that can be identified with a global identifier (URI in case of HTTP). In order to manipulate these resources, client communicates using standard interfaces (like HTTP) and exchange representations of these resources (using HTML, XML, ...).

Note that Rest does not force you to use any specific network protocol nor how resources are identified.

For those who have never read about Rest this description of Rest architecture could seem something strange and bit complicated. 

A RESTful web service is a simple web service implemented using HTTP and the principles of REST. URI is defined as global identified, communication interface is HTTP and resource representation can be any valid Internet media type like JSON, XML or YAML. The set of operations that can be executed to resources depend on HTTP Methods and are (GET - retrieving/listing, PUT - replacing/updating, POST - creating and DELETE - deleting).


Let's create our first Rest application with help of Spring MVC. Imagine an application that has a database of manga characters, and you want to provide a Rest interface so clients can retrieve characters following a RESTful strategy.

First thing to do is identify the resource. In this case it is easy, "a character". Next step is finding a URI that determines unequivocally a character. Easy too de facto rule can be applied here. This rule suggests that a unique URI can be <host>/<applicationname>/<resourceName>s/<id> in our case to return (GET) character with id 1 the URI would be "http://localhost:8080/RestServer/characters/1". If no identifier is present all characters should be retrieved. If instead of GET, POST is used, a character with id "1" would be inserted. And finally decide which Internet media type is required, in this case doesn't matter because we are implementing both client and server so initially XML will be used.


Let's start with a simple Spring MVC application created with Spring MVC template. Not much secret here, you will have a servlet-context.xml where component-scan, annotation-driven and InternalResourceViewResolver are registered.

Next step is defining Character class. A simple POJO with four attributes. Class is converted to its XML representation using Jaxb annotation.  Jaxb allows developers to map Java classes to XML representations and viceversa.

And finally the most important class in Spring MVC, "The Controller". Controller will be the responsible of implementing required operations of Character resource. In current case only GET is implemented, the other operations would be similar. Let's see the code:

First part is a map where all characters are stored. I have used this approach to not focus in data access. Then findCharacter method that is called when URI is /characters/{characterId}. This is a URI template and is a URI-like string, containing one or more variable names, which can be accessed using @PathVariable annotation. So when you are accessing to /characters/1 parameter characterId is bound to 1.

Last important part is @ResponseBody annotation. This annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body, and not placed in a Model, or interpreted as a view name as standard behaviour of Spring MVC. So findCharacter method returns a Character object.

And that's all if you execute this code, and for example you enter URI http://localhost:8080/RestServer/characters/1 the output (using RestClient UI) will be:

And now is when you are wondering, ¿If I am returning a Character object and output is a XML, where is conversion between object and XML? So easy, let me introduce a new concept: HttpMessageConverters. HttpMessageConverter is responsible for converting from HTTP request message to an object and converting from an object to HTTP response body. Next HttpMessageConverters are registered by default:

- ByteArrayHttpMessageConverter
- StringHttpMessageConverter
- ResourceHttpMessageConverter
- SourceHttpMessageConverter
- XmlAwareHttpMessageConverter
- Jaxb2RootElementHttpMessageConverter
- MappingJacksonHttpMessageConverter

So now you understand why works perfectly. When you are returning Character instance, Jaxb2RootElementHttpMessageConverter using canWrite method checks if class contains XmlRootElement annotation. If class is annotated, write method is called. In this case Jaxb marshaller is called, and XML is returned. Same from XML to object but using Jaxb unmarshaller class.

So easy, no complicated configurations, no complicated mappings, no unclear code, and you only need to worry about your model objects, not in conversion. But let me introduce one change. Now instead of returning XML we want to return JSON.

Change could not be easier, add Jackson library to pom.xml and change @XmlRootElement to @JsonAutoDetect. And now MappingJacksonHttpMessageConverter will handle this object and will transform Character instance to JSON protocol using Jackson library. Only changing one line of code!!!

And now output will be:


Of course this is a very simple application with only one operation, but it gives you an idea of how to develop Restful web services using Spring MVC. It is a matter of time of writing all your required operations using same approach that I have used with GET.

Arriving at this point I think that all of us have arrived to same conclusion. Annotations are really really powerful, and Spring MVC fits perfectly for developing RESTful web services.

See you next time.