Friday, November 30, 2012

How to start a thread on JBoss startup

I recently had to initiate a thread to read mails on server start-up. This had to run after the application was deployed since the thread class depended on a few classes of the application. Note that we are running on JBoss 4.2.3 currently, so i am not sure how this works with latest versions of JBoss.

You need to create a folder called deploy.last within your deployment directory (e.g : default configuration). Then we first create a normal interface/implementation as follows;

public interface EmailRetrieverInvokerServiceMBean {

 void start() throws Exception;

 void stop();

public class EmailRetrieverInvokerService implements
  EmailRetrieverInvokerServiceMBean {

 public void start() throws Exception {

  MailRetriever mailRetriever= new MailRetriever();

 public void stop() {
            MailRetriever.START_STOP_FLAG = true;


Just a normal interface and implementation. Note that the start() method will be called when we deploy the application. The MailRetriever class has an implementation as follows;

public class MailRetriever extends Thread {

   public static boolean START_STOP_FLAG = false;

    public void run() {
       "MailRetriever started....");

        //Until the flag is not set to true, this thread will keep running
        while (!START_STOP_FLAG) {
            try {
             //Do mail reading

             //Then sleep for a specified time until the next iteration
                Thread.sleep(1000 * 60 * mailPollingDelay);
            } catch (Exception ex) {
                log.error("" + ex.getMessage(), ex);
                //Exception handling and thread respawning should be handled

This is the thread that will be started when the start() method of our MBean implementation class is invoked. The thread will continue to run until the boolean flag is set to true. Then to wire it up, you need to specify a jboss-service.xml which should go in the META-INF directory when building your distribution. Let us have a look at what that looks like;

<?xml version="1.0" encoding="UTF-8"?>

   <mbean code="com.service.EmailRetrieverInvokerService"

Within this xml we define the fully qualified path to our interface class that we defined and give a name where we can access our implementation as a normal MBean definition. If you are using a maven build then all you need to do is create this XML file and put it under src/main/resources/META-INF. This will put it under the META-INF during the distribution creation stage.

As a last step what you need to do is bundle everything up as a service archieve (SAR). You can achieve this using maven as follows;

<project xmlns="" xmlns:xsi=""
 <name>Mail Reader</name>






A service archive will be created for you. Then it is just a matter of copying the SAR file onto your deploy.last which you created within the jboss deployment directory. This will guarantee that the thread will run after all other components are deployed within jboss.

That's it. If you have any queries, comments, suggestions, please leave them which is much apprecaited as always.

Thank you for reading and have a great day!!

Monday, November 26, 2012

How cool is integration testing with Spring+Hibernate

I am guilty of not writing integration testing (At least for database related transactions) up until now. So in order to eradicate the guilt i read up on how one can achieve this with minimal effort during the weekend. Came up with a small example depicting how to achieve this with ease using Spring and Hibernate. With integration testing, you can test your DAO(Data access object) layer without ever having to deploy the application. For me this is a huge plus since now i can even test my criteria's, named queries and the sort without having to run the application.

There is a property in hibernate that allows you to specify an sql script to run when the Session factory is initialized. With this, i can now populate tables with data that required by my DAO layer. The property is as follows;

 <prop key="hibernate.hbm2ddl.import_files">import.sql</prop>

According to the hibernate documentation, you can have many comma separated sql scripts.One gotcha here is that you cannot create tables using the script. Because the schema needs to be created first in order for the script to run. Even if you issue a create table statement within the script, this is ignored when executing the script as i saw it.

Let me first show you the DAO class i am going to test;

 package com.unittest.session.example1.dao;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.unittest.session.example1.domain.Employee;

@Transactional(propagation = Propagation.REQUIRED)
public interface EmployeeDAO {

 public Long createEmployee(Employee emp);
 public Employee getEmployeeById(Long id);

package com.unittest.session.example1.dao.hibernate;


import com.unittest.session.example1.dao.EmployeeDAO;
import com.unittest.session.example1.domain.Employee;

public class EmployeeHibernateDAOImpl extends HibernateDaoSupport implements
  EmployeeDAO {

 public Long createEmployee(Employee emp) {
  return emp.getEmpId();

 public Employee getEmployeeById(Long id) {
  return getHibernateTemplate().get(Employee.class, id);

Nothing major, just a simple DAO with two methods where one is to persist and one is to retrieve. For me to test the retrieval method i need to populate the Employee table with some data. This is where the import sql script which was explained before comes into play. The import.sql file is as follows;

 insert into Employee (empId,emp_name) values (1,'Emp test');

This is just a basic script in which i am inserting one record to the employee table. Note again here that the employee table should be created through the hibernate auto create DDL option in order for the sql script to run. More info can be found here. Also the import.sql script in my instance is within the classpath. This is required in order for it to be picked up to be executed when the Session factory is created.

Next up let us see how easy it is to run integration tests with Spring.

 package com.unittest.session.example1.dao.hibernate;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;

import com.unittest.session.example1.dao.EmployeeDAO;
import com.unittest.session.example1.domain.Employee;

public class EmployeeHibernateDAOImplTest {

 private EmployeeDAO employeeDAO;
 public void testGetEmployeeById() {
  Employee emp = employeeDAO.getEmployeeById(1L);
 public void testCreateEmployee()
  Employee emp = new Employee();
  Long key = employeeDAO.createEmployee(emp);
  assertEquals(2L, key.longValue());


A few things to note here is that you need to instruct to run the test within a Spring context. We use the SpringJUnit4ClassRunner for this. Also the transction attribute is set to defaultRollback=true. Note that with MySQL, for this to work, your tables must have the InnoDB engine set as the MyISAM engine does not support transactions.

And finally i present the spring configuration which wires everything up;

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:xsi="" xmlns:aop=""
 xmlns:tx="" xmlns:context=""

 <context:component-scan base-package="com.unittest.session.example1" />
 <context:annotation-config />

 <tx:annotation-driven />

 <bean id="sessionFactory"
  <property name="packagesToScan">
  <property name="hibernateProperties">
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
    <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/hbmex1</prop>
    <prop key="hibernate.connection.username">root</prop>
    <prop key="hibernate.connection.password">password</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <!-- -->
    <prop key="">create</prop>
    <prop key="hibernate.hbm2ddl.import_files">import.sql</prop>

 <bean id="empDAO"
  <property name="sessionFactory" ref="sessionFactory" />

 <bean id="transactionManager"
  <property name="sessionFactory" ref="sessionFactory" />


That is about it. Personally i would much rather use a more light weight in-memory database such as hsqldb in order to run my integration tests.

Here is the eclipse project for anyone who would like to run the program and try it out.