Wednesday, June 30, 2010

Hibernate's AnnotationSessionFactoryBean

These days im a bit busy with creating a new framework to be used for development of enterprise projects. I was using the hibernate template to deal with all database related activity and used the HibernateDAOSupport class as well. When configuring it at first i found it to be very cumbersome because you have to specify each and every annotated class within its configuration as such;


<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.mypackage.domain.Person</value>
</list>
</property>

</bean>


First i thought i found use xDoclet and generate this XML through the build process. But as I Googled up on the same i found that there was another way to do it in just one line which would scna all your sub packages. You just have to give your base package name and that its. Following is the re factored AnnotationSessionFactoryBean configuration;


<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.mypackage.**.*</value>
</list>
</property>

</bean>


Thats it. Now you can put your domain classes anywhere within your project and this will scan all your entities.

Wednesday, June 23, 2010

Some HTML Tags We Rarely Use

Found this article on some of the HTML tags we rarely use which is useful in come occasions. Check this out.

Friday, June 18, 2010

Java Script Charting Framework

Found this site on dZone giving developers a powerful java script charting framework to work with.. I will definitely be trying this out as it feels much richer than JFree Chart...

Thursday, June 17, 2010

AOP with Spring

One thing to note about Spring AOP is that it does runtime weaving of aspects compared to AspectJ's compile time weaving. The good thing is you can define your aspects as java classes without having to learn yet another expression language if you were to use AspectJ. Ok here i just put together a small application to show how easy it is to set up aspects within your Spring applcation.

First of all we will start with defining our service class;


public class ChildService {

public void advice(){
System.out.println("Ok!!!!");
}
}



This class simply defines one method called advice(). Our intention is to weave into the advice method of ChildService and advice the child before and after. Hence we will be using @Before and @After annotations within our Aspect to handle this. If you do remember if we were to do this without annotations we have to implement BeforeAdvice, AfterAdvice within our Aspect class. But with annotations its a mere fact of defining a class and annotating it.

Following is the Aspect which will weave into the advice() method of the ChildService class.


import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class AdviceChild {

@Pointcut("execution(* *.advice(..))")
public void adviceChild(){}

@Before("adviceChild()")
public void beforeAdvicing(){
System.out.println("Listen Up!!!!");
}

@After("adviceChild()")
public void afterAdvicing(){
System.out.println("You got that ?");
}


}


As you can see here i have first annotated the advice class with @Aspect. This tells the Spring container that this is an aspect. Then we denote out point cut to tell at what point we are to use this Aspect. The pointcut is defined to weave into methods that have the name advice with any parameters.

Then we simply define the @Before and @After annotations on our methods to say what needs to happen before and after the method execution. The value specified within these annotations is the name of the pointcut which is derived from the method name that we specify the @Pointcut annotation on in this case being adviceChild().

Ofcourse there is another annotation called @Around which we can use so that we do not need @Before or @After. A code snippet on how to use @Around is given below;






@Around("adviceChild()")
public void aroundAdvice(ProceedingJoinPoint jp){
System.out.println("Listen Up!!!!");
try {
jp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("You got that ?");
}


One point to note is that the method you annotate with @Around should have a ProceesingJoinPoint as a method parameter.


Lastly we need to tell the Spring container about our advice.We could either just wire the bean
named AnnotationAwareAspectJAutoProxyCreator which is a BeanPostProcessor
or we could simply use the custom configuration element provided by spring in the aop namepsace. Hence the configuration will be as follows;





<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">


<aop:aspectj-autoproxy />

<bean id="childServ" class="ChildService"/>

<bean id="chdAdviceAspect" class="AdviceChild"/>

</beans>


If you wanted to go with complete XML configuration without using annotations then your XML configuration will be as follows;




<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">




<bean id="childServ" class="ChildService" />

<bean id="chdAdviceAspect" class="AdviceChild" />

<aop:config>
<aop:aspect ref="chdAdviceAspect">
<aop:pointcut id="advice" expression="execution(* *.advice(..))" />
<aop:before method="beforeAdvicing" pointcut-ref="advice" />
<aop:after-returning method="afterAdvicing"
pointcut-ref="advice" />
</aop:aspect>
</aop:config>
</beans>


If your defining it with XML then you do not need to have the annotations within your
AdviceChild class. This approach is cleaner too because then you can use any plain
old class as an Aspect.


Note that if you were to define aspects the old fashioned way then you need to create a ProxyFactoryBean to represent your bean which you need to weave in your advice and inject your advice class as an interceptor name. This is very cumbersome as you need to define this to each and every bean you want to weave in your advice to. And hence this approach i have given here required very less XML and is not at cumbersome as the ProxyFactoryBean method.

And lastly i give you a test class for you to see a running configuration.


public class AspectTester {

/**
* @param args
*/
public static void main(String[] args) {

ApplicationContext appContext = new ClassPathXmlApplicationContext("appContext.xml");
ChildService chldService = (ChildService)appContext.getBean("childServ");
chldService.advice();
}

}



Thats it guys. If there are any queries do drop a comment.

Cheers!!!!

Wednesday, June 16, 2010

Defining Custom Editors With Spring

Custom editors gives you a lot of flexibility and reduces XML configuration when defining your spring beans. Say for example i have the following Person object;


public class Person {

private String firstName;

private String lastName;

private int age;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}


}


And the following Class called PersonManager is using this Person object as follows;


public class PersonManager {

private Person person;

public Person getPerson() {
return person;
}

public void setPerson(Person person) {
this.person = person;
}


}


If you wanted to inject a person object to the PersonManager class then you would first register the Person class as a spring bean and register that bean as a ref bean of PersonManager class.

