miércoles, septiembre 28, 2011

Ratti Ratti Sachi Maine Jaan Gavayi Hai, Nach Nach Koylo Pe Raat Bitayi Hai, Akhiyon Ki Neend Maine Phoonko Se Uda Di (Jai Ho - A.R. Rahman)




Last week Spring Integration 2.1 M1 was released. One of new features is an implementation of MessageStorage interface that relies upon MongoDB for persistence.  

In current post I will show you an example of Spring Integration using Claim Check pattern and MongoDB as storage system.

First of all a small introduction of each component we will use.

Spring Integration provides an extension of the Spring programming model to support the well-known Enterprise Integration Patterns. It enables lightweight messaging within Spring-based applications and supports integration with external systems via declarative adapters.

MongoDB is a high-performance, schema-free, document-oriented database, which stores JSON-like documents.

Claim Check pattern is an EIP pattern which allows you to replace message content with a claim check (a unique key), which can be used to retrieve the message content at later time. This pattern can be used when message content is very large and should be sent by request or when you cannot trust the information with an outside party and you use a claim check to talk with it.

As an example I have used a simplified version of Cafe Sample Application that are shipped with Spring Integration bundle, but adding MongoDB MessageStore.


In this diagram you can see a schema of sample application. First of all cafe component is the gateway, the point of entree to the system, and is connected to orders channel. Orders are sent to splitter, and each order is sent through pack channel. Last step is check-in component. This component is responsible to store order into MongoDB and generate an UUID. Finally UUID is sent to output (in this case console output).

Now I will show you the code of first part of application. I have assumed that you have already installed MongoDB on your system and is running.

Application context file contains Spring Integration beans that define structure defined above. See that the most important part is the definition of MongoDbFactory at line 18, and line 22 where we are defining database name (test database is created by MongoDB by default). The other part of file is self-explained. See that in line 37, claim check is defined and MongoDB message storage is referenced.

Next important piece of code is Cafe interface. This class acts as a facade for placing orders and not explained yet, for retrieving orders. Let's see this class:

Typical Spring Integration gateway class, where entering points are defined. For now line 7 is the most important because this method will be called for placing orders into orders channel.
And now you are ready to send orders using Cafe interface and receiving at console output not the order but an UUID.

This is a simple snippet that can be executed as unit test (in fact this is not a unit test I know, but for teaching purpose is enough). And if you execute it you will see two long numbers in console, something like:


Remember that number because is required in next step. Meanwhile orders are stored into database. If mongo console is opened, we can query test database and all orders stored will be returned.


Now that check-in has been implemented and tested, it is time to implement check-out method. In this example user (you) will enter UUID using console. Entered reference will be sent to input channel, order object with entered code will be retrieved from database, and sent it to stdout channel. Let's see the code:


Not much difference but instead of using claim-check-in we are using claim-check-out. In line 37 we are defining a gateway to enter UUID (recoverOrderAndSent method of Cafe interface). Introduced identification is sent to input channel and check-out is executed, consequently order with that identifier is sent to output channel (console output).

And our "test" now looks like:


Take a look, first of all two orders are sent to check-in component. Orders are saved to MongoDB and returned UUID are printed to console. Next step in that method is asking user to introduce one of previous UUID and order is checked-out. 

And the output:


Note how simply is to configure your application to use claim-check pattern with Spring Integration, only configuring XMLs, without writing one line of code.. This is a simple example, of course you can use all the power of Spring Integration (aggregators, splitters, adapters, ...) with claim-check.

I wish you have found that post useful.

Download code.

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

jueves, septiembre 22, 2011

Luna quieres ser madre Y no encuentras querer Que te haga mujer Dime luna de plata (Hijo de la Luna - Mecano)



In previous post link I talked about aspects, concretely ITD, and how can be used to design your classes with its own responsibilities while maintaining source code clear and concise. In that post I used aspectj and spring-aspects as aspect-oriented implementations. An important concept of aspect programming is the process of weaven. An aspect weaver takes information from raw classes and aspects and creates new classes with the aspect code appropriately weaved into the classes.

If you are using Eclipse with AJDT plugin, weaver is executed automatically, but if you are using any build tool like Maven, you should take care of configuring correctly so generated classes contains aspect code too.

In this post I will explain how I have modified a pom file so compilation process also weaves aspect code into classes.

First thing I always do when I generate a pom file is adding component version in properties section. In this case spring and aspectj:

Next step is adding dependencies. To work with aspectj and spring-aspects four dependencies must be added.

But one more important dependency is required, and let me surprise you:


You can think I am joking, but not, JPA API is required. Here you can read why: https://jira.springsource.org/browse/SPR-6819. AnnotationDrivenStaticEntityMockingControl class requires javax.persistence.Entity to be in classpath. Hopefully nowadays most projects use JPA, so this dependency may already be required by your code, if not, then you should append it as dependency.

And finally aspectj-maven-plugin is registered:


This plugin requires that you define which dependencies will be used using <dependencies> tag. In order to apply already compiled aspects to your own sources you need to setup all JAR files you would like to weave in the plugin configuration using <aspectLibraries> section; in this case spring-aspects artifact is required so application can use capabilities that offer @Configurable annotation. Finally execution section should contain compile and test-compile goals so main and test classes can be woven.

Hope you find this post useful.

Alex.

lunes, septiembre 19, 2011

