jueves, diciembre 01, 2011

All my scientists are working on a deadline, So my psychologist is working day and nighttime, They say they know what's best for me, But they don't know what they're doing (Atomic Garden - Bad Religion)


Maven archetypes are project templates that allow users create project structure with a simple Maven command. In my company we are using archetypes because provide a way to standardize projects structure. All our projects are built using the same directory structure, all of us use the same version of common libraries like JUnit, Hamcrest, Spring Framework, Mockito, or in case of web applications bundling them with company's approved CSS and Javascript libraries. Also PMD, checkstyle or findbugs coding rules can be stored in distributed archetype.

If each time you start a new project you are of those who copy files from existing projects to the new one, apply DRY principle and create a Maven archetype from existing project.

First thing to do is create your template project with all files to be bundled into archetype. In this example, simple Spring MVC project will be transformed  to be a Maven archetype.


After template project is created and all desired files are added, you should have a directory layout like:


My personal advice is that if you are thinking about distributing this archetype with community (not only for your company), remove all IDE specific files.

Now you have your project created and ready to be packaged as archetype. Execute next command on root of your project.
mvn archetype:create-from-project
And Maven console output should be:

And now your archetype is created in target/generated-sources/archetype directory with next hierarchy:


Now project is inside archetype-resources directory. This directory contains all files that will be added in generated project.

At first sight, not much differences between original project and "template" project, it seems that only three files has been added archetype-metadata.xml, archetype.properties and goal.txt, but shortly you will see that original project content has been modified too.

Before continuing see that in project exists two poms, one pom that is in root directory, that will be called archetype pom, because it contains all archetype configuration, and another one into archetype-resources, called template pom, because it will be the pom used in generated project.

Next step is isolate archetype project into separate folder, so can be dealt as alone project.
mv target/generated-sources/archetype ../spring-mvc-archetype

Following step is adding a name to generated archetype, so open archetype pom and change  <name> tag value to your archetype name, for example spring-mvc-archetype, and if you want  artifactId and groupId too.

After this modification, open archetype-resources' pom, and see how <artifactId> or <groupId> values are surrounded with ${artifactId} or ${groupId}. When you are creating a new archetype, by default Maven will ask you to enter four parameters, groupId, artifactId, version and package. Entered values will be used to fill placeholders.

With default four parameters should be enough, but imagine you want that user provides more information, for example, war name. To get this, open archetype-metadata.xml file (src/main/resources/META-INF/maven) and add one required property, using <requiredProperties> tag.

In previous file we are adding a new required property named warName. And last thing to do is update
archetype.properties located on test/resources/projects/basic with default value of new property.

And that's all, if you open any Java class or any Xml file, you will see that has been modified with ${package} variable. This information is filled when you generate the project.

Now you can install archetype into your local catalog and start generating standardized  projects.
mvn clean install
And your artifact is ready to be used. Try next command or if you have installed m2Eclipse plugin open Eclipse and try your new archetype:
mvn archetype:generate -DarchetypeCatalog=local
A list of all installed archetypes is shown. Choose previously created and fill up all required properties, and your new project is built and configured. You can start coding with same libraries that your workmates use and same style rules.

In this post a simple example has been provided, but think about all kind of elements that you copy and paste from one project to another like SCM connection, surefire plugin configuration, release plugin tag name, to cite a few, and how you can integrate them into your archetype.

I wish you have found this post interesting.

Music: http://www.youtube.com/watch?v=AhzhiQA6-Aw&ob=av3e

viernes, noviembre 25, 2011

Your big daddy's got no place to stay, Bad communication, I feel like the president of the USA (Mr. Bad Guy - Freddie Mercury)


In current post I am going to explain how to implement nice web form using HTML 5 and CSS 3 effects, and how can be integrated into Spring MVC web application.

First thing to do is create a Spring MVC skeleton project using STS Spring Templates. In fact you can use any other method but I prefer to use a standard template.

Next step is create an HTML 5 web structure, but exists some online applications that can do this for you, hence I am going to HTML 5 Boilerplate site, and create a custom HTML 5 template.




Then open downloaded zip and copy required structure into previous generated project. Css and Js folders into resources directory, and rename index.html to index.jsp and copy it to views directory.

Now open servlet-context and add mvc:resources tag for serving static resources.


If you deploy application a white screen should be showed but without any client/server error.

Let's start creating next html form.