But spring offers an easy way of injecting the Person object to the PersonManager by use of Custom PropertyEditors. With this you can define your values as a string value and create the Person object as you deem appropriate from the format you define. In my example i have defined the format to be;
firstname,lastname,age
hence is would be comma separated values which defined the values needed to create the Person object. Now in order to let spring understand how to handle this string value you need to define your own propertye editor. It is as follows;






public class PersonPropertyEditor extends PropertyEditorSupport{

@Override
public void setAsText(String arg0) throws IllegalArgumentException {

String[]vals = arg0.split(",");
Person p = new Person();
p.setFirstName(vals[0]);
p.setLastName(vals[1]);
p.setAge(Integer.valueOf(vals[2]));
setValue(p);
}
}



Here i simply split the string value and set the relevant values of the Person object and then call the setValue inherited method to set the value. Its as simple as that.

And finally you define your customer registar which binds your customer editor.


public class PersonConfiguratorWithRegistars implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry arg0) {
arg0.registerCustomEditor(Person.class, new PersonPropertyEditor());

}
}



Now when letting spring know about your custom editor there were two ways initially before Spring 3.0. They are;

  1. Define as a customEditors property within org.springframework.beans.factory.config.CustomEditorConfigurer
  2. Define as a propertyEditorRegistrars within org.springframework.beans.factory.config.CustomEditorConfigurer
As of Spring 3.0 the customerEditors property is deprecated as they had a thread locking issue as explained here.

So lastly i show you how to wire your new customer editor and the PersonManager object by providing a string value. The application context XML is as follows;






<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--

This is the OLD way of wiring your custom editor which is not thread safe

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="Person">
<bean id="personEditor" class="PersonPropertyEditor">
</bean>
</entry>
</map>
</property>
</bean>

-->

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<ref bean="customPersonPropertyEditor" />
</list>
</property>
</bean>

<bean id="customPersonPropertyEditor"
class="PersonConfiguratorWithRegistars" />

<bean id="perMgt" class="PersonManager">
<property name="person" value="John,Alan,23" />
</bean>


</beans>



Thats it. You can use the following test class to test the same;


public class PropertyEditorTest {

/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("appContext.xml");
PersonManager personMgr = (PersonManager)appContext.getBean("perMgt");
Person p = personMgr.getPerson();
System.out.println(p.getFirstName()+" "+p.getLastName()+" "+p.getAge());
}

}

Thursday, June 10, 2010

A Simple Json Utility Class Using Gson

In my current project we planned to go with Gson(Google's json manipulating library) to handle out json manipulation within our application. Hence i wrote this small utility class to ease the use of Gson within the project.



import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
* This class is used as a Json utility. The base functionality comes from the Gson<br>
* package from Google. It is made generic due to the fact that many clients may use<br>
* this class at any given moment.
*
* @author dinuka
* @param <T>
*/
public class Jsonutil {

/**
* Null serialize is used because else Gson will ignore all null fields.
*/
private static Gson gson = new GsonBuilder().serializeNulls().create();

/**
* Made private because all methods are static and hence do not need
* object instantiation
*/
private Jsonutil() {}
/**
* To Json Converter using Goolge's Gson Package<br>
* this method converts a simple object to a json string<br>
*
* @param obj
* @return a json string
*/
public static <T> String toJsonObj(T obj) {
return gson.toJson(obj);
}

/**
* Converts a collection of objects using Google's Gson Package
*
* @param objCol
* @return a json string array
*/
public static <T> String toJsonList(List<T> objCol) {
return gson.toJson(objCol);
}

/**
* Returns the specific object given the Json String
* @param <T>
* @param jsonString
* @param obj
* @return a specific object as defined by the user calling the method
*/
public static <T> T fromJsonToObj(String jsonString,Class<T>obj) {
return gson.fromJson(jsonString, obj);
}

/**
* Returns a list of specified object from the given json array
* @param <T>
* @param jsonString
* @param t the type defined by the user
* @return a list of specified objects as given in the json array
*/
public static <T> List<T> fromJsonToList(String jsonString,Type t){
return gson.fromJson(jsonString, t);
}

}


Typical usage of the given utility class is as follow;


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.reflect.TypeToken;


public class Test {


public static void main(String[] args) {
Person p = new Person();
p.setFirstName("xxx");
p.setLastName("yyy");

List<Person>pList = new ArrayList<Person>();
pList.add(p);

String jsonStr = JsonUtil.toJsonList(pList);

System.out.println("Person List as Json Array = "+jsonStr);

Type collectionType = new TypeToken<List<Person>>(){}.getType();
List<Person>personList = JsonUtil.fromJsonToList(jsonStr,collectionType);
System.out.println("Person List from json String array = "+personList);

String personJsonStr = JsonUtil.toJsonObj(p);
System.out.println("Json String from person = "+personJsonStr);

Person p1 = JsonUtil.fromJsonToObj(personJsonStr, Person.class);
System.out.println("Person from json String = "+p1);

}



}

class Person{
private String firstName;
private String lastName;
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}


}



Thats it guys. If you have any queries or possible enhancements you can see, please do leave a comment.

Thursday, June 3, 2010

How to solve Classpath nightmare in java

Have you ever come across a situation where you modify a class and when you run it you do not see the changes you just committed? Most probably in most cases the issue lies with an older .class file being loaded in from another jar which overrides your current jar. This is definitely a debugging night mare.

Fortunately in java you can find out from which location your class file is loaded from. This article provides the info you need to find out on how to do it the eclipse way or injecting it directly to your code.


Enjoy!!!

Wednesday, June 2, 2010