The Bell That Rings Inside Your Mind, Is Challenging The Doors Of Time, It’s A Kind Of Magic (A Kind Of Magic - Queen)



During class design we should take decisions about the assignment of responsibilities that will have every class. If we have chosen well, systems tend to be easier to understand, maintain and extend.

Almost all of our projects have a persistence layer, either relational database, document stores, or simply XML files. And typically you will use DAO pattern to implement abstract interface between your business objects and your data store.

In this post but I am going to explain another pattern that can be used instead of DAO pattern. Active record pattern is an architectural pattern that force you to implement CRUD operations on your model  class, hence model class itself is responsible for saving, deleting, loading from database.

There are many strategies to follow to implement this pattern, but for me, the best one is using Aspect Oriented Programming, because we are still maintaining separation of concerns favoring isolated unit testing, and not breaking encapsulation.

Aspect-oriented programming entails breaking down program logic into distinct parts. These parts are known as crosscutting concerns because they "cut across" multiple abstractions in a program. Example of crosscutting concerns can be logging, transaction manager, error manager or splitting large datasets. For people that have worked with aspects not much secret here, to use them you simply create an aspect defining the advice and the pointcut, and your aspect is ready to be executed. 

I guess most of us use aspects-oriented programming as I have described in previous paragraph, but will be fewer that uses ITD (Inter-type Declarations) feature.

Inter-type Declarations provide a way to express crosscutting concerns affecting the structure of modules enabling programmers to declare members of another class.

As we say in my country "bad said but well understood", ITD is a way to declare new components (attributes, methods, annotations) of a class from an aspect.

AspectJ is an aspect-oriented extension for Java. AspectJ supports ITD, and for this reason will be used in this post. Moreover I recommend you install AJDT plugin because it will help you develop aspects and having a quick overview of which Java classes are aspecterized.



If you have not understood what ITD is, don't worry, it is a typical example of concept that is best understood with an example.

Let's start with simple example:

Imagine having to model a car. You would have a car class, with some attributes, for this example three attributes (vin number, miles drived and model) is enough.


It is a POJO with three attributes and their getters and setters.

Now we want to add persistence layer, but in this case we are going to persist our POJOs in a XML file instead of a database. So Car objects should be transformed to XML stream. For this purpose JAXB annotations will be used. For those who don’t know, JAXB allows developers to map Java classes to XML representations and viceversa.

I am sure that first idea that comes to your brain is annotating Car class with @XmlRootElement (annotation to map root element in JAXB). Don’t do that, use aspects. Your first mission is trying to maintain Car file as simple as possible. To add an annotation using ITD, is as simple as:


With @type you are exposing which member is annotated. In this case only class. Other possibilities are @method, @constructor and @field. Then elements pattern that should be annotated, in this case Car class, but you could use any regular expressions like org.alexsotob..*. Finally the annotation.

Next step is using JAXB classes to marshalling/unmarshalling objects. In this example I am using spring-oxm package and briefly you will understand why. Spring-oxm is a part of spring-core that contains classes for dealing with O/X Mapping.

This spring module contains one class for each Xml binding supported. In our case Jaxb2Marshaller is used as marshaller and unmarshaller.

It is possible that you are thinking of creating a service class where you inject Jaxb2Marshaller instance. This service would include two methods (save and load) with Car class as argument or return value. Sorry but, doing this, you are implementing DAO pattern. Let's implement Active Record pattern approach. And as you may suppose, aspectj comes to rescue you to avoid mixing concepts in same source file.

Let's update previous aspect file so all required logic by JAXB will be in same file.


See that apart from annotating Car class we are creating two methods, and an annotated attribute.  Attributes must follow same rule as methods,  <class name> dot (.) and <attribute name>. Note that in this case attribute is transient because should not be bound in XML file.

Last step is configuring marshaller in spring context file.

Not much secret. Now let's code a unit test.

Run junit class and BOOM all red, with an amazing NullPointerException. Marshaller is created in Spring context, but not injected into Car class (Car is not managed by spring container, so is impossible to be injected). And now I suppose you are telling yourself: "I told you a service layer would be better, because it would be managed by Spring and autowired would work perfect.". But wait and see. How about using spring-aspects module? Spring Aspects contains an annotation-driven aspect (@Configurable) allowing dependency injection of any object, whatever is or not controlled by container. So let's apply last two changes and the application will run.

First of all is creating a new aspectj file to annotate Car class as Configurable.

And finally modify spring context file to allow @Configurable annotation.

Adding <context:spring-configured></context:spring-configured> namespace is enough. As a result, any time you instantiate an object (via the "new" keyword), Spring will attempt to perform dependency injection on that object.

Now run unit test again and green will invade your computer :D.

ITD is a really nice solution to design classes with its own responsibilities. It gives you the oportunity of writing maintainable and understandable code, without loosing encapsulation. Of course you should take care of not to have high coupling in aspected classes, and convert them in "God Classes".

Note that implementing same approach but using relational database, it is as simple as changing Jaxb2Marshaller to EntityManager.

I wish you have found this post useful.

Download Full code

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

lunes, septiembre 12, 2011

Questa di Marinella è la storia vera Che scivolò nel fiume a Primavera Ma il vento che la vide così bella Dal fiume la portò sopra una stella (Canzone Di Marinella - Mina)




