My experience with Git

Few days ago I came to know about git, so to give it a try I created an account on github. To those who doesn’t know much about it GIT is a fast version control system :). Since I’m using windows I’ve to download a git client, so the first google result that came on typing “git window” was “msysgit”. Msysgit comes with 2 options “gitbash” a command line utility and git ui so you can use any of them, for initial learning perspective I preferred GitBash.

I’ll not explain the concepts of git as there is lot of information available on the net
http://en.wikipedia.org/wiki/Git
http://git-scm.com/

So first I’ve to create a remote repository. GitHub provides online project hosting using git, they have different plans as according to your needs. I’ve created a free account so I can create public repostiories, which means anybody can checkout the code and you can allow people to modify the code. If you want to create private repository then you have to create a paid account, they have multiple plans as per your need https://github.com/plans. So my user at github is sandy724.

In next blog I will discuss how I’ve used GitBash for synching up the code with remote repository

Equals implementation for Lazy loaded objects in Hibernate

Most of you already know about the standard way to implement equals and hashCode for a class. As an example lets consider a User class


public class User {
private Long id;
private String name;
private String address;
}

If we consider Id as unique identifier for logical equality of users then the equals and hashCode method can be written over “id”, as given below


@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}


@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}

Now lets assume User is an entity thats managed by hibernate and is lazily loaded. So actually you will be interacting with the proxy(HibernateProxy) of User and not the actual User class.

Now in this the equals implementation of User class will fail. If we check for equality of normal instance of User class with the proxy instance of User the equals method will return false. The reason for failure is the class check i.e


if (getClass() != obj.getClass())
return false;

Since the class of Proxy user object is not User but a HibernateProxy class.

To overcome this problem hibernate comes with a utility class HibernateProxyHelper which is used to get the actual class if the object passed to it is of type HibernateProzy. The above piece of code can be replaced with


if (  HibernateProxyHelper.getClassWithoutInitializingProxy(obj) != getClass() ) {
return false;
}

Another problem with the implementation of equals in case of proxy objects is we cannot directly access the fields i.e


if (!id.equals(other.id))
return false;

as proxy objects can access only the methods of the underlying object so instead of directly accessing the field we have to use the getter method


if (!id.equals(other.getId()))
return false;

So the updated equals implemention that should work perfectly fine in case of proxy objects also will be as given below


public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (  HibernateProxyHelper.getClassWithoutInitializingProxy(obj) != getClass() ) {
return false;
}
User other = (User) obj;
if (id == null) {
if (other.getId() != null)
return false;
} else if (!id.equals(other.getId()))
return false;
return true;
}

XStream Int parsing issue

This blog is about issue in parsing int data from an xml.
While working with XStream I experienced a problem, if the xml comprises an int data beginning from 0 XStream was throwing an Exception ConversionException. On digging deeper I patterned out that the converter(IntConverter) used to convert the string value into corresponding integer value was causing problem. If the string had 0 as prefix then that string is treated as an octal value and it try to decode it as an octal value. That’s why when a value such as 089 is processed by this converter, the converter processed that value as an octal and tried to decode it and since 8 & 9 are not in octal base that’s why converter was throwing this exception. To get the better of this problem you can either have the numeric values in xml without following 0s or you can write your own converter.

Template design pattern in action part1

So finally I got time to complete the blog 🙂

I’ll discuss about how we can solve the problem using templating design pattern. So what we have done, we have written a Template class “CacheTemplate” having a method getCachedData.
getCachedData takes 2 parameters
key: Key for which we have data cached
cacheCallback: If we don’t have data cached then we will call this cacheCallback to get the data and store it into cache.


public class CacheTemplate {
private CacheProvider cacheProvider;
public  T getCachedData(String key,
CacheCallback cacheCallback) {
T data = (T) cacheProvider.get(key);
if (data == null) {
data = cacheCallback.cacheOperation();
cacheProvider.put(key, data);
}
return data;
}
}

Now taking forward the example taken in previos blog, let us apply this template to the “getPersons” method


public List getPersons() {

return cacheTemplate.getCachedData("persons", new CacheCallback>() {
@Override
public List cacheOperation() {
_getPersons();
}
}
}

private List _getPersons() {
persons = //Business logic to get persons;
return persons;
}

Now if you compare the current implementation with the previous implementation and check the concerns we had they all are resolved.
1.) Now our business logic of retrieving the persons is at one place.
2.) Now we have a generic implementation of managing cache.

Property file reader

In my current project we have some property files and we need to read properties from those property files, so we come up with an approach to read property files. The main points that we need to focus was
1.) The properties should be loaded only once, In a way we need singleton behavior
2.) We can have multiple property files
One assumption that we have is property files will always be located in root class path

Now for the solution of this problem we thought of using Enum (effective java ;)) as they internally provide the feature of singleton behavior, also for multiple property file situation we created multiple instances corresponding property file.

So the code that we have written is like this


public enum PropertiesReader {
     SEARCH("search.properties"),APP("app.properties");

     Properties properties;
     private Logger log = LoggerFactory.getLogger(PropertiesReader.class);

     private PropertiesReader(String propertyFile) {
   properties = new Properties();
          try {
               InputStream inputStream =    this.getClass().getClassLoader().getResourceAsStream(propertyFile);
               properties.load(inputStream);
          }
          catch (IOException e) {
               log.error(propertyFile + " was not found in classpath");
          }
   }

     public String getValue(String key) {
          return (String) properties.get(key);
     }
}

So now
if we want to read a property from search.properties file
assertThat(PropertiesReader.SEARCH.getValue(“max.pages.to.display”)

if we want to read a property from app.properties file
assertThat(PropertiesReader.APP.getValue(“debug_mode”)

JSR-303

JSR-303
The main idea behind JSR-303 is to have a common approach for validation at all places of the application in a simplistic way. The bean validation is built keeping in mind the validation process as a kind of meta information for a bean, so if you say that a property of bean should be not null or the content of a bean property should match to the format of e-mail or telephone. Such kind of information can be treated as meta-information of bean properties. One of the other motive for having JSR-303 into picture is to remove the boilerplate code introduced due to the need of bean validation at multiple places in the application, such as at UI level, while persisting a bean or performing some business operation.

JSR-303 provides bean validation using two ways, either you can configure validations using annotations on properties or using a XML validation descriptor. Annotations can be used as Meta-data for bean validation in case of some simple validations such as not null, e-mail, telephone number check. XML validation descriptor is used for some complex validations or context aware validation.

JSR-303 also defines API for Java Bean validation, so this API can be used to programmatically validate the bean .

Bean validation JSR-303

In my current project we are working on a web-application using JBoss Seam. One of the very common requirements while working on a web application is validating the data contained in a bean. Seam is powered with annotation based validation, seam uses Hibernate Validator for this feature. Hibernate validator is a reference implementation of Bean Validation (JSR-303).JSR-303 defines a meta-data model and API for JavaBean validation based on annotations.
In my coming posts I’ll be focussing on JSR-303 and it’s reference implementations. Some of the posts I’m thinking of right now
– Bean Validation JSR-303
– Hibernate Reference implementation
– Using Hibernate Validation, accessing it programmatically
– Creating custom annotation validator