jueves, febrero 23, 2012

If there ain't all that much to lug around, Better run like hell when you hit the ground. When the morning comes. (This Too Shall Pass - Ok Go)



Javascript has become much more important to interactive website development than five years ago. With the advent of HTML 5 and new Javascript libraries like jQuery and all libraries that depends on it, more and more functionalities are being implemented using Javascript on client side, not only for validating input forms, but as UI creator or Restful interface to server side.

With the growing use of Javascript, new testing frameworks have appeared too. We could cite a lot of them but in this post I am going to talk only about one called Jasmine

Jasmine is a BDD framework for testing Javascript code. It does not depend on any other JavaScript framework, and uses a really clean syntax, similar to xUnit framework. See next example:


To run Jasmine, you should simply point your browser to SpecRunner.html file which will contain  references to scripts under test and spec scripts. An example of SpecRunner is shown here:


From my point of view, Javascript has become so popular thanks to jQuery, which has greatly simplified the way we wrote Javascript code. And you can also test jQuery applications with Jasmine using Jasmine-jQuery module, which provides two extensions for testing:

  • set of matchers for jQuery framework like toBeChecked(), toBeVisible(), toHaveClass(), ...
  • an API for handling HTML fixtures which enable you to load HTML code to be used by tests. 
So with Jasmine you can test your Javascript applications; but we still have a small big problem. We should launch manually all tests by opening SpecRunner page into browser. But don't worry, exists jasmine-maven-plugin. This plugin is a Maven plugin that runs Jasmine spec files during test phase automatically, without needing to write SpecRunner boilerplate file.


So I suppose you want to start coding. We are going to create a simple jQuery plugin in standard Maven war layout, where Javascript files go to src/webapp/js, css at src/webapp/css and Javascript tests at src/test/javascript. Of course this directory structure is fully configurable, for example if your project was a Javascript project, src/main/javascript would be better place. Next image shows you directory layout.



Let's start. First of all we are going to create a css file which will define a red class. Not complicated code:


Next step, create a js file containing jQuery plugin code. It is a simple plugin that adds red class to affected element.

And finally html code that uses previous functionality. Not much secret, a div element modified by our jQuery plugin.

Now it is time for testing. Yes I know write tests first, and then business code, but I thought it will be more appropriate to show first the code to test.

So let's write Jasmine test file.

First thing to do is add a description (behaviour) of what we are going to test with describe function. Then with beforeEach, we are defining what function we want to execute before each test execution (like @Before JUnit annotation). In this case we are setting our fixture to test plugin code, you can set an html file as template or you can define html inline as done here.

And finally the test, written inside it function. Our test should validate that div element with id content, defined in fixture, should contain class attribute with value red after running redColor function. See how we are using jasmine-query toHaveClass matcher.


Now we have got our Javascript test written and it is time to run it, but instead of using SpecRunner file, we are going to make Jasmine tests being executed by Maven during test phase.

Let's see how to configure jasmine-maven plugin.

First thing to do is register plugin into pom.

And then configure plugin with required parameters. In two first parameters (jsSrcDir and jsTestSrcDir) we are setting Javascript locations for production code and testing code.  Since we are writing tests for jQuery plugin in Jasmine, both jquery and jasmine-jquery libraries should be imported into generated SpecRunner, and this is accomplished by using preloadSources tag.

All these parameters will change depending on your project but in case you are creating a Maven war project, this layout is enough.

And now you can run Maven by typing:

mvn clean test

And next console output should be printed:


I think we have integrated Javascript tests into Maven in an easy and clean way; and now our continuous integration server (Jenkins or Hudson) will run Javascript tests too. If you are planning to mount a continuous delivery system with your next project, and this project will contain Javascript file, take in consideration using Jasmine as BDD tool because it suits perfectly with Maven.

I wish you have found this post useful.

Download code

Music: http://www.youtube.com/watch?feature=player_embedded&v=qybUFnY7Y8w#!

jueves, febrero 16, 2012

Party rock is in the house tonight, Everybody just have a good time, And we gon' make you loose your mind, Everybody just have a good good good time. (Party Rock Anthem - LMFAO)




Redmine is a free and open source, flexible web-based project management and bug-tracking tool,  written using the Ruby on Rails framework.

Redmine supports multiple projects, with its own wiki, forum, time tracker and issues management.

Moreover Redmine implements a plugin platform so can be customized depending on your requirements. Exists plugins to work with Kanban, Scrum, notification plugins or reports.