Most of us use Maven as a build automation tool. One of most important section are those related to dependencies. Typically projects have dependencies to external libraries like Spring, Hibernate, Slf4j, ... which are downloaded from External Maven Repository Servers like mvnrepository, ibiblio or from own Internal Maven Repository Server using JFrog or Nexus. This scenario but does not cover all possible cases.

It is uncommon that your project requires an external library that is not present in any repository, but can occurs, and in these cases are where you use company Internal Maven Repository to upload these artifacts. But this is not always possible, and typical example is when you are writing in a blog about a beta library and it is not present in any repository, and you want to add this library to pom file. Would be perfect if Maven could resolve these dependencies too without packaging them into project. So what can we do?

There are some alternatives:

- packaging .class files of external library into your project, so they are packaged as project files.
- asking library creators to upload Milestones to public repositories.
- create your own public Maven Repository.
- using GitHub?

Using GitHub, YES!!. You can configure your GitHub account as Maven Repository. In my case I always upload sample code to GitHub. Why not creating a GitHub project that acts as a Maven Repository and poms referencing to this repository?

Now I will summarize steps that shall be followed: (assuming that you have already created a project).
  1. Create a GitHub repository.
  2. Initialize local directory as Git repo.
  3. Modify project pom so distribution management tag points to local repository.
  4. Perform deploy goal so artifact is deployed to local repository.
  5. Push changes to GitHub.
  6. Nothing more. Now other project poms can use your repository.

Let's get down to work:

The first thing you should know is that the project I want to upload to Maven Repository is located at /media/share/workspace/github-test and project that will have a dependency will be located at /media/share/workspace/bar.

First step is creating a new GitHub repository. So login to your GitHub account and create a new repository. In my case I have named maven-repository.


Second step is initialize local directory as Git repository.

Third step is adding distributionManagement tag pointing to repository so when project is deployed, artifact is created to Git directory.

See that url tag is pointing to previously created Git directory (local disk).

Fourth Step is running mvn -DperformRelease=true clean deploy. Project is compiled, tested, and packaged. Now go to local repository and see what has appeared.

Fifth Step implies two operations, committing changes and pushing them to GitHub.

See that first command is adding root directory. Then all files are committed to local repository and pushed to GitHub repository.


Sixth Step if you want to call it step, is adding repository tag to project that requires published component. In our case bar project requires it.

This pom represents a project that wants to use github-test module. It is important to note that repository url is special (not showed when you explore GitHub projects with navigator), and is https://github.com/maggandalf/maven-repository/raw/master. After repository name (in this case maven-repository) you should concatenate /raw/master. raw because you want to access to files without any decoration (no HTML), and master because it is the branch name.

When bar project is being compiled, github-test artifact is downloaded.


I think it is a good approach when you need to upload a Maven artifact temporally, or simply because your project requires a milestone version of artifact that is not uploaded into any repository.

I hope you like this post, and ... MOVE TO GIT.

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

martes, septiembre 06, 2011

Soy El Capitán De La Nave Tengo El Control, Llamando A La Tierra Esperando Contestación, Soy Un Cowboy Del Espacio Azul Eléctrico (Llamando A La Tierra - M.Clan)



Groovy is an object-oriented programming language for the Java platform and can be used as a scripting language. Most of us but instead of using Groovy alone, we use Grails (web framework based on Groovy) for developing web applications.

But Groovy can be used standalone for developing your internal tools. Let me explain why Groovy scripts have simplified our development of tools for generating data for integration tests.

In my company we create clinical instruments. These instruments are so expensive, and big enough to say that they are not portable. For these reasons each instrument has an emulator, so integration tests are run without having physically any instrument.

Our emulator has an XML file where all required resources for running tests are configured. In summary each file contains a list of blood barcodes, and reagent barcodes. In our case barcodes have a meaning (kind of resource, expiry date, checksum, ...).

So one can think about creating a standard configuration file that is used in integration tests. It is a good idea if you don't know that expiry date is expressed in months. So one day without knowing exactly why your tests begin to fail. The answer is obvious, resources have become expired. We need a (script ?) that updates this XML file so when a resource is becoming expired, its month field is changed.

Moreover not all resources should be updated. Some tests imply working with expired resources. For this reason some barcodes have special format that suggests that update should not be applied.

Because project is developed in Java, one can think about creating a small Java class that do all these work. But wait and think if this class would be small or not, we need a parser (DocumentBuilder), a method that walks all nodes and see if resource is expired or not (NodeList, Element.getAttribute(), ...), and finally writing modifications to file. Furthermore, some barcodes contains special charachtrs that should be detected using a regular expression (Pattern, Matcher) for avoiding its update. Although this class is not difficult, it is far away from a small class with few lines.

But how about polyglot programming? Groovy can be a choice. Let's see how Groovy deals with XML and Regular Expressions.

Imagine next XML file:


Groovy and XML

Meanwhile in Java you create a DocumentBuilderFactory that returns a DocumentBuilder, and then call parse method, in Groovy is as simple as:

and root variable points to root element of XML file.

And now imagine that you want to update all blood barcodes of given holder. With Java you will use an iterator over NodeList or using an XPath expression. See the simplicity with Groovy.


See that with Groovy, nodes are explored as object attributes, and finally we call findAll() method that returns a list of sample nodes belonging to SampleHolder11 tag. For returning an attribute value is as easy as adding @ character before attribute name, in our case barcode.

And for writing an XML is as easy as:


In previous example, output is written to console.

Groovy and Regular Expressions

