Dec 29, 2010

String.trim() on Unicode space characters In Depth

As developers, we know that the \u00A0 is a unicode space character. Even the \240 is a unicode space character. As a Java developer, have you been working with String.trim()? I am sure, your answer would be "Yes"!

Now, let us come to an interesting pointer. Have you ever had a look at how String.trim() works? If you had been tech savvy and if you would have read the Java Specs, am sure, you would be knowing the bizarre nature of String class's trim() function.

For the others, let us get further. Just type in the following java code as a stand-alone Java program and try to run it!

Sample Program
public class Sample {
public static void main(String arg[])
    String test = "\240";
    for(int i=0;i<test.length();i++)
        char ch = test.charAt(i);

hai: :hai<br />

In the above example, when you run it, you would be surprised to see that the text between "hai:" and ":hai" would still be a space even after executing trim() on the test string. As a developer, I expected "hai::hai" to be printed too! But the "hai: :hai" surprised me. On digging a bit further, I am able to see that the Java String class trim() works a bit differently.

So, I was wondering whether trim() really trims all white spaces and space characters? May be not and here goes the clarification.

Trim(): Clarification in Detail

Java's String abide by UTF-16. However, Java's trim() says that it trims off the leading and trailing white space characters listed by Java and not unicode. It does not trim all the space and (or) white space characters as defined by uni-code. In this context, we need to understand 2 more pointers.
  1. Character.isWhiteSpace(char/int): Checks whether the specified int or character is a whitespace. 'white space' here refers to a sub set of white space characters defined by unicode(excluded are the non-breaking white space characters defined by unicode and included are uni-code lower control characters that are equal or below U+0020), a list of white space characters defined by Java(not in the unicode list). 
  2. Character.isSpaceChar(char): Checks whether the given character is a space character. Space character in turn refers to space characters defined by uni-code.

And as I understand, Java String Class's trim() trims off the white spaces (list as defined by Java) and this is definitely not as intuitive as it should have been and hence this post!

As always, I appreciate your feedback/hollers regarding this article any time!

Dec 22, 2010

How To Access Spring Security Tags or JspTagLibs on Spring Secuirty in Apache Velocity?

I was working on a Spring framework based application where in I wanted to incorporate Spring Security quickly. While doing so, there was a need for me to display links in the UI based on the logged in user roles. The UI that I was using was Apache Velocity. I knew the fact that there were JSPTagLibs available for Spring Security.

I had incorporated the basic security and I was using Spring Security 3.0.4. So, I was exploring on using the Spring Security JSP tab library into the Apache Velocity Templates for displaying a few links based on the roles of the principal who had logged in! In this juncture, I wanted to use the JSPTagLibs of Spring security in the velocity template.
When I explored options on this, it was so unfortunate that I could not find any. But , when I confronted the resolved JIRA issue on 'Support for jsp taglibs in freemarker templates', initially I presumed that the same or a similar structure might be present for velocity too.
But the freemarker blog article on 'Velocity or FreeMarker: Looking at 5 Years of Practical Experience' made me realize that my presumption was wrong.

Further to this, I had to explore alternative options.

The best and the quickest alternative was to make use of a wrapper class that can get me the objects that I needed in the velocity views. For this, I needed a wrapper class for the Security tag library that can get me the objects/properties that I needed to make use of in my views. So I went ahead and made use of the following wrapper class. I had a wrapper class as shown below. This contained the properties/methods related to the security that I intended to make use of inside my velocity views.
package com.utils;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;


public class VelocitySecUser {

* Gets the user name of the user from the Authentication object
* @return the user name as string
public static String getPrincipal() {
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (obj instanceof UserDetails) {
return ((UserDetails) obj).getUsername();
} else {
return "Guest";

* Is the user granted all of the grantedAuthorities passed in
* @param roles a string array of grantedAuth
* @return true if user has all of the listed authorities/roles, otherwise false
public static boolean allGranted(String[] checkForAuths) {
Set<String> userAuths = getUserAuthorities();
for (String auth : checkForAuths) {
if (userAuths.contains(auth))
return false;
return true;

* Is the user granted any of the grantedAuthorities passed into
* @param roles a string array of grantedAuth
* @return true if user has any of the listed authorities/roles, otherwise false
public static boolean anyGranted(String[] checkForAuths) {
Set<String> userAuths = getUserAuthorities();
for (String auth : checkForAuths) {
if (userAuths.contains(auth))
return true;
return false;

* is the user granted none of the supplied roles
* @param roles a string array of roles
* @return true only if none of listed roles are granted
public static boolean noneGranted(String[] checkForAuths) {
Set<String> userAuths = getUserAuthorities();
for (String auth : checkForAuths) {
if (userAuths.contains(auth))
return false;
return true;

private static Set<String> getUserAuthorities() {
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Set<String> roles = new HashSet<String>();
if (obj instanceof UserDetails) {
Collection<GrantedAuthority> gas = ((UserDetails) obj).getAuthorities();
for (GrantedAuthority ga : gas) {
return roles;

Further to this, you might have to add this as a bean into the attribute map of your velocity view resolver as given below:
<br /> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"><br />        <property name=....//><br /> <property name="attributesMap"><br />               <map><br />                <entry key="sec"><ref bean="veloSecUserDetails"/></entry><br />               </map><br /> </property>              <br /> </bean><br /> <bean id ="veloSecUserDetails" class ="com.utils.VelocitySecUser"/><br /> 
When this is done, automatically, you would have the object $sec accessible from within your velocity templates. You can start making use of this object in the velocity templates using the code shown below:
<br />Testing the Object $sec <br />Name of the principal is: ${sec.principal} <br />#if($sec.AllGranted("ROLE_USER")) <br />     The principal has USER role within the application<br />#end<br />
That is it!!Your code starts woking great and you have access to all the methods that you have it in the wrapper within your Apache velocity template on the flu!

I sincerely express my thanks to the discussion at Spring forum since the base ideas are basically discussed here as the solution for accessing spring security tags within Velocity Templates!

As usual, I look forward getting your hollers/feedback regarding this post any time!

How To Resolve 'org.springframework.core.convert.ConversionFailedException: Unable to convert value from type 'java.util.LinkedHashMap' to type 'java.util.Map'; nested exception is java.lang.IllegalArgumentException: Left-hand side type must not be null'

I had been using Spring framework 3.0.0. I had the requirement of passing an attribute map to one of my bean in the application context and I was using the conversion service as shown in the code snippet below
<bean id="conversionService" class="" />

When ever I try to set the attribute map to the bean, it was giving me the following exception
org.springframework.core.convert.ConversionFailedException: Unable to convert value {<your value>} from type 'java.util.LinkedHashMap' to type 'java.util.Map'; nested exception is java.lang.IllegalArgumentException: Left-hand side type must not be null

The error was, of course. not helpful and did not give me any clue as to why and from where the problem emerged from. I was thinking that the objects, the key value, that I was passing was not of the expected type. However, since that was not the case, I had to explore a bit across the Internet in this regard. When I explored, I found that there is a problem with the conversionService bean in the Spring Framework version 3.0.0 that has been fixed in Spring Framework 3.0.1. This has been documented as a JIRA issue. A

As pointed out in the JIRA link, I observed that the problem was with the conversion service of the Spring version 3.0.0. Fortunately, the issue has been fixed in the 3.0.1 version itself.fter going through this, I ended up in downloading the latest Spring framework jars and the code started working like charm!

So, whenever you try to add an attribute map to any of your bean in the application context within a Spring 3.0.0 based application, and, if you are using a conversionService that references, and if you confront a problem like 'Unable to convert value from type 'java.util.LinkedHashMap' to type 'java.util.Map'; nested exception is java.lang.IllegalArgumentException: Left-hand side type must not be null', then please have a look at the JIRA issue and upgrade your jars accordingly.

Since I thought that this might help a few of you who are confronting similar issues, I have documented this and posted here. I appreciate your hollers/feedback regarding this post any time!

Nov 19, 2010

What is Caught: java.lang.NoSuchMethodError: antlr.ASTFactory.setASTNodeClass(Ljava/lang/Class;)V?

Are you trying to run a groovy script and keep on getting the error "Caught: java.lang.NoSuchMethodError: antlr.ASTFactory.setASTNodeClass(Ljava/lang/Class;)V"?
I was in that boat a couple of days back and was wondering what was causing this issue since I had been using groovy for the past few months without any issues.

What I was doing was trying to run a groovy script at the home directory of a new server. I was using groovy 1.7.0 version and kept on getting the above error irrespective of the script that I ran! I was trying to run it from command line from my home directory on an unix server using
 ~/software/groovy-1.7.0/bin/groovy <groovy-script name.groovy>

On exploring a bit,I was able to see that the "NoSuchMethodError" error had popped in from the antlr library. So, I went into the \lib directory within the groovy folder and looked into the antlr library that was present.

I noticed that there were 2 antlr libraries that were present. They were
antlr-2.7.7.jar and antlr.jar. I was of the opinion that the groovy program would have got confused with the existence of 2 different instances of all classes within the 2 different antlr library present within the groovy folder. Hence, I deleted the antlr.jar and retained the antlr-2.7.7.jar and tried running the script.

The scripts started to run without any issues thereafter!

Sep 1, 2010

Display Text Area Contents with Line Breaks as Html Content

There was a need for me to display the text area contents as html in one of my assignments. I was able to see that the line breaks (\n) present in the text content that needs to be displayed as html in a page were getting stripped of automatically!

Was wondering why the text area content with line breaks was not getting displayed properly as html on the first attempt. Then found that the \n were auto stripped by html while displaying the text field contents with line breaks as html.

So, here is the fix that I incorporated in the html page that was displaying the text area content with line breaks. The best way via which I was able to fix this up was as below:

Let us say content is the field that has the text area content stored in it from the database.
While displaying that in the html page, I used
content.replaceAll(’\n’,’<<br />>’) 

And this worked!

Jun 2, 2010

How to Implement Hashcode() and Equals(): Dos and Don'ts

The hashcode() and equals() method have always intrigued me a lot! I had never wanted to dive in depth into this! However, I thought I should dive deep into the bet practice related to the implementation of equals() and hascode() for domain objects.

Before we dive deep into this let me tell you the problems that you might confront if you do not override hashcode() and equals() in your persistent domain objects

Consequences of Not Overriding the Equals() and Hashcode()

  1. When you try to load the same persistent object from 2 different sessions, then you might have unexpected results. Let us say that we have the following code where in the domain object Sample does not have the overridden equals() and hashcode()
  2. int i=2;//2 is the existing id of the Sample object in the db
    Sample s1 = firstSession.load(Sample.class, i);
    Sample s2 = secondSession.load(Sample.class, i);
    In the above case, we would expect that the assert statement would return true! But this would never be the case since the s1.equals(s2) would just make a == comparison and would return false. For a simple Sample class given below:
    public class Sample {
    private int id;
    private int rollNo;
    public int getId() {
    return id;
    public void setId(int id) { = id;
    public int getRollNo() {
    return rollNo;
    public void setRollNo(int rollNo) {
    this.rollNo = rollNo;
    The following code would return false if the hashcode() and equals() are not overridden
    Sample s2 = new Sample();
    Sample s3 = new Sample();
    System.out.println("am here:"+s2.equals(s3));
  3. If you are planning to use the domain object as a composite id, it is imperative that you override both the methods. Else the equals() of the Object class would be used where in the == would be used and it would never suffice!

ID Based Equals() and Hashcode() Implementation: Hidden Dangers

One of the very common implementation of the equals() and hashcode() methods that I come across is as given below: It uses the id property for the implementation
public boolean equals(Object obj) {
if(!(obj instanceof Sample)){
return false;
Sample other = (Sample)obj;
if (!(other.getId() == return false;
return true;

public int hashCode() {
But how far is the above code reliable? Is this the right way of implementing the equals() and hashcode()? In case of ORM solutions like Hibernate, where the ORM would not generate the id till it saves the domain object to the db, the above implementation proves to be hazardous. Here is a very nice article that tells the problems associated with the implementation given above!

  1. First and foremost, putting the unsaved domain objects with equals() and hashcode() (in ORM like Hibernate) described above into sets would produce unexpected results.
  2. Let us have a look at the below code:
    Sample s = new Sample();
    Sample s1 = new Sample();
    Set<Sample> newSet = new HashSet<Sample>();
    System.out.println(newSet.contains(s));// returns true
    System.out.println(newSet.contains(s1));// returns true
    System.out.println("size:" + newSet.size()); // returns 1: unexpectedly
    // due to improper
    // implementation of
    // equals() and hashcode()
    In the above code, the id of both s and s1 would be 0 if int or null if the type is Integer. As a result, the second s1 when put in the set overrides the first s object and hence when tested for contains the hashcode() method returns 0 for id and hence both return true. But, the set size is just 1!
  3. Secondly, the collections would produce unexpected results before and after saving them to the db. Lets see this issue in detail.Consider the following code:
  4. HashSet newSet = new HashSet();
    Sample s4 = new Sample();
    newSet .add(s4);;
    assert(newSet .contains(s4)); // returns false since the id before and after save changes.

Here the id of the Sample object before saving is 0 and after saving is different and is determined by the ORM. As a result the assert returns false in contrary to what is expected!

Best Alternative Implementation

Amidst such issues, the best option would be to implement equals() and hashcode() using a combination of business keys! In an IDE like Eclipse. it is going to be easy. Just right click, point to source --> Generate equals() and hashcode() and you have the option as shown below to choose the business keys that you want to be a part of the equals and hashcode() checks. With all, this proves to be the best and the most reliable option to me! However, do keep me updated with your suggestions too!

Best Practices
  1. Ensure that your customized implementation abides by the contract dictated by sun.
  2. Ensure that you are making use of a combination of immutable business keys of the domain object for the implementation.
  3. Do have a look at the hibernate forum discussion before you go ahead withe the implementation.
  4. Yet another article that is worth checking is here. Have a look and then go ahead with your customizations further!

May 18, 2010

Java Code Optimization: Tip # 1: How To Use Java Map .contains() and .get()

One very common mistake that I see in application code written in java is the way maps are accessed! Though it is very common, in my opinion I would say that this is an expensive mistake! Go ahead, get to know what the error literally is and correct the same if you come across one in future for that would help you to have an optimized code on the fly.

Let us say that we have a map! Let us create the map
Map<Integer,String> testMap = new HashMap<Integer, String>();

Here, while looping through the keyset of the above Hashmap, a java developer very often tries to do the following:

Un-Optimized Code:
<br />if(testMap.contains(1))<br />{<br />    String tempString = testMap.get(1);<br />    System.out.println(tempString);<br />}<br />

This is emphatically a stress to the memory and makes an un-optimized code. Here,
  • We check whether the map contains the key we are looking for.
  • Next, we try to get the value of the key if the key is present in the map
  • We access the map 2 times and if this is placed within a for loop, imagine the number of times we would be accessing the map

The above code can easily be replaced by:

Optimized Code:
<br />String tempString = testMap.get(1);<br />if( tempString == null)<br />{<br />    System.out.println(tempString);<br />}<br />

In the optimized code,
  • we are not checking whether the map contains the key we are looking for.
  • We are just trying to get the value for the key specified.
  • If the key exists in the map, we would have a valid value in the tempString.
  • Else, this would be null and hence we access the map just once for every check we do!

In my opinion, rather than accessing map.contains() and map.get() for every check, trying to get the value by using map.get() would render an optimized code
That was one optimization technique that I found was really utile! And hence thought of sharing the same with you all!

May 10, 2010

Spring Annotations: A Remarkable Reference

I was surfing the Internet and accidentally came across a nice reference for Spring. Since i work with more of Spring annotations, I really found it to be very cool!!! A reference card for Spring annotations is emphatically rare! It is quite useful too!! I thought it is a must have for a programmer who works in java and especially Spring based web application using annotations.

This thought forced me to share the same with you guys too! Here is a list of Core Spring Annotations, Spring MVC annotations, Aspect J and JMX annotations along with JSR 250 and Testing annotations too!! Go through this and have a good time! Keep me posted with your feedback as usual!

Reference Card for Spring Annotations


May 5, 2010

How To Use @Async in Spring Web Application?

I decided to give the @Async annotation a try! The recently added @Async annotation in the Spring Framework 3.0 seems to be an easy fit for applications that would require asynchrous calls to be invoked while the application is running or deployed! Here is a sample code that can help you with making your @Async annotation work with ease!
  1. As the first step, you have to incorporate the schema location detail and the xmlns detail for the task tag in Spring framework. The xmlns configuration details that you need to include is:
  2. The schema location configuration details that you need to include in your application context includes
  3. Next, make Spring container understand that you are going to invoke asynchrous tasks that are annotation driven. So, remember to add the following line in your applicationContext.xml file.

    <br /><task:annotation-driven><br />
  4. After this, check your configuration xml file to ensure that you have implemented the context scanning on the code package where you are going to define the asynchronous jobs that you expect to be run by the spring framework. Let us say, we have a package where we are going to have a class that would have all the methods annotated with @Async here and these would in turn be invoked by the scheduler. Then, ensure that you have this package as a part of the component scanning tag within the configuration xml file as follows:

    <br /><context:component-scan base-package=""><br />
  5. Now, we are almost complete with the changes in the configuration files. Next, let us go ahead with a class that would have methods annotated with @Async which are in turn the asynchronous tasks that would be invoked within our application. Remember, as discussed earlier, this class needs to be in package. Let us refer to this class as The code for this class would look something like:

    <br />package org.test.common.utils.Tasks;<br />import java.util.Date;<br />import org.springframework.scheduling.annotation.Async;<br />import org.springframework.transaction.annotation.Transactional;<br />import org.springframework.stereotype.Component;<br />@Component<br />public class MyScheduler implements Scheduler{<br />@Transactional(readOnly = false)<br />@Async<br />public void testTask() {<br />System.out.println("Starting to process the task at " + new Date()); <br />}<br />}<br />
  6. And that is it! You are done. The @Async tells the spring container that the method underneath is an asynchronous task that would be invoked within the application. You can call this method from any class using the snippet as given below:

    <br />@Autowired<br />private Scheduler s;<br /><br /> s.newTask();<br />
  7. Further, when you use @Async you can return parameters from those methods and that should be Future typed. Say Future etc! That is unbelievable. Even if you want to update the db, you can go ahead and get the current session and process this method within a transaction to make db updates on a periodical basis.
If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

May 4, 2010

How to Implement a Task Scheduler/ Job Scheduler in Spring Framework using Annotations?

I had a chance to analyze how the task scheduler works in Spring framework today!! The recent addition of the @Scheduled and @Async into Spring framework 3.0 forced me to tgive them a try! Emphatically, spring framework is remarkable. With a few tweaks in code, everything gets in place as expected. In this article, let me give you a very brief overview on how to implement a scheduled task in spring using @Schedule annotation! This would be a nice tutorial for a newbie and an intermediate Spring programmer! If you intend to have a scheduled job run periodically and if you are using Spring, please read further and get to know the nuances involved.Let us dive into action right away!.
  1. First and foremost, let us decide on incorporating the task:annotation-driven in the applicationContext.xml file. This is the configuration file that would be loaded by the ContextLoaderListener within your spring application. I have decided to have the task:annotation-driven tag within the application since this is where I would be including the beans that would form a part of my service layer and I am going to include the TaskScheduler class a service in my application.
    Next, go ahead and add the xmlns details to your configuration. The following code needs to be added to the applicationContext.xml file in your application.

  2. Further, you have to add the schema location details for the task-annotation driven tag in your applicationContextxml. This is as follows:  <br /><br />
  3. Note: If you do not add the configurations given in point # 1 and #2 in your applicationContext.xml where we would be defining the services used in our application (I am conidering that I would have a class containing the scheduled jobs as a service and this would be a part of my services package), you are likely to get the "The prefix 'task' for element '' is not bound" error.
  4. Next, you have to make your Spring container understand that you would be having some scheduled jobs within your application and those tasks are driven by annotations. You can do so by adding the following line to the applicationContext.xml file.

    <task:annotation-driven><br />
  5. Now, it is important that the Spring framework should be aware of the class details where you would be using your @Scheduled annotation. For this, let us consider we have a package In this package, let us consider that we have a class This is the class that would contain all the methods which would be invoked as scheduled tasks/jobs in your application. It is important that you add this package in the component-scan tag within your applicationContext.xml as follows:

    <context:component-scan base-package=""<br />
  6. Next, we need to code the details of the scheduled job within the class MyScheduler. As a sample, we will have one method testTask. This task would be annotated as @Scheduled with the required attributes. This would in turn make Spring container understand that the method underneath this annotation would be run as a job that is scheduled by the Spring Framework. This can be done as follows:

    package org.test.common.utils.Tasks;<br />import java.util.Date;<br />import org.springframework.scheduling.annotation.Scheduled;<br />import org.springframework.stereotype.Service;<br />@Service<br />public class MyScheduler {<br />  <br />    @Scheduled(fixedRate = 5000)<br />    public void process() {<br />        System.out.println("Invoking testTask at " + new Date());<br />    }<br /><br />}<br />
  7. Attributes for @Scheduled Annotation:If you want a job or a task to be run every 5 secondsm then you need to modify the @Scheduled annotation sued above as: @Scheduled(fixedRate = 5000). If you want a time gap of 5 seconds between the end of previous execution and the start of the succeeding execution then you need to modify the @Scheduled annotation as @Scheduled(fixedDelay= 5000). You can also trigger a cron job and define your cron parameters say try running a job at 6.30pm everyday by using @Scheduled(cron="30 18 * * * ")
  8. And that is it! You deploy the application. You would see the 'Invoking testTask at " + current date' getting printed every 5 seconds in your console!
  9. Further, Even if you want to update the db, you can go ahead and get the current session and process this method within a transaction to make db updates on a periodical basis.
  10. Note: Remember that the methods annotated with @Scheduled should not have parameters passed to them. They should not return any values too.If ever you want the external objects to be used within your @Scheduled methods, you should inject them into the MyScheduler class using autowiring rather than passing them as parameters to the @Scheduled methods
If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!Technorati Tags: , , , , ,

Understanding the Different ApplicationContexts in Spring Application

As a beginner to spring, one might often not know the difference between the several applicationContexts that we use in a spring application. Spring documentation is the best place that can really guide you though the process of completely getting this clarified!

But here is the abridged version for a quick understanding of the differences between the various configuration files that we use in a spring application.

  • Understand that the webapplicationcontext denotes the xml configuration file that is invoked by the DispatcherServlet within the spring enabled web application. This is the xxx-sevlet.xml file where you define the details of the handler mappings, view configuration, controller bean definitions and other web related beans. This also includes the definition of the locale and theme resolvers that you might use within your application. You can have a single or multiple web application contexts within your spring enabled web application.
  • The other application contexts that are used within the spring enabled web application are usually loaded by the contextLoaderListener/servlet as shown in the figure below. This can be a single file (applicationContext.xml) or multiple applicationcontexts with names based on the modularization that you make within the application. these application contexts are very different from the web application contexts. They contain the details of the datasources, daos, services, other component beans and the details of the transaction managers used within your application.
  • Note that the webapplicationcontext used within any application would have access to all beans defined within the application contexts that are loaded by the ContextLoaderListener.
  • When you configure the transaction manager, it is important to understand the fact that the Txmanager will search for @Transactional type annotations in all the beans defined within the same application context only! So, this means that you cannot define the TxManager in the applicationContext and have your services and dao beans defined in the webapplicationcontext of your application for this would result in org.hibernate.HibernateException: No Hibernate Session bound to thread. Before you go ahead, ensure that the above differences are very clear and configure your application accordingly!
Technorati Tags: , , , ,

Apr 28, 2010

How To Use Transaction Manager with @Transactional without getting 'org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here' Exception?

Its you readers who post comments on my blog often induce me to post more information and additional write ups here!I sincerely thank you for that induction you create in me! Based on the information requested, I thought of posting an article here that would help many of you (like me) who end up with the very famous "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here".

If you are looking at the procedure to incorporate the TxManager in your spring application by making use of @Transactional annotation along with org.springframework.orm.hibernate3.HibernateTransactionManager and , here is the right information that you can make use of! This would not only help you to get out of 'org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here' exception but would also help you in understanding the rudiments involved with the transaction very easily.

Here are the basic steps that you can make use of. Let us say that you have an applicationContect.xml(This is the application context that is loaded by the contextLoaderListener/contextLoaderServlet of your application). Let us say that you have a webdispatcherservlet's webapplication context named as application-servlet.xml.

In this case, please follow the steps given below to incorporate the transactions with ease. In my opinion, it is always recommended that you have your service layer transactional . So i intend introducing the @Transactional annotations at the services in the following example!
  1. First and foremost, define the TxManager bean within the applicationContext.xml as shown below. Remember that this context is the place where you should define the component scan for the services and daos present within your application.
  2. <bean id="transactionManager"
    <property name="sessionFactory" ref="defaultSessionFactory" />
    <tx:annotation-driven transaction-manager="transactionManager" />
  3. Note that if you define the bean id of your TxManager as transactionManager, the tx:annotation driven tag can be as given below. It literally means that you need not define the name of your transaction manager in the tx:annotation-driven tag. If you have this bean's id as something else other than "transactionManager", you need to have the the additional attribute "transaction-manager" to the tx:annotation-driven tag.
  4. <tx:annotation-driven /><br />
  5. Next,define the xmlns for the tx tag as given below in the same applicationContext.xml
  6. xmlns:tx=""<br />
  7. Further, you need to add the schema location for the Tx tag as shown below in the same applicationContext.xml
  8. <br /><br />
  9. Next, go to your daoImpl file say and define the sessionFactory as shown below
  10. @Repository("SampleDAO")<br />public class SampleDaoImpl implements SampleDao {<br /><br />    @Autowired<br />    @Qualifier("appSessionFactory")<br />    private SessionFactory sessionFactory;<br />
  11. Remember that you have to use the sessionFactory injected in your daoimpl as shown below
  12. sessionFactory.getCurrentSession().saveOrUpdate(hibernateObject);<br />
    sessionFactory.getCurrentSession().createSQLQuery("<your query here>")<br />
  13. Next, go to your service impl layer. Let us say that you have your service implementation file named as Here, you will have to introduce the @Transactional annotations. Be careful and ensure that you make the transaction read only for the find and get queries while you can make the transaction writeable in methods that updates, saves or deletes the objects in db as follows. Here, you can make the @Transactional annotation at class level as read only. When you have an update method that writes to the db, you can annotate that method with @Transactional(readOnly=false) for this would override the class level annotation incorporated as readonly!
  14. @Service("sampleServiceImpl")<br />@Transactional(readOnly = true)<br />public class SampleServiceImpl implements SampleService {<br />@Autowired<br />@Qualifier("sampleDAO")<br />private SampleDAO sampleDAO;<br />public sampleObject getObject(int id)<br />{<br />return sampleDao.getObject(id);<br />}<br />@Transactional(readOnly = false)<br />public void update(SampleObject sampleObj) <br />{<br />sampleDAO.saveOrUpdate(sampleObj);<br />}<br />}<br />
  15. That is it!!!Your application would have included the TxManager successfully! Your db calls would be then managed by the Spring defined TxManager without any problems from here!
While this depicts a very simple implementation, you can go ahead and change the properties for the @Transctional annotation further to modify the propagation and isolation levels wherever necessary! You can also implement multiple transactional managers if need be by using @Transactional("TxManager1") and @Transactional("TxManager2") and by defining the corresponding TxManagers in your appplicationContext.xml with ease!!! Hope this helps you to circumvent the famous "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here"! Whatsoever, keep me posted and stay tuned!

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Apr 27, 2010

Field versus Property Access in Hibernate :Understanding @AccessType in Hibernate

Programming with POJOs is emphatically a part and parcel of hibernate! But deciding the contents and the property access within the POJOs is at the discretion of the programmer. However, from a procedural programmer's perspective, the instant answer to such a scenario would be to opt for getters and setters for the properties within the POJOs! Before we have a look at whether this is really right and recommended, the other important consideration would be the accesstype! This can either be field or property level. Nonetheless, the controversies regarding the usage of Property or filed level access for the properties in the POJOs still continues and dosent seem to end even till date!

What is @Accesstype in Hibernate?

Let us say that you have a POJO as follows. The location of annotating the id property of the POJO with @Id and @column annotations in hibernate determines the access level of this domain object
public class Sample {
private int id;
private String title;
private String Description;
public int getId() {
return id;
public void setId(int id) { = id;
public String getTitle() {
return title;
public void setTitle(String title) {
this.title = title;
public String getDescription() {
return Description;
public void setDescription(String description) {
Description = description;

Type 1: Field Access with @Accesstype in Hibernate

In the above POJO, if we annotate he id property as follows, then we are offering field level access to the properties inside the POJO. ORM framework chooses to access the fields using Introspection and reflection rather than via the getters and setters.
@Entity <br />public class Sample {<br />    @Id<br />    @Column(name = "id", nullable = false)<br />    private int id;<br />    <br />    @Column(name = "title", nullable = false)<br />    private String title;<br />    <br />    @Column(name = "description", nullable = false)<br />    private String Description;<br />    <br />}<br /><br />
In this case, getters and setters are not necessary! Such coding supports future changes to the structure of the domain object with ease. It not only offers clean/maintainable code but also better encapsulation, though a procedureal programmer would emphatically deny such a statement!And for those, who argue that having accessor methods offers better encapsulation, I would suggest to go through this article for that would better explain the nuances very clearly!

In future, if there is a need for AOP integration or business logic incorporation within the domain objects, then that can be very well supported by adding the necessary behaviour to this POJO as and when needed!

Type 2: Property Access with @Accesstype in Hibernate

But, if we annotate the properties on top of the getter methods, then it is that the POJO uses property elvel access. It is as given below:
@Entity <br />public class Sample {<br />    private int id;<br />    private String title;<br />    private String Description;<br />    <br />    @Id<br />    @Column(name = "id", nullable = false)<br />    public int getId() {<br />        return id;<br />    }<br />    public void setId(int id) {<br /> = id;<br />    }<br />    @Column(name = "title", nullable = false)<br />    public String getTitle() {<br />        return title;<br />    }<br />    public void setTitle(String title) {<br />        this.title = title;<br />    }<br />    @Column(name = "description", nullable = false)<br />    public String getDescription() {<br />        return Description;<br />    }<br />    public void setDescription(String description) {<br />        Description = description;<br />    }<br />}<br />

Such access of domain objects via getters/setters is again another way of accessing the properties of the POJO. The ORM framework uses accessors to set and get properties in this case. If in case, there is a need for business validations to be incorporated at a later date, then there might be a need for additional set of getters and setters that might have to be implemented in code. This not only makes the coding cluttered but also makes the maintenance burdensome!

Mix up!

This is always possible! You can have the default field access and mark the properties that need the proeprty level access as transient. Further, you can define the annotation for such properties before their accessors
@Entity <br />public class Sample {<br />    @Id<br />    @Column(name = "id", nullable = false)<br />    private int id;<br />    @Transient <br />    private String title;<br />    @Transient <br />    private String Description;<br />    <br />   <br />    @Column(name = "title", nullable = false)<br />    public String getTitle() {<br />        return title;<br />    }<br />    public void setTitle(String title) {<br />        this.title = title;<br />    }<br />    @Column(name = "description", nullable = false)<br />    public String getDescription() {<br />        return Description;<br />    }<br />    public void setDescription(String description) {<br />        Description = description;<br />    }<br />}<br />

Existing Controversies

With respect to performance, it can be vouched that there is not much of difference between the two methods discussed above. However, While a survey by google vouches that the field access is preferred, there is still another face to this issue that needs to be analysed in depth!

As per the @AccessType implementation of hibernate, if we intend to get the identifier of an associated object in hibernate, if we use property level access, then hibernate understands that there is getId() method in the corresponding POJO and hence gets the id without initializing the proxy. However, this does not work if we use filed level access. If we intend to get the id of the associated object, since there is property level access defined, hibernate does not knoww about the accessor methods in this domain object and hence tries to initilaize the proxy to get the id of the associated object!As a result, Hibernate team strongly suggests the use of property access if we do not want the proxy initialization to happen since that might result in lazy initialization exception if done out side the session.

Yet another temporary solution has been discussed in this link. However, a note with title @org.hibernate.annotations.AccessType in hibernate documentation

The annotation @org.hibernate.annotations.AccessType should be considered deprecated for FIELD and PROPERTY access. It is still useful however if you need to use a custom access type.

Adding fuel to this fire is the bug reported in hibernate. While this points to the proxy initialization issue on calling getId() of an embedded object within hibernate, it is very clear that Property level access is being discouraged by Hibernate (though Spring's dictum is to opt for field level access only as in this link.

Best Practices

  1. There is not much of difference between the field and property level access with respect to performance.
  2. Field level access would be preferred if the code avoids hibernate proxy pitfalls!If there is a need for property access later, this can always be supported by adding the necessary accessors!
  3. Field level access proves to be good if you really want the annotations closer to the code. This not only gives a fare idea of the property details but also avoids unnecessary accessors that might prove to be great evil. Additionally, having accessors is emphatically not a good OO design strategy!
  4. If you are using filed level access, remember that Hibernate would initialize the proxy on getting the id of an associated object at least until the bug gets resolved.
  5. Property level access can be implemented as long as you do not have business logic or validations within your domain objects since one such scenario can prove to be very dangerous! The positive aspect about this type of access is that Hibernate does not initialize the proxy in case of getting the identifier of the associated POJO.
  6. Overall, the usage of field and property level access depends much on the requirement as the first consideration and then the coding style!

If you find the information pretty pretty helpful, I would really be happy if you would keep me posted! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Apr 23, 2010

How To Solve org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here?

When we implemented transactions using autowiring and TxManager in the spring config xml file, we ended up in having the well known org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here.

I was googling a bit on "No Hibernate Session bound to thread". Emphatically, I ended up with innumerous answers in several sites on the Internet. Springsource forum is not exception to this! Abundant conversations have been happening on this topic all around!!!

But there were a few best practices that I was able to compile from the chit-chats happening across the Internet. I thought of sharing the same here so that it would help some one some day in the near future!

  1. First and foremost, configure the transaction manager properly : Use @Transaction annotation near your code and have a transactionManager bean in your spring config file.
  2. when integration a transaction manager, do not use hibernate.current_session_context_class and hibernate.transaction_factory_class in the hibernate properties unless you have proper reasons to
  3. Never call sessionFactory.openSession()
  4. Use ApplicationContext rather than using BeanFactory
  5. Have single dao instances running across the Application
  6. Above all, most importantly, ensure that the current application context has the component scan for the beans where you have added the @transactional annotations. as per spring documentation's @ Trasactional usage guidelines,

<tx:annotation-driven/> only looks for @Transactional on beans in the same application context it is defined in. This means that, if you put <tx:annotation-driven/> in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services. See Section 15.2, “The DispatcherServlet” for more information.

Point # 6 was the culprit in our case and that was then resolved! So the lessson was You are likely to get "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" if you do not adhere to any of the above pointers.
PArticularly, if you are going to have the applicationContext.xml with the TxManager and the servletname-servlet.xml with the component scan annotations, then you are more likely to get this "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" exception since the TxManager's transaction holds good for the current application context only (which in this case does not have the bean definitions for the service or the daos where you have the @ Trasactional annotations)

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Resolve java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

Spring 3.0 is emphatically remarkable! When we moved to Spring 3.0, everything worked fine and the team was of course happy! While doing this, we were also trying to move transactions from the old-school way (using hibernate.cfg.xml) to autowiring session factory and making it annotation driven! The latter move forced us to introduce the following code in out applicationContext.xml
<tx:annotation-driven transaction-manager="transactionManager" />

When we thought everything would work, we were surprised to see that on deployment, tomcat reported:
<br />java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor<br />

While this Resolve java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor kept us in surprise, I had to google around a bit! On searching a bit across the Internet, I came across the following solution


The previous versions of Spring (<3.0)were shipping AOPAlliance.jar which was required to run the above annotation. In spring 3.0 however, does not come bundles with this jar. As such, if you use Spring 3.0, it is important that you download this jar from this link

Yet another utile pointer that I came across is the fact that there is a JIRA issue to include the AOPAlliance.jar in future releases of Spring! Once I added this jar to the classpath of my application, the Resolve java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor error disappeared!

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Spring Integration with Hibernate

I was working on a nice web application that was using Spring, Hibernate, jquery and Apache velocity! The saddest fact was the reality that Spring was not properly integrated into Hibernate and transactions were not properly handled.

At last, after a detailed discussion on what would happen if such an application goes live, the spring has been integrated properly with Hibernate! As soon as one starts integrating Hibernate with Spring, the various options would be
  1. To use HibernateTemplate
  2. To use HibernateDaoSupport
  3. Use plain Hibernate with hibernate.cfg.xml (like what we have been using till date)
  4. Autowire session factory as a bean in the daos
The Pros and Cons
  1. Using HibernateTemplate
  2. HibernateTemplate is a nice API from Spring for easy integration with hibernate. It mirrors all methods exposed to Hibernate session and proves to be handy! Automatic session close and transaction participation proves to be the best part of this API. Additionally this is handy not only for the nice exception translation but also helps a newbie who does not want to handle sessions or transactions by himself. But, with the advent of Hibernate 3.0.1, this API (using HibernateTemplate.find and the like  - This includes defining private HibernateTemplate in the daos and setting the hibernate template while setting the session factory in a setter method say setSessionFactory) just proves to be futile and it is highly recommended that it is better to handle the sessionFactory by ourselves rather than clinging to Spring and depending on it for handling the sessions for us! As such, this proves to be the first level of Spring and Hibernate integration and is a good option for a newbie!
  3. Using HibernateDaoSupport
  4. The process of writing SampleDaoImpl extends HibernateDaoSupport is not doubt a very good option. Here, we would then be using no callbacks and session  = getSession(false) rather than setting the hibernate template via the session factory. This is emphatically a very remarkable API provided by Spring for integration with hibernate and is surely better than the option 1 discussed above since this allows throwing of checked exception within the data access code.
  5. Using plain Hibernate with hibernate.cfg.xml
  6. While this proves to be the mos traditional way of implementation, this is just for the hibernate fans. I am not for such an implementation since there is no need for writing code as given below:
    Session session = HibernateUtils.getSession();
    Transaction tx = session.beginTransaction(); o);//o is the incoming object to be persisted
    (Exception e)
    //code to handle exception
  7. Using Autowiring of the SessionFactory
  8. As far as i see, this is the best way of integrating spring with hibernate. This is not only the latest and the updated way of integration, this proves to be the best solution for designing web application where the developer has a hold on the sessions and transactions though Spring does this in its own way
    <br /><br /><?xml version="1.0" encoding="utf-8"?><br /><beans xmlns="" xmlns:xsi="" xmlns:p=""<br />xmlns:context="" xmlns:jee="" xmlns:tx=""<br />xsi:schemaLocation=""><br /><br /><!-- Auto-detection of the DAOs --><br />    <context:component-scan base-package="webapp.dao" /><br />    <context:property-placeholder location="WEB-INF/" /><br /><!--<context:property-override location="WEB-INF/"/>--><br />    <br />    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"<br />    p:username="${jdbc.username}" p:password="${jdbc.password}" p:maxActive="${dbcp.maxActive}" p:maxIdle="${dbcp.maxIdle}" p:maxWait="${dbcp.maxWait}" /><br />    <br />    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" p:dataSource-ref="dataSource"<br />    p:configurationClass="org.hibernate.cfg.AnnotationConfiguration" p:packagesToScan="webapp.model"><br />        <property name="hibernateProperties"><br />            <props><br />                <prop key="hibernate.dialect">${hibernate.dialect}</prop><br />                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop><br />                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop><br />                <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop><br />            </props><br />        </property><br />       <br />    </bean><br />    <br /> <tx:annotation-driven transaction-manager="txnManager"/> <br /> <bean id="txnManager"<br />        class="org.springframework.orm.hibernate3.HibernateTransactionManager"<br />        p:sessionFactory-ref="sessionFactory"/><br /><br /></beans><br />
    The corresponding DAO class is as below
    @Repository<br />@Transactional<br />public class SampleDaoImpl implements SampleDao {<br /><br />  @Autowired<br />  SessionFactory sessionFactory;<br />

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Mar 31, 2010

How to Use Log4j?

A very simple incorporation of log4j is here!If you really want to know as to how to incorporate log4j logging in your application, here are the details. Though this is simple, I see a bunch of questions related to this in every java related forum and hence I thought of posting this blog!

  • Let us have a simple Bean.xml and Bean.class. the xml file has the bean definition and the bean class just prints a string. This is a very simple application written to make you all understand the incorporation of log4j!

  • Just create a Spring Project in eclipse (since am using a bean and bean.xml is being used for configuring the bean). The project hierarchy is as shown below. You also have a file (empty file) in the classpath of this project as shown below:

  • Select the project.Right click and go to properties. Here you can add the required jars. For the implementation of log4j in a spring project, you would need
  1. Spring jars (all the 3.0 version jars)
  2. log4j.jar(latest)
  • Now add the following code to your

# Set root category for logging error messages

# Debug statements logged by Spring framework., AppAppender

#AppAppender is set to DailyRollingFileAppender and new file rolls every day.

  • Now just run as a java application. Only errors get printed in the log gile.

If you want to change the level of logging, you can make the warninggs or information to get printed in the log file by changing the log4j.rootCategory to INFO, WARN etc.

  • If you have a directory hewrarchy in your application, you can enable logging levels for each of the package by adding an entry as

<br /><br /><your package structure>==ERROR, AppAppender<br /><br />

  • AppAppender is nothing but a file in the logs folder under c: whose layout, date pattern and type are as described in the code above. Here, it is a daily rolling appender. A new file gets created everyday and the old file is stored after being renamed with proper dates.

Spring Explorer View in Eclipse 3.5

I am working with Spring 3.0 and I use Eclipse as my IDE. As a novice in the arena of Spring, I was pretty much curious to make use of STS! Developers who are using Spring are really fortunate to have the STS plug-in in eclipse. That is simple awesome and cool!!

The details of installation and configuration for a simple project is given below in this post. I was working at it yesterday and thought of sharing this to all since what took 4-5 hours for me would just be completed in minutes for you!

  • From Eclipse --> Help --> Install New Software and by making use of the update site SpringSource Update Site for Eclipse 3.5, I was able to configure STS in my eclipse Galilee with ease. Please find the figure below and ensure that the following are checked when you get ahead to the update site for the installation of STS
  • On clicking Next and Finish, you should be able to get through the installation within minutes!
  • After this,Restart Eclipse!
  • Once you do this, right click on your project and click Spring Tools --> add Spring Project Nature as shown below
  • On adding the Spring nature to your web application, your project in eclipse would show up as given below:
  • Further to this, go to Project --> Properties --> spring. I am considering a simple spring application. Enable Project specific settings in this window that comes up
  • In project validators tab, ensure that Spring validators and Bean validators are checked as shown below:
  • In project builders tab, ensure that AOP Reference Model Builder and Spring Bean Meta Data Builder are checked as shown below. Then click ok
  • After this, goto Beans Support under Spring as shown below. Here scan and select the list of configuration xml files that you have in your spring application.
  • Once you do this, goto Project menu --> Check the entry 'Build Automatically'
  • Now select the project in the Package Explorer and then go to Window menu --> view --> Other. Here click on Spring Explorer to see the bean and config file listing as shown below. Right click on the xml file and from the context menu, click @RequestMappings

Awesome!!You would be able to see all the request mappings within your application in a single screen view here!!!Pretty awesome and very useful indeed!!!!!The Spring Explorer view in STS is just too cool and superb!! Hats off to the Spring tool developers who did this great work in the customization of Spring Explorer view in Eclipse!

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Mar 30, 2010

Spring Framework Fundamentals: A PPT

Here is a power point presentation for those who are very new to Spring Framework. I prepared it for my use and thought of putting it up in my blog since that would be useful for some one too!!!

The spring fundamentals ppt is available in the following location.

PPT on Spring Basics

Do post in your comments if the spring basics ppt was really useful for you!

Feb 2, 2010

How to Use ORDER BY and LIMIT/TOP to limit Records in HIBERNATE?

In SQL, we have been used to writing queries with ORDER BY eother DESC or ASC. And to limit the number of resocrd retrieved from teh database, we generally use LIMIT or TOP and mention the number of records that we intend to retrieve from the database.

Being in hibernate for long, I have had situations where I would require the first record of the list. At first, when I came across such a situation,, I went ahead and wrote a named query that was as follows:

select s from Student as s where in (:sIdList) and s.age=:age ORDER BY s.age DESC LIMIT 1

When I executed this query, there was absolutely no errors that were visible. As such I thought that this would work. Since I was getting a getting a single record from DB, I used the following in my DAO

<br />Student student = (Student)session.getNamedQuery("findStudent")<br />   .setInteger("age", studAge)<br />   .setParameterList("sIdList", sIdList)<br />   .uniqueResult();<br />

Even this did not show up any error till there was only one record which matched the above criteria. But if you have multiple records in the DB that matches the criteria given, then you would have the following exception

You either get a NonUniqueResult exception or ClassCastException at the DAO when multiple records match the criteria. Though the ORDER BY works, the LIMIT does not limit the number of records retrieved and as such a list of obtained from the DB instead of a single record.

So, the best way to handle such cases would be the following. You can make use of ORDER BY in the query and setMaxResults(int) in the DAO to overcome this problem and to get the first record from the list. Here is how it is:

<br />Student student = (Student)session.getNamedQuery("findStudent")<br />   .setInteger("age", studAge)<br />   .setParamterList("sIdList", sIdList)<br />   .setMaxResults(1)<br />   .uniqueResult();<br />

In this case the query should have been as follows:

<br />select s from Student as s where in (:sIdList) and s.age=:age ORDER BY s.age DESC <br />

I felt that this was pretty useful and hence thought of sharing with you all!! More tips ahead! Stay tuned!

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Jan 26, 2010

Show/Hide and Disable Click of Radio Buttons in JQuery

Here is a nice code snippet that can help you really while you work with radio buttons and jquery!

When you have a group of radio buttons, you might want to hide all of them when one is selected and submitted.

Here is the code that can hide the radio buttons for you: (assuming that the name of the radio button that you give to all of them is "answers")


Yet another interesting code snippet that might help you while you work with radio buttons is as given below:

There are times when you feel like disabling the click of the radio button based on certain conditions. Following code helps you in disabling the click on the radio button when the radios are actually hidden and the corresponding texts are visible. (name of the radio buttons is given as "radios")

<br />$('input[name="radios"]').each(function() {<br />$(this).click(function(){ <br />// test if radio is hidden<br />if ( $(this).is(':hidden') ) { <br /> return false;<br /> } else {<br /> return true;<br /> }<br />});<br />});<br />

How to Resolve java.lang.NoSuchMethodError: javax.persistence.Persistence.getPersistenceUtil()Ljavax/persistence/PersistenceUtil?

I had a chance to have a look the new features of Spring 3.0 today. The validation and formatting that is implemented as a part of JSR-303 implementation seems to be very exciting and interesting. Of course, it made me feel that we are moving towards codeless web based applications sooner or later!

I was very much curious to do a proof-of-concept application for this implementation. So I downloaded the Spring3.0 jars and made use of Hibernate Validator 4.0.2 GA version and validation-api-1.0.0 GA version.I had been using java 1.5

After removing all the old jars and even after implementing everything whatever was required, I was stuck with the following error

java.lang.NoSuchMethodError: javax.persistence.Persistence.getPersistenceUtil()Ljavax/persistence/PersistenceUtil

Please find the stack trace below:

<br />SEVERE: Servlet.service() for servlet springapp threw exception<br />java.lang.NoSuchMethodError: javax.persistence.Persistence.getPersistenceUtil()Ljavax/persistence/PersistenceUtil;<br /> at org.hibernate.validator.engine.resolver.JPATraversableResolver.isReachable(<br /> at org.hibernate.validator.engine.resolver.DefaultTraversableResolver.isReachable(<br /> at org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver.isReachable(<br /> at org.hibernate.validator.engine.ValidatorImpl.isValidationRequired(<br /> at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(<br /> at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForRedefinedDefaultGroup(<br /> at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(<br /> at org.hibernate.validator.engine.ValidatorImpl.validateInContext(<br /> at org.hibernate.validator.engine.ValidatorImpl.validate(<br /> at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(<br /> at org.springframework.validation.DataBinder.validate(<br /> at<br /> at<br /> at<br /> at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(<br /> at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(<br /> at org.springframework.web.servlet.DispatcherServlet.doDispatch(<br /> at org.springframework.web.servlet.DispatcherServlet.doService(<br /> at org.springframework.web.servlet.FrameworkServlet.processRequest(<br /> at org.springframework.web.servlet.FrameworkServlet.doPost(<br /> at javax.servlet.http.HttpServlet.service(<br /> at javax.servlet.http.HttpServlet.service(<br /> at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(<br /> at org.apache.catalina.core.ApplicationFilterChain.doFilter(<br /> at org.apache.catalina.core.StandardWrapperValve.invoke(<br /> at org.apache.catalina.core.StandardContextValve.invoke(<br /> at org.apache.catalina.core.StandardHostValve.invoke(<br /> at org.apache.catalina.valves.ErrorReportValve.invoke(<br /> at org.apache.catalina.core.StandardEngineValve.invoke(<br /> at org.apache.catalina.connector.CoyoteAdapter.service(<br /> at org.apache.coyote.http11.Http11Processor.process(<br /> at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(<br /> at$<br /> at<br />

It was almost 6-8 hours, I kept trying to do away with this problem since a colleague of mine seemed to get away with it in java 1.5. The following were the pointers that I understood as a result of my research googling the Internet!
  • The org.springframework.validation.beanvalidation.LocalValidatorFactoryBean while calling the SpringValidatorAdapter's validate(), invokes the Hibernate validator's ValidatorImpl.validate() method.
  • The hibernate validoator 4.0.2 GA version has a very strong dependency on JDK6 which contains the Persistence class with javax.persistence.Persistence.getPersistenceUtil()
So,I finally upgraded my machine to Java 6. It was just a miracle. Everything started working without problems and errors disappeared!!!

Jan 5, 2010

Resource Out of Sync With the File System in Eclipse: How To fix?

If you come across the error 'Resource out of sync with the file system' while working with eclipse, you can fix it within a minute. Get to know the root cause and you can fix it within minutes.

Root cause of 'Resource out of sync with the file system'

It is likely that you would have edited the file from outside eclipse environment and hence when you try to access the file from eclipse after this, you would get this problem.

Solution for 'Resource out of sync with the file system'

  1. Right click on the file from within eclipse.
  2. Click Refresh
  3. Now try to open the file in eclipse again.
  4. Error  is gone!
  5. You can got Windows. Point to Preferences. Click on General. Go to Workspace and check the box ' Refresh Automatically' as shown in the figure below. The problem 'Resource out of sync with the file system' would never pop in again!

(function($){ }) JQuery : What It Really Is?

Today I happen to use the code snippet

(function($){ })(jQuery);

But, for around an hour, I was wondering as to what the above function really does? what is the use of wrapping functions like


inside the above?

After a bit of research, I understood what it really does and that is awesome. This post further gives you a heads up on what

(function($){ })(jQuery);

is in detail.

The $ in

(function($){ })(jQuery);

can be considered to be prototype reference outside the function call. This $ becomes a jquery reference inside the function. as a result, even if this $ variable or function is being used by any other javascript library, this reference overwrites all and proves to be a nice jquery reference well within the function.

Generally you can expect to see all JQuery plug-ins to be written inside this function where $ is being passed as a parameter. Before we take a look at jQuery plug-ins, consider the code snippet below:

var userDefinedFunction = function ($) { 
  //your code here
userDefinedFunction (jQuery);

is equivalent to

(function ($) { 
    //your code here

Having discussed this, let me give you ahead up on writing customized plug-ins. Just follow the steps below and your customized JQuery plug-in is ready!

  1. Let us consider that we write a plugin by name sample.
  2. You have to have a file jquery.sample.js
  3. Within the file we can have methods for the plug-in. For this, you need to extend the JQuery object as follows:
  4. (function($){  
    $.fn.sample = function() {});
  5. You can now access this function using the below code in your html file:
  6. <script language="javascript" type="text/javascript">
                $('#<form name>').sample();
  7. Default settings for this plug-in is created by using the code

    $.fn.sample = function(options) 
    {var defaults = {inputVal: 1, trueVal : 'true', falseVal : 'false',submitButton : '#submit'}
    var pluginOptions = $.extend(defaults, options);

  8. If ever you intend to call this function with new values which are different from the default values, use the following snippet and get it done!
  9. <script language="javascript" type="text/javascript">
                $('#<form name>').sample({inputVal:2, trueVal:'yes',falseVal:'no', submitButton:'#ClickMe');
  10. As such, this was a nice learning and a great heads up on JQuery plug-ins!But, there are much more interesting tips to come! Stay tuned!