Now open index.jsp and remove div with id main and create next form:

And now if you run again, you should see something like:



Add @import url(http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz); on top of CSS file.This will make a nice font available from Google Fonts directory.

Now it is time to start applying CSS for creating a better layout. Open style.css and modify/create next elements:

And now your form should look with next layout:


See that new font is not used, simply find body,button,input,select,textarea entry and remove font-family property.

Better than before, see how only modifying CSS, form layout is modified.

And now let's start with CSS3 magic.

First trick is adding shadows and gradients to form.

And next lines into input, textarea style:

where -moz prefix is used for Gecko based browsers, and -webkit is used for Webkit browsers.

Next lines add some mouse over effects into form elements.


And to finish applying styles, we are going to modify submit button.

Remove input[type="submit"] from button and input style.

And add next lines into CSS file:


CSS magic is over, now it is time to start with server side.

If you look careful Spring taglibs, you will see that you cannot create for example email input types directly or URL types to cite a few. So I decided to use a new template engine called Thymeleaf, that offers a really nice approach for integrating HTML 5 with Spring MVC applications.

The main goal of Thymeleaf is to provide an elegant and well-formed way of creating HTML 5 templates. Its Standard and SpringStandard dialects allow you to create powerful natural templates, that can be correctly displayed by browsers and therefore work also as static prototypes. This is possible due the absence of taglibs like  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>.

First thing to do is change index.jsp to index.html, and change ViewResolver to Thymeleaf ViewResolver:

First add Thymeleaf dependencies into pom and then modify servlet-context.xml to register TempateResolver, TemplateEngine and ThymeleafViewResolver and remove the deault view resolver.



Next step is modeling our form to a model class, and modify Spring Controller to manage form submition.

Model class is not shown because is a simple POJO with form fields. Let's see how controller is modified.

Open HomeController class and create two methods (GET, POST) to deal with HTML5 form. Note that it is a typical Spring Form Controller;

And finally we are going to templarize index.html content, using Thymeleaf engine.

Open index.html and make next changes:

Add Thymeleaf namespace on html tag.

<html xmlns:th="http://www.thymeleaf.org">

Then change form tag with two new attributes, one with object's model name (form backing object) and other one with submition URL.

<form action="#" th:object="${messageInfo}" th:action="@{/}" method="post">

Next thing to do is change each form element with th:value attribute containing backing object property name.

<input type="text" name="name" value="" id="name" placeholder="Your Name" required="required" autofocus="autofocus" th:value="*{name}"/>

And more few changes should be performed:

Use DOCTYPE instead of doctype

At time of writing this post, html5boilporate introduces link tag without closing, so Thymeleaf parser will throw an exception if is executed as is, so let's terminate link tag and meta tags.

And finally last change is required because of xhtml correctness:


<script> tag is surrounded with CDATA tags. See explanation here:  http://javascript.about.com/library/blxhtml.htm.

Now you can deploy application and your HTML5+CSS3 form is displayed and data submitted is displayed through server console and form page is reloaded with introduced data. And now I am going to explain what are those strange expressions in form and then we will add a new page.

Inside each Thymelef attribute four kind of expressions can be used:

  • ${...} are Spring EL expressions and are executed on model attributes.
  • *{...} are expressions executed on the form backing bean, it is like a pointer to form object (root).
  •  #{...} are for internationalization.
  • @{...} are link expressions to rewrite URLs.

And before jumping to next section try this, instead of opening index.html from http://localhost:..... try to open from your drive file://.... and I suppose you see that that's not a nice prototype because no styling is applied. This happens because we are using CSS location as:

<link rel="stylesheet" href="css/style.css"/>

HTML file is at /src/main/webapp/WEB-INF/views/ and this directory does not contain css folder. And now you can think that I have not told you the true about prototyping with Thymeleaf, but wait trust me and change that line to:

<link rel="stylesheet" href="../../css/style.css" th:href="@{/css/style.css}"/>

And open again, and wow now you can see it, a real page as one generated by the server. What we have changed is that when a browser opens HTML file without using template engine (offline), href attribute is used, but when page is online (and requested file acts as a template), th:href attribute is used.


Listing Messages:

Let's start creating a new HTML file to display all inserted messages and apply some styling with CSS.


First add a new CSS property to apply same design in table.

New CSS 3 property (nth-child) is used so even tr tags of a table will contain different style than odd tr tags.