Remember that some barcodes have special format. In our case if any barcode starts with A, B, C or D, should not be modified. A clean, reusable and maintainable solution is using regular expressions to check if one barcode matches or not special format. In Java the process is not banal, you have to create a Pattern object with a regular expression, a Matcher and use find() method to see if pattern is found on entry or not.

But how we can determine if one string matches a regular expression in Groovy ? ==~ operator does the work for us. Tell me what you think about this expression:


Elementary. You will agree with me that Groovy approach is simpler than Java one.  For specifying a pattern you only have to use ~ character plus a slash (/) then a regular expression and finally a slash to delimit. But Groovy also supports =~ (create a Matcher) and ==~ (return boolean, whether String matches the pattern).

I think that creating a script that reads/parses/writes XML file is so fast and easy, not much classes are involved compared to Java. And not worth making the comparison with regular expression approach, in Groovy is the simplest way one may think.



After the success of previous Groovy script, we decided to create another tool (Groovy script) for manipulating database.

System registers into database every incidence that has occurred to an execution. Some incidences are easy to reproduce with emulator, but others not. In integration tests there is no problem, because a defined-filled database is used, but acceptance tests contains no data and is generated with the execution of tests. But because there are some incidences that are hard to reproduce in emulator, a Groovy script to insert incidences are created.

Groovy and SQL

As Java, Groovy can also access to databases and as you can suppose in a simple way. No Connection object, no PreparedStatement, no ResultSet, ....

Let's see an example of searching data and using them for creating a new registry. Imagine that we have a table called Execution and another one called Incidence, and one-to-many relationship.


Simple, yes? With one line a connection to database is established.

Executing SELECT query and iterate over results are also easy. Using eachRow method, all results are iterated. No ResultSet object is required anymore. Parameters values are passed between brackets ([]), and as XML each row is accessed using Closure. In previous example each row is mapped to execution variable. Moreover see how easy is read a value of each tuple. As in XML you access the value as a class attribute, no more getters of ResultSet methods, in example execution.dboid is used to refer to dboid field.

Finally execute method is used to update database.



Now that I have shown you some of nice features that Groovy offers us, I will explain you how we execute these tools.

GMaven

We use Jenkins with Maven as Continuos Integration System. Before Jenkins starts to execute Integration Tests, Groovy scripts are executed so emulator is configured propertly. The iteresting part of this step is how pom is configured for executing Groovy scripts.

Exists a plugin called gmaven-plugin. This plugin runs Groovy scripts depending on phase and goal.


No problem configuring gmaven plugin, the most important part is where you specify which script should be executed.

As final notes I want to say that I am a huge fan of Java and my intention is not criticize it, but I think that there are some problems that are best suited using other languages rather than Java. My advice is  learning as many kind of languages as you can (Scala, Groovy, ...) so as programmer you can choose the best solution to a given problem.

I wish you find this post useful.

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

viernes, julio 22, 2011

Tu I Jo Asseguts A La Barra D’un Bar, Sona Bona Música I Som Davant Del Mar (Al Mar - Manel)



In current post I am going to talk about differences between Hamcrest and Fest Fluent Assertions. The reason of this post is not to tell you if you should use one or the other. I only want to show you how both implementations resolve the problem of writing readable assertions.

To compare both APIs I have created two JUnits, one using Hamcrest assertions and one where Fest assertions are used.

The comparision is done using only common operations (Logical, Object, Collections, Number, Text) and creation of new matchers. I am not going to compare which ones have implemented more matchers or kinds of matchers, because I think this is not a parameter to use for choosing what library fits better to your project. Moreover in both APIs you can extend them for creating your own matchers.

Let's start showing model representing a simple modelling of Studio Ghibli http://en.wikipedia.org/wiki/Studio_Ghibli movies information. 


Imports:

Hamcrest requires 11 imports:

while Fest requires 2 imports:

in fact this is not a good or bad thing how many imports are required, but it is always a headache remember where a required assertion is packaged. Because Fest uses Fluent Interfaces approach with two imports all operations are available with IDE's "auto-completation" feature.

Simple asserts:

Not much difference between Hamcrest and Fest, in case of Fest verb is also added in method name creating a much readable assert.

Hamcrest


Fest


Logical asserts:

In this case we find a big difference. Hamcrest supports logical operations and can be used independently, meanwhile logical operations in Fest are a part of the method:

Hamcrest


Fest


Object asserts:

Same object operations are provided in both APIs. There is only one difference, in Fest you can chain callings of methods, so number of asserts compared to Hamcrest are fewer.

Hamcrest


Fest


Collection asserts:

In case of Collections is where they differ more from each other. Hamcrest deals with Collections and Maps with methods like hasKey, hasValue, hasItem. Fest uses a more generic calling like includes, excludes, entry; I have not found any way for asserting key instead of key-value in Fest.
Moreover in this example I also compare how to access a bean property in each elements of collection. From my point of view I think that Fest has a better approach resolving this case.

Hamcrest

Fest


Number asserts:

As in simple asserts, there is no much difference between them.

Hamcrest


Fest


String asserts:


Hamcrest

Fest


As you have noted Hamcrest and Fest are very similar, but I think that Fest solves the same problem but in much cleaner way.

Although both solutions offer very similar matchers, each implementation is so different, so creation of a custom matcher is different too. In Hamcrest you should create a class that extends from TypeSafeMatcher. In Fest there are two possibilities, first one is extending Fest-assertions with custom condition (using already Fest structure and defined types), and the second one is extending with custom assertion (creating a new assertThat implementation for required type).