What I really like about Redmine is that although does not fix the way you must work, it contains enough options to work in any kind of project management approach.

Redmine can be installed in different ways:
  • Using webrick (not recommended in production environments).
  • Run with mongrel and fastcgi.
  • Using Passenger.
  • Or package Redmine into war and deploy into  Java container like Tomcat or Glassfish.
In this post I am going to show you how to package Redmine 1.3 into a war file so could be executed into Tomcat7 and Linux. In theory should be work with Glassfish, JBoss, or any other OS.

First of all download JRuby 1.6.6, so open a terminal

wget http://jruby.org.s3.amazonaws.com/downloads/1.6.6/jruby-bin-1.6.6.tar.gz

And decompress downloaded file and move to /usr/share directory.

tar xvzf jruby-bin-1.6.6.tar.gz
sudo mv jruby-1.6.6/ /usr/share/jruby-1.6.6

Then update environment variables with JRuby installation directory.

sudo gedit /etc/environment


Finally try to execute jruby to see that has been installed correctly:

jruby -v

And JRuby version information should be printed on console.

Next step is to install required gems:


Redmine installation

Download Redmine 1.3 and install them on /usr/share directory:

Redmine requires a database to work. In this case I had already installed mySQL5, but postgeSQL is supported too. So let's configure mySQL into Redmine.

cd /usr/share/redmine-1.3.0/config/

Installation comes with a database template configuration file, we are going to rename it and modify to suit our environment. Moreover Redmine contains different start up modes (production, development, test). In our case because we are configuring a production environment, only production section will be touched.


After this modification, it is time to create Redmine user and database into mySQL.

mysql -u root -p


Now it is time to initialize Redmine



Next step is required because we are installing Redmine 1.3, in next versions of Redmine 1.4 and beyond will not be necessary. Open config/environment.rb and comment next like:

config.gem 'rubytree', :lib => 'tree'

And then create database schema and fill them with default data with next scripts.


Now we are going to test that Redmine is correctly configured. For this purpose we are going to use webrick.


and open a browser at http://localhost:3000 to start checking installation.

Redmine web page will be shown, you can login with username and password admin/admin

At this point we have Redmine correctly installed.


Configuring Email

An issue tracker should be able to send mail to affected users when a new issue is created or modified by  change.

If your mail server requires tls security protocol you should install action_mailer_optional_tls plugin.

This plugin requires git, if you don’t have installed yet, type:

sudo apt-get install git

and then run next command on Redmine directory:

jruby script/plugin install git://github.com/collectiveidea/action_mailer_optional_tls.git

Let’s configure email delivery:

Inside configuration file you will find common email settings. Depending on your email server these attributes can vary widely, so at this point I am going to show you a simple smtp server configuration using plain authentication at production environment. Go to last line of configuration.yml file and append next lines into production section.

All attributes are self-explanatory.

And before creating war file, let’s check that email is correctly configured. Again we use webrick.


Then open browser at http://localhost:3000 and log in with admin account.

Adjust admin email by clicking on My Account link, and at Email section, set administrator email.

After that we are going to test email configuration, from main menu, go to Administration -> Settings -> Email Notifications, add emission email and click on test email. After a few time, a test message will be sent to administrator email account.

We have succeeded in Redmine installation, now it is time to package it to be deployed into Tomcat.

Packaging Redmine

Before starting, because of incompatibility with installed jruby-rack gem, we should run next commands to install 1.0.10 version of jruby-rack.

Warble command requires a configuration file. This file is created using next command:

Edit Warble::Config section and configure config.dirs, config.gems and config.webxml.rails.env sections as:

And finally run:

warble

And Redmine war has been created and is ready to be deployed into Tomcat.


Although we have got a war file, I recommend not deleting Redmine installation directory because could be used in future to install new plugins, or modify any configuration. After a modification, calling warble command, a new war with that change would be created.


I wish you have found useful.


martes, enero 31, 2012

Giuro per sempre a te, Di viver, morire per te, Se tu sarai con me lo so, Dea Roma, vincerò!



One of the common problems of people that start using Hibernate is performance, if you don't have much experience in Hibernate you will find how quickly your application becomes slow. If you enable sql traces, you would see how many queries are sent to database that can be avoided with little Hibernate knowledge. In current post I am going to explain how to use Hibernate Query Cache to avoid amount of traffic between your application and database.

Hibernate offers two caching levels:

  • The first level cache is the session cache. Objects are cached within the current session and they are only alive until the session is closed.
  • The second level cache exists as long as the session factory is alive. Keep in mind that in case of Hibernate, second level cache is not a tree of objects; object instances are not cached, instead it stores attribute values.