Then create a file called list.html in same level of index.html:


This is a copy paste of index.html but changing div with id content.

In this case we are using another nice feature of Thymeleaf, collection iteration. With th:each you are iterating over a collection of elements. See that rowStat variable can be used for retrieving column information like number of column. And also see how we are defining default values between td tags, so this file is a prototype too.

Next step is changing our controller, so homeForm (renamed to showResults) method returns a list of messages:


Using a simple list as repository is not a good design, but for teaching purpose is enough. See that view name is set to list, and list of messageForm are sent back with model name used in th:each attribute.

Internationalization:

Next step is internationalizing the application. For this reason we create a message properties file (messages_en_US.properties) into src/main/resources/locale:

Then you must configure Locale beans in Spring context file.

And finally change index.html and list.html static values to internationalized keys using #{} expression:

<th th:text="#{theader.count}"></th>
<label for="name" th:text="#{theader.name}">Name: </label>

And although internationalization is used, web page is still a prototype.

It seems like application is working well, but it has one problem. Try next sequence of events:

1. Add a new message.
2. When list of all messages are shown, refresh the page (F5).

And surprise the same message is added too, so now we have two repeated messages, but you have only inserted one.

To fix this problem we must change our controller and use redirect keyword on create method to redirect to a method of controller that finds all inserted messages.


When a new message is created (create method), a redirect to /list is returned, then showResults method is called, and returns a list with all inserted messages. Remember to change th:action from form tag to /insert too.

And now if you execute the same process as before, no multiple insertions occur.

Validation:

And as final step let's see how to implement validation with Thymeleaf.

First thing is adding Jsr-303 provider into our pom. In this case Hibernate-Validator.


Next step is changing our model by for example creating a length constraint in phone field:

@Length(min=9)
private String phone;

To trigger validation of a @Controller input, you must annotate input arguments with @Valid. So our controller is modified to:

And finally modify form page so when an error occurs, a message is shown.

First a new CSS style is created for showing error message:

See that in previous style we are defining an img folder so new static resource resolution in servlet-context.xml as done with css and js folders must be registered.


And finally in index.html a new div is created for showing errors:


For showing errors, #fields variable is used. This variable is provided by Thymeleaf and contains all errors bound by Validation Framework. Note that star '*' is used as errors function parameters for returning all errors produced by all form fields, but Thymeleaf allows you to specify only one particular field.

Conclusions:

From this post I have learned some interesting points:

  • With new HTML5 tags, some Javascript validation (like entering well-formatted email) is not required anymore.
  • CSS 3 shadows and gradients properties allow us to create amazing forms without using complicated structures of images.
  • Thymeleaf is an amazing template engine, in fact for me a real way for creating prototypes and final code at once. 
  • Thymeleaf is a young project, and for example does not support jQuery by default, but exists   a Thymeleaf dialect that integrate it. I think that in nearest future it will be a template engine to be consider.

Hope you find Thymeleaf useful too.


Download Code.

Music: http://www.youtube.com/watch?v=MMr1zH8NoEY

viernes, noviembre 18, 2011

What a wicked game you play, To make me feel this way, What a wicked thing to do, To let me dream of you ( Wicked Game - Chris Isaak)



In my previous post I was talking about how to create a service using Jdk service provider. In current post I am going to talk about how to implement your own Jsr223 Script Engine. And as you will see, script engines are a kind of Jdk service providers, so instead of creating your own set of interfaces, we are going to see how to implement a service provider of an already defined service. 

Moreover we are going to see how we can convert a scripting language expression evaluator (in this case Spring EL) to be Jsr-223 compliant.

First of all for those who do not know what is Jsr-223 specification (or Java Scripting API), Jsr-223 is a scripting language independent framework for using script engines from Java code. Thanks of Jsr-223, we only use javax.script package instead of importing language specific classes.

For example using Spring EL scripting language, requires you import in your business class at least two Spring classes ExpressionParser and SpelExpressionParser, and if you want to use another scripting language, more specific vendor classes should be added, so your code is tied to script parser used.

If you use Java Scripting API, two classes are required, ScriptEngineFactory and ScriptEngine, regardless of the language used. And this occurs because ScriptEngine is an interface returned by ScriptEngineFactory service.

Let's start coding:

First class to implement is ScriptEngineFactory and is responsible of creating a new ScriptEngine. It must implement ScriptEngineFactory interface and its implementation will be the service provider of Scripting API.



First part of class is where we are defining what is the name of script language used to get the engine, the version of language (I have chosen Spring version), and version of engine.

Then three special methods:

  • getMethodCallSyntax: returns a String which can be used to invoke a method of a Java object using the syntax of the supported scripting language. In case spEL, the equivalent of calling a Java method from script, is using Types with special T operator.
  • getOutputStream: returns a String that can be used as a statement to display the specified String using the syntax of the supported scripting language. In case of spEL, there is no output stream so an unsupported exception is thrown.
  • getProgram: returns a valid scripting language executable progam with given statements. As previous method, an unsupported exception is thrown.

and finally the most important method getScriptEngine, which must return an implementation of ScriptEngine interface. In this case the Spring EL script engine. Let's see how spEL ScriptEngine is implemented.


First of all class extends from AbstractScriptEngine, which provides implementation for several of the variants of the eval method. Compilable interface is implemented too. ScriptEngines that implements this interface can compile scripts so any further execution of expression does not require any recompilation.

Most important method is eval which should cause immediate script execution using vendor library.

Main purpose of this class is adapt Jsr-223 classes to Spring EL classes. If you look carefully this class, it contains a private inner class that extends CompiledScript. This class is responsible of storing compiled expression, so subsequent calls of eval method requires no reparsing. This class is returned when compile method is called.

As final note spEL language contains some features that go beyond a standard script like registering Java functions into script, referencing Spring Beans, expression templating or navigation through properties of root objects. Of all of these features I think it would be useful having root objects support in Jsr-223 implementation, so I have coded a special attribute named "root". So if you set an attribute to script context with name "root",  attribute's content will be treated as root object.

Before implementing this solution I wondered another possibilities like not implementing root objects, or using Adapter pattern implementing two interfaces ScriptContext and EvaluationContext, but I dismissed because there were duplicated methods (different signature, same behaviour), and from developer's point of view  could be a bit confusing. Moreover this approach implies that caller should know that are running spEL script. Also I planned of using MethodResolver or PropertyResolver but was rejected because spEL would have been extended.

With attribute approach, if you are not using root objects, there are no differences between using Scripting API with Javascript, Groovy or spEL.

And finally service configuration. Create META-INF/services directory into resources folder, and create javax.script.ScriptEngineFactory file; this is the full qualified name of service interface with next content:

And that's all about implementation, with next unit tests you will see clearly how is used:

First one is testing that SpelScriptEngine is returned by ScriptEngineManager.

Not complicated, it is used as you would use for retrieving Javascript engine. Short name is used as engine identifier.

And next unit test contains some assertions about how some Spring EL features are used with ScriptEngine rather than SpelExpressionParser.

Notice how in first test, SpelScriptEngineImpl.ROOT_OBJECT constant is used, so Inventor instance is specified as root object.

Hope you found this post useful.

Feel free to use this code, I have created a git repository so you can download, branch, ... https://github.com/maggandalf/spEL223

Also I have uploaded project as zip file. Download Code.

Music: http://www.youtube.com/watch?v=UAOxCqSxRD0

jueves, noviembre 10, 2011

Fear of the dark, fear of the dark I have a phobia that someone's always there (Fear of the Dark - Iron Maiden)



Some time ago I wrote about how to implement your Restful Web API using Spring MVC. Read my previous  post to know about it. 

In that post it was developed a simple Rest example. For testing the application,  file was copied into a web server  (Tomcat for example), and then accessing to http://localhost:8080/RestServer/characters/1 information of character 1 was returned.

In current post I am going to explain how to transform that application to a Google App Engine and be deployed into Google's infrastructure using Maven. Of course in this case we are going to deploy a Rest Spring MVC application, but same approach can be used for migrating a Spring MVC web application (or any other application developed with other web framework) to GAE.

First of all, obviously you should create a Google Account and register a new application (remember the name because will be used in next step). After that you can start the migration.

Three changes are required, create appengine-web.xml defining application name; add server tag to settings.xml with Google account information, and modify pom.xml for adding GAE plugin and its dependencies.

Let's start with appengine-web.xml. This file is used by GAE to configure application and is created into WEB-INF directory (at same level of web.xml).

The most important field is application tag. This tag contains the name of our application (defined when you register a new Google Application).