Hamcrest extension for asserting that a character is a human:


In case of Fest there are two approaches, the first one, that requires that our class extends from Condition. As I told previously, extending Condition implies using the same kind of types supported by org.fest.assertions.Assertions.assertThat method (object, int, short, list, array, ...). In previous case our type is Character, and of course does not exist an overload of Assertions.assertThat method with Character, but java.lang.Object. So our class should be:


As you probably noted, you need to cast character variable to Character, neither a clean solution nor optimal. But of course you can use second method, extending from GenericAssert. This class (a Fluent class) will be the responsible of implementing an assertThat that accepts Character objects, and moreover will implement matcher methods. And I say methods because unlike Hamcrest, Fest can contain more than one matcher in each class. For example if there are some tests that we are asserting if character is human, and in another ones asserting if is human and if has a name, in Hamcrest we should create two classes. In Fest you don't have this restriction.


As it is told in Fest site "Which one to use? Hamcrest or FEST-Assert? It is up to you...it depends on the needs of your project and your coding style!"

Download code.

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

lunes, julio 04, 2011

Umetxoak Ikusirik Lorea Ezin Bizirik Arantzak Kendu Nahi Dizkio Bizi Berri Bat Eman (Loretxoa - Benito Lertxundi)



EJP (or Easy Java Persistence) is a powerful and easy to use relational database persistence API for Java. It has no need for mapping Annotations or XML configuration, and there is no need to extend any classes or implement any interfaces. In it is site we can find the following statement: "EJP is, by far, the easiest persistence API available for Java."

From my point of view EJP is a mixture of some features between myBatis and Spring Jdbc Template Row Mapper.

An example of EJP from its website:


and Customer and Support classes are simple POJOs without annotations or any special tag, and no configuration file.

What I am going to explain in this post is how integrate EJP with Spring.

First of all, we are going to create an interface which defines all permitted operations:


This is an example of common operations provided by EJP. Methods that should be clarified are:

  • newDatabase method is used for returning a Database object. This object is a facade that implements all operations supported by EJP. It is the main class of EJP project with permission of DatabaseManager class.
  • loadAssociations are responsible (as its name suggests) to load an object associations.
  • queryForObject methods execute a "query by example" queries.
  • queryForInt is a method used for queries that return numerical results like count(*), avg(...), ...
EjpJdbcTemplate is the implementation of previous interface, and makes use of JdbcTemplate class as core.

Getting a new Database:


Remember that Database object is the core of EJP, and is required to execute all EJP operations. This method creates one Database with given Connection. databaseName is not mandatory, but for no reason is a constructor attribute. A null can be passed without any problem. In this implementation database name is a class attribute.

Deleting:


No secret in deleting an object. Using ConnectionCallback, connection is provided, and Database object is created.

Loading Associations:


If you want to load explicitly all associations of an object, load associations method must be called. The only integration difficult is that database.loadAssociations returns void, and ConnectionCallback should always return a result. In this case void.TYPE is used.

Executing Queries:


In this case most important line is where Database executeQuery method is called. This method returns a class of type Result. This class is a wrapper of ResultSet class but also can deal directly with beans (implicit wrapping), instead of getting one-by-one each parameter. But for following JdbcTemplate strategy and use a row mapper, ResultSet is used for mapping results.

Querying for Int:



See that follows the same schema as executeQuery, but instead of using RowMapperResultSetExtractor, a SingleColumnRowMapper is used. This mapper is used when the query result returns a single result.

Now I am going to show how to use this template into a DAO implementation.


Not much secret in this DAO. Only two methods requires special review findAllCustomersOrderedByName() and findCustomerByExample()

The first one:


this.template.queryForObject(Customer.class, "ORDER BY first_name",BeanPropertyRowMapper.newInstance(Customer.class)) 

 is converted by EJP to SELECT * FROM Customer ORDER BY first_name.

The second one:

this.template.queryForObject(customer, BeanPropertyRowMapper.newInstance(Customer.class)) 

instead of receiving a Class it receives an instance itself to execute the query. In case that first name field was set to alex, the equivalent SQL query would be SELECT * FROM Customer WHERE first_name='alex'


Now I have explained a strategy to integrate EJP with Spring. Because I have followed same structure as Spring-Data Jdbc-Extension project, rather than create a "HelloWorld" project, I decided to fork Spring-Data project into my Github account, and uploaded the code as a new extension for the project. Moreover a Jira issued has been created with id DATAJDBC-11. If you want to watch full code and unit tests go to git@github.com:maggandalf/spring-data-jdbc-ext.git and review spring-data-jdbc-ext/spring-data-jdbc-core/src/main/java/org/springframework/data/jdbc/ejp directory.

I wish you have found this post useful.


Music: http://www.youtube.com/watch?v=PlEknDUSRc0&feature=fvwrel

lunes, junio 20, 2011

Tonari No To To Ro Totoro To To Ro Totoro, Kodomo No Toki Ni Dake Anata Ni Otozureru, Fushigina Deai (Tonari No Totoro - Ghibli Songs)

Spring Framework 3.1 M2 has been released past week. This new release is the last milestone, and next versions will be tagged as RC.

This new version completes the work started in M1, and adds some new functionalities.