After this brief introduction (so brief I know) about Hibernate cache, let's see what is Query Cache and how is interrelated with second level cache.

Query Cache is responsible for caching the combination of query and values provided as parameters as key, and list of identifiers of objects returned by query execution as values. Note that using Query Cache requires a second level cache too because when query result is get from cache (that is a list of identifiers), Hibernate will load objects using cached identifiers from second level.

To sum up, and as a conceptual schema, given next query: "from Country where population > :number", after first execution, Hibernate caches would contain next fictional values (note that number parameter is set to 1000):

L2 Cache
[
id:1, {name='Spain', population=1000, ....}
id:2, {name='Germany', population=2000,...}
....
]
QueryCache
[{from Country where population > :number, 1000}, {id:2}]

So before start using Query Cache, we need to configure cache of second level.
First of all you must decide what cache provider you are going to use. For this example Ehcache is chosen, but refer to Hibernate documentation for complete list of all supported providers.

To configure second level cache, set next Hibernate properties:

hibernate.cache.provider_class = org.hibernate.cache.EhCacheProvider
hibernate.cache.use_structured_entries = true
hibernate.cache.use_second_level_cache = true

And if you are using annotation approach, annotate cachable entities with:

@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

See that in this case cache concurrency strategy is NONSTRICT_READ_WRITE, but depending on cache provider, other strategies can be followed like TRANSACTIONAL, READ_ONLY, ... take a look at cache section of Hibernate documentation to chose the one that fits better with your requirements.

And finally add Ehcache dependencies:

<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>3.6.0.Final</version>
</dependency>

Now second level cache is configured, but not query cache; anyway we are not far from our goal.

Set hibernate.cache.use_query_cache property to true.

And for each cachable query, we must call setCachable method during query creation:

List<Country> list = session.createQuery("from Country where population > 1000").setCacheable(true).list();

To make example more practical I have uploaded a full query cache example with Spring Framework. To see clearly that query cache works I have used one public database hosted in ensembl.org. The Ensembl project produces genome databases for vertebrates and other eukaryotic species, and makes this information freely available online. In this example query to dna table is cached.

First of all Hibernate configuration:


It is a simple Hibernate configuration, using properties previously explained to configure second level cache.

Entity class is an entity that represents a sequence of DNA.

To try query cache, we are going to implement one test where same query is executed multiple times.


We can see that we are returning first fifty dna sequences, and if you execute it, you will see that elapsed time between creation of query and commiting transaction is printed. As you can suppose only first iteration takes about 5 seconds to get all data, but the other ones only milliseconds.

The foreach line just before query iteration will print object identifier through console. If you look carefully none of these identifiers will be repeated during all execution. This fact just goes to show you that Hibernate cache does not save objects but properties values, and the object itself is created each time.

Last note, remember that Hibernate does not cache associations by default.

Now after writing a query, think if it will contain static data and if it will be executed often. If it is the case, query cache is your friend to make Hibernate applications run faster.


Download Code

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

viernes, enero 27, 2012

Once upon a time and long ago, I heard someone singing, Soft and low (Distant Melody - Peter Pan)




Thymeleaf Spring-MVC Maven Archetype aims to create a web application that uses Thymeleaf template engine and Spring Framework.

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.

You can read more about Thymeleaf at:


When you create an application using this archetype, generated web application will be composed by two html templates in WEB-INF/views, one for showing a form using HTML5 and CSS3 and another one for listing inserted data.

Spring controllers are located in controller package.

Application is internationalized too using LocaleChangeInterceptor with en_US as default locale. Properties are in src/main/resources/locale folder.

And finally server-side validation is provided by using JSR-303 provider.

Versions of used jars are:

  • Spring Framework: 3.0.5
  • Thymeleaf: 1.1.2
  • Hibernate-Validator: 4.1.0
  • Slf4j: 1.5.10
  • Servlet-api: 2.5
  • JUnit: 4.9

You can install this archetype from source or from jar file:

From source:

mvn clean install
mvn archetype:generate -DarchetypeCatalog=local

From jar:


and execute:

mvn install:install-file \ -DgroupId=com.lordofthejars \ -DartifactId=thymeleaf-spring-maven-archetype \ 
-Dversion=DOWNLOADED_VERSION \ -Dpackaging=jar 
-Dfile=PATH_TO_JAR_YOU_DOWNLOADED/thymeleaf-spring-maven-archetype-VERSION.jar


