Wednesday, February 24, 2010

Smart Way of Doing Null Checks for JAXBElements

If want to Avoid using if(X!=null){a = x.toString}else{"NULL"}; many times in code, this blog is usefull to you.
I got a situation like : To track the data passed to a webservice, i need to create a large string which has values of the number of inputs passed to a webmethod.As all the input elements are JAXB elements and most of the input elements are optional, I must have to do a null check to each and every element before converting it to string.For this i created a small method as follows:
private String JAXBNullHandler(JAXBElement obj) { if (obj != null) { return String.valueOf(obj.getValue()); } else { return "NULL"; } }Wherever i need the string value of an element i used the method call as follows:
JAXBNullHandler(amount); where amount is a JAXBElement.
This has reduced a considerable amount of code and the code is legible.

Monday, February 8, 2010

Remember this before using Spring Context Loading

This week i faced a strange issue with spring context loading.
My aim is to persist all types of errors occuring in webservices. Hence i have created an helper class and injected the helper class in webservice Impl class as follows:private SaveExceptionHelper saveExceptionHelper;

String[] paths = { "/spring/service.xml"};
ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
saveExceptionService = (SaveExceptionServiceImpl) ctx.getBean("saveExceptionService");

Also in service.xml i have put tag for SaveExceptionServiceImpl.


Upto this I didnt get any problem in build and deployment.
Later i have used a DAO which is having persitance method of hibernate.
and injected in service.xml under SaveExceptionServiceImpl.

I got an exception like

" abc.def.User class not found"

Where "User.class"" is created in some other project folder and imported in SaveExceptionServiceImpl.


Later i fixed it by using an interface to the helper class as saveExceptionService = (SaveExceptionService) ctx.getBean("saveExceptionService");
And i removed the import of ServiceImpl class.
Moral of the story is:
  1. The Importance of using Interfaces in Spring context initialization.
  2. The helper classes which has implemenation should not use resources from other projects. Incase, it is using other resources, we need an interface for that class and inject the interface in webservice class. Impl class in context loader xml(service.xml).