To summarize them we can name:

  • Configuring Spring Web MVC application without web.xml (post).
  • Cache abstraction has been revised.
  • A new "packagesToScan" feature for JPA.
  • REST support refinements with respect to URI templates.
  • And many more refinements.

In current post I will talk about Java-based container configuration approach to setting up a Spring Web MVC application.

As a reference application we are going to migrate Spring MVC Template Project to 100% Java-based container configuration.

If you are using STS, you can create a new Spring project from Spring Template Project wizard:


One of these templates is for creating a Spring Web MVC application. In my STS version, this template creates a XML-based container configuration project.



As you have already noted, important elements of this project are: 
  • HomeController that redirects to home.jsp page.
  • web.xml file where Spring DispatcherServlet (loading servlet-context.xml) and ContextLoaderListener (loading root-context.xml) are specified.
  • root-context.xml defining shared resources visible to all other web components.
  • servlet-context.xml defining servlet's request-processing infrastructure, and importing controllers.xml configuration file.
  • controllers.xml as its name suggests configures controllers.

What we are going to create is a revision of Spring MVC Template Project that instead of setting up project using XMLs, is configured using Java classes. The new directory structure is:



If you look carefully, under src/main/webapp directory, there are no XML Spring configuration files. And no web.xml, but I will talk about that later. For now imagine that under WEB-INF there is a web.xml file.

See that structure is very similar to previous one, but spring directory is removed and config package is created. Moreover XML files have been converted to  standard classes.

Again ignore strange WebAppInitializer class that has appeared. Let's see applied changes:

root-context.xml has its equivalent with mytld.mycompany.myapp.config.RootContextConfig.

Most important thing in previous class is @Configuration annotation. This annotation indicates that the class can be used by the Spring IoC container as a source of bean definitions.

Class that replaces servlet-context.xml file is:

I am going to show you servlet-context.xml content so you can ensure that XML and Class contain  the same parameters.

Apart from @Configuration annotation, this class is annotated with @EnableWebMvc, which enables @Controller programming model, and @Import for importing other bean definitions, like servlet-context.xml imports controllers.xml. This class extends from WebMvcConfigurerAdapter because some extra configuration is required. WebMvcConfigurerAdapter defines options for customizing or adding to the default Spring MVC configuration. In summary it provides customizing parameters as mvc namespace does. In our case, as servlet-context does, we define static resources path to /resources/, so we only override configureResourceHandling method. If for example we would like to register interceptors, configureInteceptors method should be overridden. And finally @Bean is used for creating the view resolver bean. @Bean methods define instantiation, configuration, and initialization logic for objects to be managed by the Spring IoC container.

Next class is called ControllerConfig and is the responsible of registering controllers. In this case @Bean approach is used because component-scan is not supported directly. Anyway you can use scan method of AnnotationConfigApplicationContext for same purpose but in this case first choice has been chosen.


And finally web.xml must be changed for loading Java-based configuration instead of XML-based ones. In this case contextClass parameter of DispatcherServlet and ContextLoader listener must be changed to AnnotationConfigWebApplicationContext so Spring IoC Container can load beans from configuration classes, and contextConfigLocation must be pointing to configuration classes, and not XML files.


And I suppose you are wondering why in previous directory structure cannot be seen web.xml but WebAppInitializer class. This is explained in my post, and is another new feature of Spring 3.1 M2, that you can configure a Spring Web MVC application with no web.xml.

So if you want a 100% Java-based configuration, simply removes web.xml file and creates the WebAppInitializer class, which looks like:

As you can see, same elements of web.xml are present but they are configured in a programmatic way.

Hope you find the post useful, of course you can create hybrid applications, mixing elements configured in XML way and other ones configured in Java classes.

Two Spring Template Projects are provided, one configuring Spring MVC application in a Java-based fashion and web.xml, and another one 100% Java-based configured.

Spring Template Project with web.xml
Spring Template Project no web.xml

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

miércoles, junio 15, 2011

It's Strange But It's True, I Can't Get Over The Way You Love Me Like You Do, But I Have To Be Sure, When I Walk Out That Door (I Want To Break Free - Queen)



Spring Framework 3.1 M2 has been released past week. This new release is the last milestone, and next versions will be tagged as RC.

This new version completes the work started in M1, and adds new functionalities.

To summarize them we can name:

  • Java-based application configuration approach has changed from the @Feature approach in M1 to @Enable* annotations (I will talk about this in next post).
  • Cache abstraction has been revised.
  • A new "packagesToScan" feature for JPA.
  • REST support refinements with respect to URI templates.
  • Many more refinements.

In current post I will talk about one new feature that will allow us to configure Spring Web MVC application without web.xml.

With Servlet 3.0 specification, web.xml is not required anymore, you can configure your servlets using @WebServlet annotation. Prior to Spring 3.1, DispatcherServlet should be declared and configured in web.xml, so although our application was deployed using Servlet 3.0 specification, web.xml was "a must". With Spring 3.1, things are different. You can use WebApplicationInitializer approach for bootstrapping a Spring web application without web.xml.

First of all let’s take a look at traditional way (using web.xml).


No problem here, if you have developed applications using Spring MVC this file will sound you familiar.

But now let’s use WebApplicationInitializer approach.

Spring 3.1 comes with WebApplicationInitializer interface, that must be implemented in Servlet 3.0 environments in order to configure the ServletContext programmatically - as opposed to (or in conjunction with) the traditional web.xml-based approach.