Maven repository is located at 


and source code is stored at  https://github.com/maggandalf/thymeleaf-spring-maven-archetype

For any question regarding of how to use this archetype or any issue/improvement, do not hesitate to contact me or open a new issue on github.

I wish this archetype can help you to start a new project using Thymeleaf template engine.

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


lunes, enero 23, 2012

Nevermind, I'll find someone like you, I wish nothing but the best, for you too, Don't forget me, I beg, I remember you said:-, Sometimes it lasts in love but sometimes it hurts instead (Someone Like You - Adele))



This week I have reached 100K visits on blog. Simply I would like to say thank you very much to all people that have come and found useful information, my intention is writing posts to make developers life easier.

Especially I would like to thank all dzone folks, theserverside people, springsource bloggers, JavaCodeGeeks, and of course my Twitter followers all of them have helped to reach this number of visits.

To celebrate this event, now alexsotob blog is converted to lordofthejars, so now you can access this blog through alexsotob.blogspot.com or by www.lordofthejars.com.

Thank you very much again to read my blog; my next challenge is to reach 250k visits.

See you next time, keep reading,

Alex.

Music: http://www.youtube.com/watch?v=hLQl3WQQoQ0&ob=av3e

lunes, enero 02, 2012

Sábado na balada, A galera começou a dançar, E passou a menina mais linda, Tomei coragem e comecei a falar (Ai se eu te pego - Michel Teló)



Backbone is a Javascript library that provides a clean way to:

  • define models in Javascript.
  • deal with Collections using a rich API.
  • define Views with declarative event handling and template support.
  • interface to Rest architectures.

In current post I am going to use the Rest WebApp of my old post, where I only explained the server side to show you how to implement client side using Backbone.

So the first thing to do is create a web structure into IDE, for this example I will reuse same project of RestServer post.

Then download backbone.js and its dependencies and copy to webapp/resources/js directory:


Open servlet-context.xml and add root and  js folder as static resource.

Then go to webapp/resources and create index.html.


Add all Javascript libraries into page, but most important, add them in the same order as appears here, if not, some Javascript failures would appear in your browser and the application will not work.

Note that some content is created directly using HTML tags rather than using Backbone views. Normally page layout, headers, footers ... are treated as static content and they are directly written into page.

Let's start modeling our data, in this case a character with its attributes (id, name, url, isHuman...).


Models in Backbone has a particularity that make them useful, they are an implementation of Active Record pattern, so when you are creating a model you will have CRUD operations against a Rest-WebService. So for example when you call save method of your model, Backbone converts that model to JSON and sends the result to server as HTTP POST (if model has no id), or HTTP PUT (update). Other available operations are fetch (load) and destroy (delete).

See how in this case we have created a Character model setting urlRoot property. This property is used to build endpoint to ResetServer.  As long as the endpoint returns JSON for a single character, properties will be merged into model.

And the same applies to Collections. When you call fetch method of characters var, all characters returned by calling GET .../characters will be stored into.

See how easy is implementing a Rest Client using Backbone. And I suppose you are wondering where are attributes' definition? Don't worry, with Backbone is not necessary to explicitly define at definition time.

Now it is time for Views. As I cited at the begin of post, Backbone has template support. For this example two templates are going to be used, one for filling a new character and another for showing character information.


To define a template you must use <script> tag with text/template type instead of text/javascript and an id. The structure is similar to JSP (embedded HTML code, <%= %> for printing variables and <% %> for logical structures).


Next step is creating Views

For this example we are going to create three views, one for each template, and one that will be a composition of both.

Let's start with View responsible of showing information of one character.

At line 3 we are loading template content defined previously with id show-characters, into showCharactersTemplate object.

Next important line is number 6. There we are defining a function that will be invoked each time we want to render a view (one time per character). See how we are passing a model object (trust me it is not defined yet, but will be there), to template. To fill template variables, template engine requires data in JSON format, and Backbone model has a toJSON method.  And finally generated html code is saved into el attribute.

Next View is responsible of showing character form, and deal with submit action.

This View shows events handling in Backbone. See line 9. We are defining that when user clicks on tag element "a" with class submit, element defined in new-character template, createOnEnter function is executed.

createOnEnter method does three things:

  • gets values from template form.
  • instantiates CharacterModel class. See that this is the place where model attributes are defined.
  • calls save method. This method sends object data to defined endpoint at server side. Because this operation is asynchronous, a callback is registered, so when a success is received, character is added into characters list.

