Spring ROO and an Idea

 I have being playing around with Spring ROO. It is a project with great potential and the facility to integrate seamlessly with maven is an added advantage.

There are many tutorials on “An enterprise Java Application in 10 minutes with ROO”, this is not a tutorial but rather looks at enhancing ROO for use in projects The reader who is unfamiliar with Spring ROO is advised to look at .http://www.springsource.org/roo for an introduction to Spring ROO.

How one draw back that seems to plague Spring ROO is the lack of sorting and filtering functionality on the web frontend lists. In other words how do we sort tabular data? This question  is obviously an important one and vital to many web applications.

An answer that we could employ is displaytag a little known but help tag library that could assist us to sort and export tabular data to excel and csv files.

In the generated list.jspx we have:


If we had to use display tag instead we would have :

Now we could actually make changes to the code generation and the annotations to alter and create our default JSPs to use the display tag. However for this exercise we can assume that we did it by hand and produced the above.

The result when running the application with mvn tomcat:run we have in our browser( ):

We can even extend the above to use displaytags exporting abilities to export to excel:

Posted in Uncategorized | 4 Comments

Digesting Struts 2 and Dojo

Digesting Struts 2 and Dojo

I was playing around with Struts 2 and Ajax mainly Dojo. Now how would one wire a struts action to return Dojo – JavaScript object? We will examine this below and setup a sample app that will use Struts and Dojo. We offer this as an alternative to JSON. The advantage of this over JSON is that an exist Struts 2 application could still generate JavaScript Objects without interfering with the Java classes. So where as when JSON is used your program must return a JSON object here your program can return normal data to pages and from these JavaScript objects can be constructed and used.

We will load a user’s information on selection of the user and dynamically append the user’s details.


Once the user is selected we will have his information dynamically appended to the screen as below:


The way this application will function is that struts will on success return a result to a JSP that will then dynamically have the XML created. The dojo.io.bind will then read in this XML and generate a JavaScript object with which we can use to update the page. We will start by creating the project for the application in Eclipse (Similar process for Netbeans)


The classes look like:


package struts2dojoexample.action;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.struts2.ServletActionContext;

import org.apache.struts2.interceptor.ServletRequestAware;

import org.apache.struts2.interceptor.ServletResponseAware;


import struts2dojoexample.pojo.User;


import com.opensymphony.xwork2.ActionSupport;


public class LoadUserAction extends ActionSupport implements ServletRequestAware,