What we need is a class (can be created in any package, next I will explain why!!!) that will implement WebApplicationInitializer. Our equivalent class to previous web.xml is:


See that same information is required, but is provided programmatically instead of using web.xml. Spring application context must be created by you setting config file/s location, DispatcherServlet is still valid and must be registered too using addServlet method, and of course context-param can be added using setInitParameter method. And only creating this class that implements WebApplicationInitializer, you can remove your web.xml from your application.

Look ma' no web.xml and Spring Web application is still working. And now let me explain why if our class is not configured anywhere and moreover is created in any place (inside classpath), is instantiated and its onStartup method called? Servlet 3.0 ServletContainerInitializer is designed to support code-based configuration of the servlet container at startup phase. Spring people have created SpringServletContainerInitializer class that implements ServletContainerInitializer, and this class will be loaded and instantiated and onStartup method invoked by any Servlet 3.0-compliant container during container startup. This occurs through the JAR Services API ServiceLoader.load(Class) method detecting the spring-web module's META-INF/services/javax.servlet.ServletContainerInitializer service provider configuration file.

Hope you like this new feature.

Note: Servlet 3.0 container is required (for example Tomcat 7), and versions of Tomcat <=7.0.14, root mapping ("/") cannot be used.
Download Code.

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

martes, junio 14, 2011

Y Hay Un Decano También, Y Un Abogado También, Y Un Policía Rodeado De Ladrones (La Taberna del Buda - Café Quijano)



Due to the advent of mobile internet, a variety of devices have connection to the world (mobiles, pads, GPS, netbooks, ...), and these devices could not be as powerful as desktops/notebooks. For this reason, keeping web pages as lightweight as possible is a must. Improving the engineering design of a page or a web application usually is the biggest savings and that should always be a primary strategy. With the right design, some other strategies can be followed. One of these is code minification.

Now-days, jQuery are becoming so popular in client-side of web development. jQuery is a cross-browser Javascript library designed to simplify the client-side scripting of HTML. jQuery itself is composed by "one" file. Thanks of that boom, Javascript is becoming more important when a web interface is developed.

Have you ever opened jQuery Javascript file? Let me tell you what you will see. Nothing human readable, all code occupied only one long line, and variables and methods name are as short as possible:

See this example:

Of course, there is no developer in the world (or at least I wish), that could write this code. So where this code comes from? It is so easy, it comes from a Javascript minifier tool.

The goal of Javascript and CSS minification is always to preserve the operational qualities of the code while reducing its overall byte footprint

There are a lot of tools designed for minifying Javascript files. One of these are YUI Compressor from Yahoo. From its site:

“The YUI Compressor is Javascript/CSS minifier designed to be 100% safe and yield a higher compression ratio than most other tools. Tests on the YUI Library have shown savings of over 20% compared to JSMin (becoming 10% after HTTP compression).”

Because the growth of popularity of jQuery, and HTML 5/CSS3, client-side coding is playing an increasingly important role in web development, and one of these consequences is that in client-side you could need to develop some custom Javascript files, apart from using already developed Javascript libraries like jQuery. And then the question is, if jQuery minify their files, why I cannot do the same with my Javascript/CSS files? And the answer is: “Yes you are right”, and also I say: “We will automatize this process into Maven, so your web project will be packaged with minified scripts”.

Let’s start with a very simple “Hello World” script file:

If you execute manually YUI Compressor as standalone application (java -jar yuicompressor-x.y.z.jar), script is minified to:

output: myscript.js (115b) -> myscript.js (54b)[46%]

Now our script is 46% smaller than the first one, of course the price we are paying is that we are loosing readability, but in production environment makes no sense.