And last View is a composite view of two previous views, acts as a controller between adding a new character and showing all inserted characters:

Initialize function does all required initializations so UI could be refreshed asynchronously. In first two lines we are binding add and reset functions of characters collection to a method. For example each time add function is called, addCharacter is invoked.

Next line is used to populate data to Collection. When fetch is called an HTTP GET to defined endpoint is sent, data is retrieved and Collection's add method is called for each result.

addCharacter function is responsible of creating one View for each character. There is not much secret, we are creating a CharacterView, and appending the result of calling its render method to html element with character-list id.

And finally render function that is responsible of rendering CharacterFormView.

See that page is only loaded first time we access it, subsequent updates are done by DOM manipulations.

To finish I embedded all html file explained here so you can see a global overview of all pieces used. Also feel free to download all Eclipse project. I wish you find this post useful.


Download Code

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

miércoles, diciembre 14, 2011

Elle ne me quitte pas d'un pas, fidèle comme une ombre. Elle m'a suivi ça et là, aux quatres coins du monde. Non, je ne suis jamais seul avec ma solitude (Ma Solitude - Georges Moustaki)



In current post I have uploaded my Devoxx presentation. This year I was at Devoxx as speaker. My presentation was about how to speed up HTML 5 applications, and Javascript and CSS in general, using Aggregation and Minification


Also you can visit two entries of my blog where I talk about same theme.
Links of technologies I talked about:

Finally I want to say thank you to all people who came to watch me, and of course Devoxx folks, for organising such amazing event.

I wish you have discovered a great way to speed up your web applications.

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

viernes, diciembre 09, 2011

Far away, long ago, glowing dim as an Ember, Things my heart use to know, things it yearns to remember (Once upon a December - Anastasia)



You never develop code without version control, why do you develop your database without it? Flyway  is database-independent library for tracking, managing and applying database changes.

Personally I find that using a database migration tool like Flyway is "a must", because covers two scenarios of our software life-cycle:

  • Multiple developers developing an application with continuous integration.
  • Multiple clients each one with different versions of production code.

Let's start with first point. If your project is big enough there will be more than one developer working on it, each one developing a new feature. Each feature may require a database update (adding a new table, a new constraint, ...), so developer creates a .sql file with all required changes.

After each developer finishes its work, these changes are merged into main branch and integration/acceptance tests are executed on test machine. And the problem is obvious which process updates testing database? And how? QA department executes sql files manually? Or we develop a program that executes these updates automatically? And in what order must be executed? Also same problem arises in production environment.

Second point is only applicable if your application is distributed across multiple clients. And at this point the problem is further accentuated because each client may have different software versions. Hence when an update is required by our client (for example because a bug), you should know which database version was installed and what changes must be applied to get expected database.

Don't worry Flyway comes to rescue you, and will help to fix all previous questions. Let me start explaining some features of Flyway that in my opinion make it a good tool.

  • Automatic migration: Flyway will update from any version to the latest version of schema. Flyway can be executed as Command-line (can be used with non JVM environments), Ant script, Maven script (to update integration/acceptance test environments) or within application (when application is starting up).
  • Convention over configuration: Flyway comes with default configuration so no configuration is required to start using.
  • Plain SQL scripts or Java classes: To execute updates, you can use plain SQL files or Java classes for advanced migrations.
  • Highly reliable: safe for cluster environments.
  • Schema clean: Flyway can clean existing schema, so empty installation is produced. 

Conventions to be followed if they are not explicitly modified are:

  • Plain SQL files go to db/migration directory inside src/main/resources structure.
  • Java classes go to db.migration package.
  • Files (SQL and Java) must follow next name convention: V<version>[__description]. Where each version number is separated by dots (.) or underscore (_) and if description is provided, two underscores must proceed. A valid example is V_1_1_0__Update.sql

So let's see Flyway in action. In this application I am going to focus only on how to use Flyway, I am not going to create any DAO, DTO or Controller class, only database migration part.

Imagine we are going to develop a small application using Spring Framework that will allow us registering authors and which books they have written.

First version will contain two tables, Author and Book related with one to many relationship.

First step is registering Flyway into Spring Application Context. Flyway class is the main class and requires a javax.sql.DataSource instance. migrate method is responsible to start migration process.


See that there is no secret. Only be careful because if your project uses JPA or ORM frameworks for persistence, you should configure them to avoid auto creation of tables, because now Flyway is responsible of managing database structure. And because of that, creation of SessionFactory (in case of Hibernate) or EntityManagerFactoryBean( in case of JPA),  should depends on Flyway bean.