ServletResponseAware {


private String user;

private String username;

private String password;

private HttpServletRequest request;

private HttpServletResponse response;


public String execute() {

User user1 = new User();




user1.setStreetAddress(“On Earth”);


// Put the DTO in request so we can use it to render XML in the JSP.

getServletRequest().setAttribute(“user”, user1);

return SUCCESS;



public void setUsername(String username) {

this.username = username;



public String getUsername() {

return username;



public void setPassword(String password) {

this.password = password;



public String getPassword() {

return password;



public void setUser(String user) {

this.user = user;



public String getUser() {

return user;




public void setServletRequest(HttpServletRequest request){

this.request = request;



public HttpServletRequest getServletRequest(){

return request;



public void setServletResponse(HttpServletResponse response){

this.response = response;



public HttpServletResponse getServletResponse(){

return response;






As you can see in Struts 2 you can implement ServletRequestAware and ServletResponseAware

When these are implemented we now have access to our session.


package struts2dojoexample.pojo;


import java.lang.reflect.Field;


public class User {


private String username;

private String password;

private String surname;

private String emailAddress;

private String streetAddress;


public void setUsername(String username) {

this.username = username;



public String getUsername() {

return username;



public void setPassword(String password) {

this.password = password;



public String getPassword() {

return password;



public void setSurname(String surname) {

this.surname = surname;



public String getSurname() {

return surname;



public void setEmailAddress(String emailAddress) {

this.emailAddress = emailAddress;



public String getEmailAddress() {

return emailAddress;



public void setStreetAddress(String streetAddress) {

this.streetAddress = streetAddress;



public String getStreetAddress() {

return streetAddress;



public String getAsXML(){

StringBuffer sb = new StringBuffer(512);

sb.append(“<user username=\”” + username + “\” “);

sb.append(“surname=\”” + surname + “\” “);

sb.append(“emailAddress=\”” + emailAddress + “\” “);

sb.append(“streetAddress=\”” + streetAddress + “\”>\n”);


return sb.toString();



* Overriden toString method.


* @return A reflexivelybuilt string representation of this bean.


public String toString() {


String str = null;

StringBuffer sb = new StringBuffer(1000);

sb.append(“[“ + super.toString() + “]={“);

boolean firstPropertyDisplayed = false;

try {

Field[] fields = this.getClass().getDeclaredFields();

for (int i = 0; i < fields.length; i++) {

if (firstPropertyDisplayed) {

sb.append(“, “);

} else {

firstPropertyDisplayed = true;


sb.append(fields[i].getName() + “=” + fields[i].get(this));



str = sb.toString().trim();

} catch (IllegalAccessException iae) {



return str;


} // End toString().



Next we have the web.xml:





<?xml version=“1.0” encoding=“UTF-8”?>


<web-app version=“2.4” xmlns=http://java.sun.com/xml/ns/j2ee&#8221; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&#8221;>















<!– Session timeout config. –>





<!– Welcome file config. –>






The struts.xml

<?xml version=“1.0” encoding=“UTF-8” ?>


“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”





<constant name=“struts.devMode” value=“true” />


<package name=“default” namespace=“/” extends=“struts-default”>

<action name=“LoadUserAction” class=“struts2dojoexample.action.LoadUserAction”>

<result name=“success”>/User.jsp</result>





The javascript files are list below:


We have the ControlEvents.js this is where we control the events the user creates like the select list drop down menu.

Dojo.js is the dojo toolkit downloadable from http://www.dojotoolkit.org/

User.js is the script file container the user object in JavaScript. In the ControlEvents.js we use the JSDigester that is provided by the JavaWebparts tags. This enables us to generated JavaScript objects.

ControlEvents.js looks like this:


var user = null;

var aconsole = null;

// This function is called when the User dropdown selection changes.

function loadUser() {

// If an operation is in progress, usually involving the server, don’t do it.

//if (processing) { return false; }

// Get name of selected collection.

var username =document.getElementById(“userslist”).value;

// Ignore the first item, our “dummy” collection.

if (username == “none”) {

return false;


// Make AJAX call.


url: “LoadUserAction.action”,

content: {user: username},

error: function(type, errObj) { alert(“Error”); },

load: function(type, data, evt) {

// Now that we have received back the XML describing the collection,

// we’ll use JSDigester to parse it.

var jsDigester = new JSDigester();

jsDigester.addObjectCreate(“user”, “User”);


user = jsDigester.parse(data);


if (aconsole != null ) {

removeAllChildren ( aconsole );


var div = document.createElement(“p”);

var txt=document.createTextNode(“Name: “ +user.username );

div.appendChild ( txt );

txt=document.createTextNode(“Surname: “ +user.surname );

var div1 = document.createElement(“p”);

div1.appendChild ( txt );

txt=document.createTextNode(“Email Address: “ +user.emailAddress );

var div2 = document.createElement(“p”);

div2.appendChild ( txt );

txt=document.createTextNode(“Street Address: “ +user.streetAddress );

var div3 = document.createElement(“p”);

div3.appendChild ( txt );






mimetype: “text/plain”,

transport: “XMLHTTPTransport”




function removeAllChildren( node ){

var childCount = node.childNodes.length;

for ( var count = 1; count <= childCount; count++) {

node.removeChild ( node.childNodes[0] );




User.js :

// User object.

function User() {

this.username = null;

this.surname = null;

this.emailAddress = null;

this.streetAddress = null;


User.prototype.setUsername = function(inName) {

this.username = inName;


User.prototype.getUsername = function() {

return this.username;


User.prototype.setSurname = function(inSurname) {

this.surname = inSurname;


User.prototype.getSurname = function() {

return this.surname;


User.prototype.setEmailAddress = function(inEmailAddress) {

this.emailAddress = inEmailAddress;


User.prototype.getEmailAddress = function() {

return this.emailAddress;


User.prototype.setStreetAddress = function(inStreetAddress) {

this.streetAddress = inStreetAddress;


User.prototype.getStreetAddress = function() {

return this.streetAddress;


User.prototype.toString = function() {

return “User=[username=” + this.username +

“,surname=” + this.surname +

“,emailAddress=” + this.emailAddress + “,streetAddress=” + this.streetAddress + “]”;



The libraries:



There some additional libraries for expansion of this application like the MySQL driver for Database connectivity to MySQL.

There you are it runs. So we managed to dynamically update a page and translate our Java in to JavaScript. This example could be extended and enhanced to embrace the vast functionality of the Dojo Toolkit.








Posted in Computers and Internet, Java programming, JavaScript | Leave a comment

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Posted in Uncategorized | 1 Comment

Dating, Where clauses and Hibernate

I recently ran into an interesting problem involving hibernate and dates across different database systems mainly Microsoft SQL 2008 and IBM Informix.

It appears that in HQL queries you can use Informix’s today for obtaining the current date and time:

query = session.createQuery();

String whereClause = "from myTable where myDateColumn > today -10";

This query finds the today 10 days from the current time.

When we run the query as below:

List<MyTable> myTableResults = query.list();

THis executes successfully in IBM Informix but in MSSQL we get the following error:

column today not found

So what do we do now? it appears that NOW() does not work.

Looking through various information and issues on the internet and hibernate tutorial and forums I found that hibernate can support certain functions of a specific database. This ties in with the hibernate dialect and JDBC driver.

I found that GETDATE() works within the where clause. So updating the above to:

String whereClause = "from myTable where myDateColumn > GETDATE() -10";

This worked well. So this raises more questions. How can we in general see which functions the RDMS provides that hibernate will support in its HQL queries – the where clause?

It should be noted that in the select part of the query we have more freedom. As dates can be retrieved.

Also it should be noticed that MS SQL has a newer driver sqljdbc4.jar and sqljdbc.jar. The difference in these two is quite big when we consider dates. For example SQL 2005 had fewer date types then SQl 2008. So this leads to problems when using the older driver(sqljdbc.jar) on SQL 2008.


Another important insight is in the Dialect class there exists the method Dialect.getCurrentTimestampSQLFunctionName() which can give us the database-specific SQL function for retrieving the current timestamp.

Also we cannot use Java’s

new Date() in the where clause part of the query as this does not always work. The format the date will be in might not translate well into a string. We could try parameters in queries using AbstractQueryImpl.setParameter(String name, Object val).

However a problem could arise when using Java’s new Date() in as a paramter in a query as opposed to using a database function, this problem would be that time from Java would be based on the application as opposed to the database server itself. So if the two are at different locations and setup differently we could have problems.

Hence we can make our application cater for different types of RDMS systems based on the type and hence use various functions to aid development.

Hence when dealing with date types one has to be cautious specially if developing on an open source RDMS and then using a commerial RDMS. This saves on licencing but when deploy issues like dates can give problems!

Posted in Computers and Internet | Leave a comment

Nice and Naughty Transactions in Hibernate and Spring

I came across a very interesting fact about Spring transaction management.


Spring provides us with two ways of handling transaction

1) Using proxies,

2) Using DI through the getTemplate() method.


Now what happens when we consider 1) we mean:

Declaring in an XML file the transactionManager and transactionTemplate bean:


<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" singleton="true">

            <property name="sessionFactory">

                  <ref bean="sessionFactory" />



      <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" singleton="false">

            <property name="transactionManager">

                  <ref bean="transactionManager" />




Then we use proxies and provide:


<bean id="myTableManagerTx" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" singleton="true" lazy-init="true">

            <property name="transactionManager">

                  <ref bean="transactionManager"/>


            <property name="target">

                  <ref bean="myTableManagerImpl"/>


            <property name="transactionAttributes">





            <prop key=" *">PROPAGATION_NOT_SUPPORTED,readOnly</prop>




            <property name="preInterceptors">


                        <ref bean="callMonitor"/>





With the use of interceptors we can now use doInHibernate() and have transaction support without any extra coding:


protected Object updateObject(final Context ctx, final Object o) {

            return getHibernateTemplate().execute(new HibernateCallback() {


                  public Object doInHibernate(Session session) throws HibernateException, SQLException {

                        return update(ctx, session, o);





However we can use alternative 2)


            try {

                  TransactionTemplate transactionTemplate = SpringFactory.getTransactionTemplate( TransactionDefinition.ISOLATION_READ_COMMITTED, TransactionDefinition.PROPAGATION_REQUIRED, false );

                  return ( List )transactionTemplate.execute( new TransactionCallback() {


                        public Object doInTransaction( TransactionStatus transactionStatus ) {

                              return getMyTableDAO().find( ctx, myId );


                  } );

            } catch( Exception e ) {

                  log.error( e.getMessage(), e );                



Here we are programmatically creating a transaction based on Spring’s DI.


What happens if we use both together? That is 1) and 2) in an application we could have errors like:


Session cannot be closed!


This is because we are using proxies for transactions and also programmatically controlling transactions. If our TransactionDefinition fields : PROPAGATION_REQUIRED, PROPAGATION_NEVER, PROPAGATION_NOT_SUPPORTED, PROPAGATION_REQUIRES_NEW etc are not adjusted and used correctly we could have problems and errors with sessions being closed prematurely and incorrectly controlled. Also the HibernateTemplate controls the sessions for us. As stated in the Spring documentation:

The central method is execute, supporting Hibernate access code implementing the HibernateCallback interface. It provides Hibernate Session handling such that neither the HibernateCallback implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions. For typical single step actions, there are various convenience methods (find, load, saveOrUpdate, delete).

 This can lead to sessions not being closed properly and resources not been freed and hence lead to memory leaks(Which I have experienced!).


Final word of advice is: carefully watch your transactions!


Posted in Computers and Internet | Leave a comment

JavaAssist and CGLIB Hibernate and Spring

I recently came across some legacy code that brought to mind some interesting aspects of Spring and Hibernate. This involves the code generation libaray CGLIB.

Javassist is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it.

Cglib It is used to extend JAVA classes and implements interfaces at runtime.

Hibernate v 3.2 and below utilize CGLIB to generate proxies for the database connections. Hibernate v3.3 and above use Javassist by default.

The way CGLIB (Older version 2.1.1 this should be fixed in new versions) generates proxies causes the memory to contain a lot of used but referenced objects hence increasing the size of the heap. So much so that the heap will grow until we get a Out Of Memory Error. This happens just before a proxy is instantiated when using the CGLIBLazyInitializer.getProxy().  

Please refer to http://opensource.atlassian.com/projects/hibernate/browse/HHH-2481 for more information. First and formost Spring managed Hibernate sessions and transactions can be very powerful and have advantages such as cleaning up of sessions.  However combining Spring with Hibernate v3.2 and below leads to memory mismanagement due to the CGLIB which has some internal issues.

If you are however stuck to modifying or maintaining applications that are utilizing CGLIB you could add the following code snipplet to improve performance and fix the above issue:

cfg.setListeners("load", new LoadEventListener [] {new DefaultLoadEventListener(), new LoadEventListener() {

            public void onLoad(LoadEvent event, LoadType loadType) throws HibernateException {

                Object obj = event.getResult();

                if (obj instanceof HibernateProxy) {






The cfg variable is the configuration variable of hibernate.

In addition when upgrading to Hibernate v3.5 be aware that it implements strick checks on whether SQL queries are well formed.

Having implemented Hibernate v3.5 some of my memory issues were gone and the application was left in a stable state.


Posted in Computers and Internet | Leave a comment

Deep Copying, Shallow Copying and Reflection

Deep Copying, Shallow Copying and Reflection Part 1

Its been quite busy over the last month. I have a long blogOpen-mouthed smileI have been looking at deep and shallow copying in Java. The Object.clone() method performs shallow copying.

That is if object A has a object B(by composition). Then our class would look something like the following.

public class A{

B b;

someMethod(B b){

this.b = b;



class B{

//methods and variables of its own


When we look at the above class and clone an instance of A we would perform the following:

A a= //some value that is an instance of A;

A newA = a.clone();

However a.clone() makes an identical copy of the object that a refers to but not copies of the objects that are composed in it like b! So programmatically this looks like:

(newA.b).equals(a.b) = true!!

newA and a share the same b hence they have references to the same instance of B.

How can this be cured? Manually we can clone b and say:

newA.b = (a.b).clone();

This works however we want to be able to do this in an automatic way. Imagine performing this task manually for larger classes with references to many objects!

We can use reflection to create one such tool. We need a tool that must by the use of reflection find out which objects are composed in a class and clone them and continue this for those objects until we reach a class that has no more objects composed in it or it is composed of primitives. This sounds like recursion.

This seems well but there are problems:

  1. If an object has overloaded constructors which one will we know was used to create the instance of the object that we want to copy?

  2. What about private members that prohibit access from the outside?

The solution would be to use any public constructor and use default values for the arguments then create a new instance. Then we can set the values of the members from the object we want to copy. To solve this we know that Java Reflection API allows us access to even private members of a class so problem 2) is solved.

What we then need to do is to create a program that can recursively examine a class analyse the members clone them and continue doing so for the whole class.

Now a great problem comes to mind: What if the members of the class have objects that themselves have other objects by composition? So we cannot use the Object.clone() method!

The solution to this lies in being able to perform recursion up to a certain point where we can then stop and where the members of the objects have a structure that is well know and can be manipulated for our purposes.

So we come to one set of classes that form a very important basis of the Java language- The wrapper classes and their primitives.

Use the facts that we know about the primitive and the wrapper classes we could make the following assumption

Primitives and Wrappers form the basis of many classes.

Of course we need the String class as well as many other classes that form a concrete base.

So we can generalise this idea into a concept of basis classes. These have

well known structures like the wrappers and String class we know how to create replicas.

Turning all the above ideas into code We will have the following. I am assuming familiarity with the Reflection API.

Clone Utility

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Modifier;

import java.util.LinkedList;

import java.util.List;

public class CloneUtility<T> {

public enum PrimitiveType {



public T cloneObject(T objectToBeCloned) {

T newT;

Class clazz = objectToBeCloned.getClass();

Constructor[] constructors = getConstructorOfClass(clazz);

if (constructors.length > 0) {

newT = (T) createNewObject(clazz, constructors[0]);

} else {

newT = (T) createNewObject(clazz, null);


Field[] fields = getInstanceVariables(newT.getClass());

copyVariables(fields, objectToBeCloned, newT);

return newT;


public Object createNewObject(Class clazz, Constructor constructor) {

Object newObject = null;

try {

if (constructor != null) {

Object[] parameters = constructor.getParameterTypes();

Object[] parametersNull = null;

if (parameters.length > 0) {

parametersNull = new Object[parameters.length];

if (parametersNull.length > 0)

newObject = constructor.newInstance(parametersNull);


if (newObject == null)

newObject = clazz.newInstance();

} else {

newObject = clazz.newInstance();


} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block


} catch (InstantiationException e) {

// TODO Auto-generated catch block


} catch (IllegalAccessException e) {

// TODO Auto-generated catch block


} catch (InvocationTargetException e) {

// TODO Auto-generated catch block



return newObject;


public Constructor[] getConstructorOfClass(Class clazz) {

Constructor[] constructors = clazz.getConstructors();

return constructors;


public Field[] getInstanceVariables(Class cls) {

List accum = new LinkedList();

while (cls != null) {

Field[] fields = cls.getDeclaredFields();

for (int i = 0; i < fields.length; i++) {

if (!Modifier.isStatic(fields[i].getModifiers())) {




cls = cls.getSuperclass();


Field[] retvalue = new Field[accum.size()];

return (Field[]) accum.toArray(retvalue);


public void copyVariables(Field[] fields, T objectFrom, T objectTo) {

Object fieldToo = null;

Object obj = null;

Object objToo = null;

int type = 1;

try {

for (Field field : fields) {

Class clazzTo = field.getType();

if (clazzTo.isPrimitive()) {

obj = field.get(objectFrom);

Object[] result = checkPrimitiveType(field, obj, 1);

while (result == null && type <= 8) {

result = checkPrimitiveType(field, obj, type++);


if (result.length != 0) {

fieldToo = result[1];

field.set(objectTo, fieldToo);


} else {

obj = field.get(objectFrom);

CloneUtility cloneUtility = new CloneUtility();

fieldToo = cloneUtility.cloneObject(obj);

field.set(objectTo, fieldToo);



} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block


} catch (IllegalAccessException e) {

// TODO Auto-generated catch block


} catch (SecurityException e) {

// TODO Auto-generated catch block




public Object[] checkPrimitiveType(Field field, Object objectFrom, int type) {

Object[] result = new Object[2];

Constructor constructorTo = null;

try {

Object obj = objectFrom;

Class[] parameterTypes = new Class[1];

// Class types for primitives

Class intClass = Class.forName("java.lang.Integer");

Class shortClass = Class.forName("java.lang.Short");

Class charClass = Class.forName("java.lang.Character");

Class byteClass = Class.forName("java.lang.Byte");

Class longClass = Class.forName("java.lang.Long");

Class booleanClass = Class.forName("java.lang.Boolean");

Class floatClass = Class.forName("java.lang.Float");

Class doubleClass = Class.forName("java.lang.Double");

switch (type) {

case 1:

parameterTypes[0] = Integer.TYPE;

constructorTo = intClass.getConstructor(parameterTypes);

result[0] = PrimitiveType.INTEGER;


case 2:

parameterTypes[0] = Short.TYPE;

constructorTo = shortClass.getConstructor(parameterTypes);

result[0] = PrimitiveType.SHORT;


case 3:

parameterTypes[0] = Character.TYPE;

constructorTo = charClass.getConstructor(parameterTypes);

result[0] = PrimitiveType.CHAR;


case 4:

parameterTypes[0] = Float.TYPE;

constructorTo = floatClass.getConstructor(parameterTypes);

result[0] = PrimitiveType.FLOAT;


case 5:

parameterTypes[0] = Byte.TYPE;

constructorTo = byteClass.getConstructor(parameterTypes);

result[0] = PrimitiveType.BYTE;


case 6:

parameterTypes[0] = Boolean.TYPE;

constructorTo = booleanClass.getConstructor(parameterTypes);

result[0] = PrimitiveType.BOOLEAN;


case 7:

parameterTypes[0] = Double.TYPE;

constructorTo = doubleClass.getConstructor(parameterTypes);

result[0] = PrimitiveType.DOUBLE;


case 8:

parameterTypes[0] = Long.TYPE;

constructorTo = longClass.getConstructor(parameterTypes);

result[0] = PrimitiveType.LONG;



if (constructorTo != null && obj != null) {

Object fieldToo = constructorTo.newInstance(obj);

result[1] = fieldToo;

return result;


} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block


} catch (InstantiationException e) {

// TODO Auto-generated catch block


} catch (IllegalAccessException e) {

// TODO Auto-generated catch block


} catch (SecurityException e) {

// TODO Auto-generated catch block


} catch (NoSuchMethodException e) {

// checkPrimitiveType(field,objectFrom,type+1);

result = null;

} catch (IllegalArgumentException e) {

// checkPrimitiveType(field,objectFrom,type+1);

result = null;

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block



return result;



Next we move on to Part2

Posted in Computers and Internet | Leave a comment