Next step is configuring your pom.xml (Maven) so when application is packaged, all packaged Javascript files are minified. For this porpoise yuicompressor-maven-plugin (http://alchim.sourceforge.net/yuicompressor-maven-plugin/) plugin comes to rescue you.

No secret here, plugin is executed in generate-sources phase, and is configured with no suffix option because I want that “compressed” file has the same name as original one, and also I don’t want any line break in minified file.

And finally the last trick, maven-war-plugin configuration should be changed for avoiding it replaces minified files for original ones.

In this case scripts are in src/main/webapp/script so excluded sources are script/*.js. yuicompression plugin will copy minified files into target directory that will be used by war plugin for building war file. For this reason we should avoid that war plugin also copies the original file to target directory, replacing the good ones (compressed) for the bad ones (uncompressed).

If you read my previous post, where I talked about decreasing download time of Javascript/CSS files(using aggregation) and also I explained why not to use an automatic approach in development time but in running time, I suppose you are wondering why I am explaining in this post minification using Maven? Well let me explain, YUI Compression should be used in conjunction  with aggregation files. YUICompressionplugin supports aggregation too, so if you are developing a public API it is a good approach using YUICompression (using Minifing and aggregation) with Maven. But if you are developing a website, the best approach is applying optimizations at runtime using Jawr API as I explained in my previous post. But next question  is how to use Jawr (by default it uses JSMin) with YUIcompression? The response is easiest one anyone could think, Jawr also supports YUI. Only one line should be added, open jawr.properties and copy next line:

jawr.js.bundle.factory.bundlepostprocessors=YUI

Now Jawr will minify aggregated file using YUI Compression instead of JSMin.

Hope you find post useful.


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

lunes, junio 06, 2011

I Hitched A Ride With Chris McCandless, I Stepped In The Wild With Chris McCandless, And I Felt Alive With Chris McCandless. I Was Wide Awake In The Dream. (The Ballad of Chris McCandless - Ellis Paul)


Now-days, jQuery are becoming so popular in client-side of web development. jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML. jQuery itself is composed by "one" file called jquery-x.x.x.min.js. With only one Javascript there is no performance problem. But with jQuery has been appeared some "addons/plugins" that uses this library. An example could be jQueryUI http://jqueryui.com/ but more can be found at http://plugins.jquery.com/. Each of these addons contain their own Javascript file. For example jQueryUI contains apart from jQuery file, jquery-ui-x.x.x.custom.min.js and one CSS file, so in this case in a web page two Javascript and a CSS elements are defined. As more and more extensions are used, more Javascript files are required. And more scripts imply more connections to server, so for example if three Scripts and one CSS are defined, four connections from browser to server are required.

Because of these amounts of connections, downloading time is increased; content negotiation and the fact that normally there will be only two concurrent connections to the same host, produces an overhead that results in a long page loading time. For example, it is faster to serve a 8KB script file than  eight of 1KB.



For speeding up your application, would be desirable that only one Javascript and one CSS were downloaded. Arrived at this point, one can think next approach; using a Maven plugin or any other automatic system, that opens all js files and concatenate all of them in a single file. This approach is valid, but has a major problem, any small change forces developer to re-run build script before changes can be tested. Also you are duplicating same information in two or more files, so you must take care assuring consistency between them. 

The goal for Jawr is to provide a system to easily map resources to bundles using a simple descriptor, and a tag library to import these bundles to JSP pages.


In summary, using Jawr taglib you define a fictional Javascript file (for example widgets.js) in JSP; this file does not exist physically anywhere. Then in Jawr configuration file (jawr.properties), you map which Javascript files should be appended when client browser requests "unreal" Javascript file (widgets.js). So from developers' point of view you could have a hierarchy of several js files, while from client-side (browser), only one file is sent.

Using Jawr in only Servlet based web applications are easy. Jawr comes with a Servlet net.jawr.web.servlet.JawrServlet, where you define Jawr configuration file, and a workable mapping for js extensions. (http://jawr.java.net/docs/servlet.html).

But in case of Spring MVC web applications, things are bit complicated. Jawr provides a Spring controller, that acts the same manner as previous Servlet, but instead of using servlet-mapping tag you must create a SimpleUrlHandlerMapping.

In this post I will explain you how to create a Spring MVC jQuery web application integrated with Jawr. Let's start with a Spring MVC application that does not contain any references to Jawr.

JSP page contains definitions for all elements required by jQuery plus one custom script file (defining a() function).

and in servlet-context.xml static resources (Scripts and CSS) mapped correctly.


This web application contains four references to static resources, so load diagram looks like:



As you can see there is no file aggregation. With Jawr these four connections can be reduced to two, one for all Javascript files and another one for CSS.

Let's start mapping resources. This is specified in jawr.properties file that should be present in root classpath:

First line enables the ability to serve gzipped resources to browsers that support it. Next two lines are required for mapping script files. jawr.js.bundle.[bundleName].id is the property where you specify the name of fictional Javascript file. This name will be the one used in JSP. The other line jawr.js.bundle.[bundleName].mappings is where you indicate all Javascript files that should be appended when jawr.js.bundle.[bundleName].id file is requested by browser. In previous example when your JSP page is requesting /script/all.js resource, Jawr will join a.js, jquery-1.5.1.min.js and jquery-ui-1.8.13.custom.min.js and sent back the result to client-browser. Last lines are the same but for CSS files.

Next step is changing JSP, so instead of having one reference for each file, only contains one reference to jawr.js.bundle.all.id value.


Jawr provides a tag library used to generate tags that import bundles to clients and these tags are <jawr:script/> and <jawr:style/>.

Unlike Servlet approach, web.xml don't have to be modified, Jawr provides a Spring controller that must be configured as you would do in Servlet approach.

Next step is configuring Spring Controller. Jawr site provides documentation about how to configure a Spring MVC with Jawr. The example provided uses old-school fashion configuration controllers using SimpleUrlHandlerMapping. But because I always use annotated controllers and I don't want to have some controllers defined with annotations and other ones in UrlMapping, in this post Jawr Spring Controller has been extended for being used with annotations.

For implementing Jawr Spring Controller with annotations I have only created an aggregation between annotated controller and Jawr controller. So class looks:


and the same approach for CSS is used but changing RequestMapping to /**/*.css and Qualifier to jawrCSSController.

As you probably noticed, two Jawr controllers are used, one for Javascript and another for CSS. This is because Jawr requires that you specify if code to optimize is Script or StyleSheet. Spring configuration looks:

Finally <resources> tag from servlet-context.xml should be changed to:

<resources mapping="/css/images/**" location="/css/images/" />

because now only images are required to be served as static resources.

With previous changes applied, load diagram looks like:



See that only one connection for all Javascript files are performed. And also see how downloaded time has been improved from first version. Times showed here are not calculated in a scientific way, they are calculated from localhost, but if you compare previous diagram with this diagram, you can see an improvement.

You can also speed up even more your response time using a cache strategy, but this topic is out of scope of this document.

I wish you have found this post useful, and now before using jQuery scripts, prepare your environment with Jawr so your application can be loaded even faster.

I hope you find this post useful.

Download Code.

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