Other tags are version, system properties and environment variables, and misc configuration like if you want a precompilation to enhance performance or if your application requires sessions.

And your project should not be modified anymore, now only Maven files will be touched.

In settings.xml, account information should be added:

See that it is as easy as registering any other server in Maven.

And finally the most tedious part, modifying pom.xml.

First thing is adding new properties:

At first line we are defining Appengine Java SDK location. If you have already installed then insert location in this tag, if not, copy same location of this pom and simply change maven repository directory, in my case /media/share/maven_repo, to yours. Typically your Maven repository location will be  /home/user/.m2/repositories. Maven will download SDK for you at deploy time.

Next step is adding Maven GAE repository.

Because our project is dummy project, Datanucleus are not used. In case of more complex projects, that database access is required using, for example JDO, next dependencies should be added:

And in case you are using Datanucleus, maven-datanucleus-plugin should be registered. Take care to configure it properly depending on your project. 

Now Google App Engine dependencies are added.


Then if you want to test GAE functionalities (not used in our dummy project), next GAE libraries are added:

Next change is a modification on maven-war-plugin including appengine-web.xml into generated package:

And finally adding maven-gae-plugin and configuring it to upload application to appspot.

See that <serviceId> tag contains the server name defined previously in settings.xml file.

Also if you are using maven-release-plugin you can upload application to the appspot automatically, during release:perform goal:

Now run gae:deploy goal. If you have already installed Appengine Java SDK, then your application will be uploaded to your GAE site. But if it is the first time you run the plugin, you will receive an error. Do not panic, this error occurs because Maven plugin does not find Appengine SDK into directory you specified in <gae.home> tag. But if you have configured gae.home location into your local Maven repository, simply run gae:unpack goal, and SDK will be installed correctly so when you rerun gae:deploy your application will be uploaded into Google infrastructure. 

In post example you can go to http://alexsotoblog.appspot.com/characters/1 and character information in JSON format is displayed into your browser.

As I have noted at the beginning of the post, the same process can be used for any web application, not only for Spring Rest MVC.

Because of teaching purpose all modifications have been made into application pom. My advice is that you create a parent pom with GAE related tags, so each project that must be uploaded into Google App Engine extends from same pom file.

I wish you have found this post useful.

This week I am at devoxx, meet me there ;) I will be speaking on Thursday 17 at 13:00 about Speeding Up Javascript & CSS Download Times With Aggregation and Minification. 

Full pom file:


Download Code.

lunes, noviembre 07, 2011

I en una paret al fons imprès en blanc i negre hi havia un pòster d'en Godard. Potser ell em podria dir-me perquè em ballava el cap. (Jean Luc - Els Amics de les Arts)


Although you can think that Comma-Separated Values (CSV) files are simple files where each value is separated by commas, it is far from reality. The most important part of CSV files are delimiters, and one can think that the delimiter, as type name suggests, is comma. But this assumption is not always true and CSV is often applied to files using other delimiters. Typical example is found in countries where comma (,) is used as decimal separator, because you would have no way to discern between decimal number or separator, semicolon (;) is used.

If your application is distributed across different countries and your application should support  Comma-Separated Values files, then you should take care about this important fact.

Let's see how can we resolve this problem so we can read CSV files depending on country. 

For reading CSV files we are going to use openCSV library. This API contains one class for reading CSV files (CsvReader) and another for writing (CsvWriter). By default it uses comma as column delimiter, but you can also inform which delimiter character must be used.

So the problem is how to know which delimiter we should use. And for resolving this problem we can use DecimalFormatSymbols class. This class represents the set of symbols needed to format numbers.

DecimalFormatSymbols has a method called getDecimalSeparator() that as his name suggests returns a decimal symbol, comma (,) in case of countries like Germany, and dot (.) in case US for example. So with a simple ternary you could know which delimiter is used in CSV files depending on locale.


So final class will look like:


And previous factory can be instantiated with Spring and injecting delimiter, using Spring Expression module.


See that thanks of Spring Expression delimiter is injected directly into class.

I think it is not difficult to implement an application that can read Localized Comma-Separated Values files, and can avoid having problems when application is distributed around the world.

Full Code: https://github.com/downloads/maggandalf/Blog-Examples/csv.zip

Music: http://www.youtube.com/watch?v=A3Yl3Fsj7tw&feature=related

miércoles, noviembre 02, 2011

