martes, marzo 06, 2012

Keep 'em laughing as you go, Just remember that the last laugh is on you, And always look on the bright side of life..., Always look on the right side of life... (Always Look on the Bright Side of Life - Mony Python)




Integration tests are kind of tests which individual modules are combined and tested as a whole. Moreover integration tests might use system dependent values, accessing external systems like file system, database, web services, ..., and testing multiple aspects of one test case. We can say it is a high-level test.

This differs from unit test where only a single component is tested. Unit tests runs in isolation, mocking-out external components or using in-memory database in case of DAO layers. A unit test might be:
  • Repeatable.
  • Consistent.
  • In Memory.
  • Fast.
  • Self-validating.
  • Testing single concept

The problem when we are writing tests, is how to test rare (or untypical) conditions like "No disk space" in case of accessing file system, or "Connection lost" when executing a database query.

In unit testing this is not a problem you can mock up that component (database connection or filesystem access), generating required output like throwing IOException.

The problem becomes "harder" with integration tests. It would be strange to mock a component, when what you really want to do is validate the real system. So arrived at this point I see two possibilities:
  • Creating a partial mock.
  • Using fault injection.
In this post I am going to show you how to use fault injection approach to test unusual erroneous situations. 

Fault injection is a technique which involves changing application code under test at specific locations. This modifications will introduce faults on error handling code paths which otherwise would rarely be followed.

I am going to talk about how to use fault injection using Byteman in a JUnit test, and run it with Maven.

Let's start coding. Imagine you need to write a backup module, which shall save a string into a local file, but if hard disk is full (IOException is thrown), content shall be sent to remote server.

First we are going to code a class that writes content into file.



Next class, would be the one that sends data through socket but will not be shown, because it is not necessary for this example.

And finally the backup service responsible of managing described behavior.

And now testing time. First of all a brief introduction to Byteman.

Byteman is a tool which allows you to insert/modify code into an application at runtime. These modifications can be used to inject code on your compiled application causing unusual or unexpected operations (aka Fault Injection).

Byteman uses a clear, simple scripting language, based on a formalism called Event Condition Action (ECA) rules to specify where, when and how the original Java code should be transformed.

An example of ECA script is:

But Byteman also supports annotations. And in my opinion, annotations are a better approach than script file, because only watching your test case you can understand what you are exactly testing. If not you should switch context from unit class to script file to understand what are you testing.

So let's create an integration test that that validates that when IOException is thrown while writing content into disk, data is sent to a server.


See that BMUnitRunner (a special jUnit runner that comes with Byteman) is required.

First test called aFileWithContentShouldBeCreated is a standard test that writes Hello world into backup file.

But the second one dataShouldBeSentToServerInCaseOfIOException, has BMRule annotation which will contain when, where and what code should be injected. First parameter is the name of the rule, in this case a description of what we are going to do (throwing an IOException). Next attributes, targetClass and targetMethod configure when injected code should be added. In this case when FileUtils.createFileWithContent method is called. Next attribute targetLocation is location where code is inserted, and in our case is where createFileWithContent method calls write method of BufferedWriter. And finally what to do that obviously in this test is throwing an IOException.

So now you can go to your IDE and run them, and all tests should pass, but if you run through Maven using Surefire plugin, test will not work. To use Byteman with Maven, Surefire plugin should be configured in a specific way.


First important thing is adding tools jar as dependency. This jar provides classes needed in order to dynamically install the Byteman agent.

In Surefire plugin configuration is important to set useManifestOnlyJar to false to ensure that the Byteman jar appears in the classpath of the test JVM.  Also see that we are defining empty environment variables (BYTEMAN_HOME and org.jboss.byteman.home). This is because when it loads the agent the BMUnit package will use environment variable BYTEMAN_HOME or System property org.jboss.byteman.home to locate byteman.jar but only if it is a non-empty string. Otherwise it scans the classpath to locate the jar. Because we want to ensure that jar added on dependency section is used, we are overriding any other configuration present on system.

And now you can run mvn clean test and two tests are successful too.

See that Byteman opens a new world into how we are writing our integration tests, now we can test in an easy way unusual exceptions like Communications Error, Input/Output Exceptions or Out Of Memory Error. Moreover because we are not mocking FileUtils, we are executing real code; for example in our second test, we are running a few lines of FileUtils object until write method is reached. If we had mocked-up FileUtils class, these lines would not be executed. Thanks of using fault injection our code coverage is improved.

Byteman is more than what I have shown you, it also has built-ins designed for testing in multithreaded environments, parameter binding, and an amount of location specifiers, to cite a few things.

I wish you have found this post useful and help you testing rare conditions of your classes.

Download Code
Music: http://www.youtube.com/watch?v=WlBiLNN1NhQ

lunes, febrero 27, 2012

For everything I long to do, No matter when or where or who, Has one thing in common too, It's a, it's a, it's a, it's a sin (It's a Sin - Pet Shop Boys)-



Usually when you start a new project, it will contain several subprojects, for example one with core funcionalities, another one with user interface, or acceptance tests could be another one.

In next screen-cast post I am going to show you how to create a multimodule Maven project using M2 Eclipse plugin.

This is the first video I have done, I wish you find it really useful, and I will try to switch between blog posts and video posts.


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