Flyway is configured. Each time you start application, it will review if configured datasource requires an update or not.

And now let's write first version of SQL migration. Create db/migration directory into src/main/resources and create a file called V1__Initial_version.sql with next content:


This script creates Author and Book tables with their respective attributes.

And if you run next JUnit both tables are created into database.


Take a look at your console and next log message has appeared:

10:33:49,512  INFO glecode.flyway.core.migration.DbMigrator: 119 - Current schema version: null
10:33:49,516  INFO glecode.flyway.core.migration.DbMigrator: 206 - Migrating to version 1
10:33:49,577 INFO glecode.flyway.core.migration.DbMigrator: 188 - Successfully applied 1 migration (execution time 00:00.085s).


And if you open your database:


Note that Flyway has created a table to annotate all updates that have been executed (SCHEMA_VERSION) and last insert is a "Flyway insert" marking which is the current version.

Then your first version of application is distributed across the world.

And you can start to develop version 1.1.0 of application. For next release, Address table must be added with a relationship to Author.


As done before, create a new SQL file V1_1_0__AddressTable.sql into db/migration folder.


And run next unit test:


your database will be upgraded to version 1.1.0. Also take a look at log messages and database:

11:27:30,149  INFO glecode.flyway.core.migration.DbMigrator: 119 - Current schema version: 1
11:27:30,152  INFO glecode.flyway.core.migration.DbMigrator: 206 - Migrating to version 1.1.0
11:27:30,191 INFO glecode.flyway.core.migration.DbMigrator: 188 - Successfully applied 1 migration (execution time 00:00.053s).



New table is created, and a new entry into SCHEMA_VERSION table is inserted marking that current database version is 1.1.0.

When your 1.1.0 application is distributed to your clients, Flyway will be the responsible of updating their databases without losing data.


Previously I have mentioned that Flyway also supports Java classes for advanced migrations. Let's see how.

Imagine that in your next release, authors can upload their personal photo, and you decide to store as  blob attribute into Author table. The problem resides on already created authors because you should set some data into this attribute. Your marketing department decides that authors inserted prior to this version will contain a photo of Spock,


So now you must alter Author table and moreover update a field with a photo. You can see clearly that for this update you will need something more than a simple SQL file, because you will need to add a new property and updating them with chunk of bytes. This problem could be accomplished using only one Java class but for showing a particularity of Flyway, problem will be treated with one SQL and one Java object.

First of all new SQL script adding a new binary field is created. This new feature will be implemented on version 2.0.0, so script file is named V2_0_0__AddAvatar.sql.


Next step is developing a Java Migration class. Create a new package db.migration on src/main/java. Notice that this class cannot be named V2_0_0_AddAvatar.java because Flyway will try to execute two different migrations with same version, and obviously Flyway will detect a conflict.

To avoid this conflict you can follow many different strategies, but in this case we are going to add a letter as version suffix, so class will be named V2_0_0_A__AddAvatar.java instead of V2_0_0__AddAvatar.java.


Before run previous unit test, open testdb.script file and add next line just under SET SCHEMA PUBLIC command.

INSERT INTO AUTHOR(ID, FIRSTNAME, LASTNAME, BIRTHDATE) VALUES(1, 'Alex', 'Soto', null);

And running unit test, next lines are logged:


20:21:18,032  INFO glecode.flyway.core.migration.DbMigrator: 119 - Current schema version: 1.1.0
20:21:18,035  INFO glecode.flyway.core.migration.DbMigrator: 206 - Migrating to version 2.0.0
20:21:18,088  INFO glecode.flyway.core.migration.DbMigrator: 206 - Migrating to version 2.0.0.A
20:21:18,114 INFO glecode.flyway.core.migration.DbMigrator: 190 - Successfully applied 2 migrations (execution time 00:00.094s).

And if you open updated database, next lines are added:


See how all previous authors have avatar column with data.

Note that now you have not to worry about database migrations, your application is packaged and delivered to all your clients regardless of the version they had installed; Flyway will execute only required migration files depending on installed version.

If you are not using Spring, you can update your database using Flyway-Maven-Plugin. Next piece of pom shows you how to execute migration during test-compile phase. By default plugin is executed during pre-integration-test phase.


Thanks of Maven plugin, we can configure our continuous integration system so all environments (test, production,...) would be updated during deployment of application.

I wish Flyway will help you make better life as developer.



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


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