En ti puedo ver la libertad, Tu me haces sentir que puedo volar, Y se que aquí es mi lugar, Y se que a ti yo quiero amar (Cuando Me Miras Asi - Cristian Castro)




From ServiceLoader javadoc: A service is a well-known set of interfaces and classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself.

Since JDK 6, a simple service-provider loading facility is implemented. As is suggested it is simple, you cannot understand that implementation as a complex system for implementing plugins for your application, but can help you in many situations where you want  implementations of a service could be discovered by other module automatically.

What I really like about using JDK Services is that your services do not have any dependency to any class. Moreover for registering a new implementation of a service, you just have to put jar file into classpath and nothing more.

Now I will explain the service we are going to implement, and then I will show you how to code it.

We want to implement a system that depending on kind of structured input (comma-separated value, tab-separated value, ...) returns a String[] of each value; so for example you can receive input a,b,c,d or 1<tab>2<tab>3<tab>4 and the system should return an array with  [a, b, c, d] or [1, 2, 3, 4].

So our system will have three Java projects.

One defining service contract (an interface) and, because of teaching purpose, a main class where internet media type, for example text/csv, is received with input data. Then using a factory class that I have created, it will ask which registered service can transform input to String[].

And two projects each one implementing a service following defined contract, one for comma-separated values and another one for tab-separated values.

Let's see the code:

Main project (reader) is composed by an interface, a main class and a factory class.

The most important part is Decode interface which defines service contract.


Two operations are defined, one that returns if service supports given input, and another that transforms data to String[].

DecodeFactory class is responsible for finding an implementation service that supports required encoding. In fact, this class encapsulates java.util.ServiceLoader calls. ServiceLoader class is in charge of load registered services.


At line 3 we are loading all services that are registered in classpath. At line 7 we only iterate through all services asking if given encoding name is supported.

And finally main class.


And now if you run this class with java -jar reader.jar "text/cvs" "a, b, c, d", an UnsupportedEncodingException will be thrown. Now we are going to implement our first service. Note that reader project will not be modified nor recompiled.

First service we are going to implement is one that can support comma-separated values encoding. Only one class and one file are important.

CSV class is an implementation of Decode interface and transforms comma-separated values.


As you can see a simple StringTokenizer class. Only take care that this class is Locale sensitive, countries where comma (,) is used as decimal delimiter, separation character is semicolon (;).

And next important file is a file that is placed into META-INF. This file contains a pointer to service implementation class.

This file should be in META-INF/services and should be called as interface full qualified name. In this case org.alexsotob.reader.Decode. And its content should be service implementation full qualified name.


And now you can package this project, and you can reexecute reader project but with generated jar (csv.jar) into classpath. And now output will be an array with a, b, c and d characters instead of unsupported exception.

See that reader project has not been modified and its behaviour has been changed. Now you can develop new implementations for decoding new inputs, and you should only take care of copying them into classpath.

Only take care that all services should have a default constructor with no arguments.

And for those who use Spring Framework, Services are also supported through three different FactoryBeans, ServiceFactoryBean, ServiceListFactoryBean, ServiceLoaderFactoryBean.

As I have noted at start of this post, JDK services is a simple (yet powerful) solution if you need to create a simple plugins system. In my case it has been enough with JDK services, and I have never required more complex structure; but in case you are thinking about a complete plugin solution you can use JPF that offers a solution like Eclipse plugins, or even OSGI.

I wish you have found this post useful and now you know (if you didn't know yet), an easy solution to develop modules that are plugged and play.


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.

Music: http://www.youtube.com/watch?v=Njbm_MABQJE&ob=av2n

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)


INTRODUCTION

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.

HANDS ON

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.

CODING

What I am going to implement is wikipedia example of Observer pattern (http://en.wikipedia.org/wiki/Observer_pattern#Example) 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:

hello
Thread-0
Thread-0
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:

hello
Thread-1
pool-1
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.


Music: http://www.youtube.com/watch?v=GfnkcKiocRw

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)





INTRODUCTION

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.

DESIGN

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 java.io.InputStreamWriter and java.io.OutputStreamWriter. 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.

CODE

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 http://snakeyamlrepo.appspot.com/releases/1.9/site/apidocs/index.html 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.


RUNNING

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)



REST INTRODUCTION

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).

HANDS ON WORK

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.

CODING

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:



CONCLUSIONS

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.