Friday, April 20, 2012

Setting up JNDI with Jetty (Embedded)

I was running embedded Jetty on my development work-space saving some time on vicious cycle of compiling and deployment. I have not worked with Jetty much and the ease of use made me hook on to it. I was in need to setup JNDI in order to retrieve a connection pool for my database related activities. Though there were comprehensive documentation in some places, most were scattered. So this post is intended to be your one stop place for the requirement of setting up JNDI with Jetty. If it does not, please do leave a comment and i will be glad to help you out.

So starting off, first let us see how to setup Jetty to run as an embedded server. The folder structure of my eclipse project is as follows;



The etc folder will consist of all the configuration files required by jetty. You can download jetty from here. For this example i have used jetty-6.1.26.

Include the following jars from the given folder locations;


lib
jetty-x.x.xx.jar, jetty-util-x.x.xx.jar,servlet-api-x.x.jar
lib/plus
jetty-plus-x.x.xx.jar
lib/naming
jetty-naming-x.x.xx.jar


For my example, i have set up mysql and therefore mysql-connector jar is also included in my library path.

Copy all the files residing in your jetty installation's etc directory to the etc directory of your eclipse project.

In order to enable JNDI, we first need to include jetty-plus. There are many ways you can do this such as providing it as a run-time argument, including it within your own jetty-env.xml residing in your WEB-INF or copying and pasting the required xml snippets from the jetty-plus.xml to your jetty.xml. I have chosen the latter. Hence, i have included the following snippet within my jetty.xml;


   <Array id="plusConfig" type="java.lang.String">
    <Item>org.mortbay.jetty.webapp.WebInfConfiguration</Item>
    <Item>org.mortbay.jetty.plus.webapp.EnvConfiguration</Item>
    <Item>org.mortbay.jetty.plus.webapp.Configuration</Item>
    <Item>org.mortbay.jetty.webapp.JettyWebXmlConfiguration</Item>
    <Item>org.mortbay.jetty.webapp.TagLibConfiguration</Item>
  </Array>

<call name="addLifeCycle">
      <arg>
        <new class="org.mortbay.jetty.deployer.WebAppDeployer">
          <set name="contexts"><ref id="Contexts"></ref></set>
          <set name="webAppDir"><systemproperty default="." name="jetty.home">/webapps</systemproperty></set>
          <set name="parentLoaderPriority">false</set>
          <set name="extract">true</set>
          <set name="allowDuplicates">false</set>
          <set name="defaultsDescriptor"><systemproperty default="." name="jetty.home">/etc/webdefault.xml</systemproperty></set>
          <set name="configurationClasses"><ref id="plusConfig"></ref></set>
        </new>
      </arg>
</call>
Next up, you need to add the XML fragment related to your data-source into your jetty.xml. I have added the snippet required for mysql. For any other database, please check this link.
 
  <New id="myds" class="org.mortbay.jetty.plus.naming.Resource">

     <Arg>jdbc/MySQLDS</Arg>
     <Arg>
        <New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
           <Set name="Url">jdbc:mysql://localhost:3306/test</Set>
           <Set name="User">root</Set>
           <Set name="Password">password</Set>
        </New>
     </Arg>
</New>
Now that we have setup everything, all you need to do is run jetty in your embedded environment. Following code shows you how to run Jetty in the embedded mode as part of your main class;
 
import java.io.File;

import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerList;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.xml.XmlConfiguration;




public class JettyTest {

 public static void main(String[] args) throws Exception {
  Server jetty = new Server();
  String[] configFiles = {"etc/jetty.xml"};
  for(String configFile : configFiles) {
  XmlConfiguration configuration = new XmlConfiguration(new File(configFile).toURI().toURL());
  configuration.configure(jetty);
  }
  
  WebAppContext appContext = new WebAppContext();
  appContext.setContextPath("/myapp");
  File rd = new File("path_to_your_war_file");
  appContext.setWar(rd.getAbsolutePath());
  HandlerList handlers = new HandlerList();
  handlers.setHandlers(new Handler[]{ appContext, new DefaultHandler()});
  jetty.setHandler(handlers);
  jetty.start();
 }
}

Thats about it. Now you can look up your data-source which is exposed from Jetty. For ease, i have configured it with Spring's JNDIObjectFactoryBean. One important aspect to note is the jndi provider URL and the initial context factory entries required for Jetty.
 
  <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
        <property name="environment">
            <props>
                <prop key="java.naming.factory.initial">org.mortbay.naming.InitialContextFactory</prop>
                <prop key="java.naming.provider.url">org.mortbay.naming</prop>
            </props>
        </property>
    </bean>
    
    <bean id="jndiDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
   
        <property name="jndiTemplate">
          <ref bean="jndiTemplate"/>
        </property>
        <property name="jndiName">
              <value>jdbc/MySQLDS</value>
        </property>
      </bean>
With that you have all that you need to configure JNDI and access it through Spring's JNDI template. One other thing i was interested in was remote debugging with jetty server. After some searching i found that you need to include the following in your runtime configuration as VM arguments;
-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
This will enable you to remote debug your application on port 8000. If there are any queries please do leave a comment and i will be more than happy to help anyone. And ofcourse if you do see any error, leave a reply too which again is much appreciated :).
Good day to you all and thank you for taking the time to read!!

Wednesday, January 11, 2012

Understanding Java References

Playing around with Java References:

I could not pay attention to the blog in the recent times and first and foremost I must apologize for not staying in touch with you all in the world of technology. I recently stumbled upon the java.lang.ref package which was available since Java 1.2 but ironically i got to know about it just a few days back. Going through a few articles explaining about the various reference types and the java doc as well, I was very much intrigued and was anxious to get my hands dirty with some reference related code.

Im not going to talk about each reference class available within the java.lang.ref package as it is already very well explained here. Let us take a look at the following code snippet which I wrote to understand the basic operation of a WeakReference.

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class ReferencesTest {

 private WeakReference<Map<Integer, String>> myMap;

 public static void main(String[] args) {
  new ReferencesTest().doFunction();
 }

 private void doFunction() {

  Map<Integer, String> map = new HashMap<Integer, String>();
  myMap = new WeakReference<Map<Integer, String>>(map);

  map = null;
  int i = 0;
  while (true) {
   if (myMap != null && myMap.get() != null) {
    myMap.get().put(i++, "test" + i);

    System.out.println("im still working!!!!");
   } else {

    System.out
      .println("*******im free*******");

   }

  }
 }
}
First I have defined a weak reference instance variable to which I assign an instance of a HashMap initialized within the doFunction() method. Then data is input to the map via the weak reference instance and not directly through the concrete instance of the hashmap we created. We check for the map being null due to the fact of the way WeakReferences work.

During the execution of the program, a weak reference will be the first to be garbage collected if there are no soft or strong references binding to it. So if memory is considerably low, or when and if the garbage collector deems appropriate, the weak reference is garbage collected and this is why I have included the else statement within my code to show the occurrence of that situation. Run this by setting minimum –Xms and –Xmx to understand how it works since otherwise you will have to wait a longer period to get an out of memory exception. And then change the WeakReference implementation to a SoftReference implementation and see that the program actually crashes after a few iterations. This is due to the fact that SoftReferences only gurantee to clean up memory just before a OutOfMemory error occurs. But with the WeakReference, the program continues to function without halting because it is almost always eligible for garbage collection and we can reinitialize the cache and continue to repopulate our cache.

The good thing about weak reference is that in my opinion it is one of the best ways to implement an in-memory cache which we usually implement ourselves when we need to keep data that do not consistently change but frequently accessed in memory and when the cost of going for a fully-fledged caching implementation like the JBoss cache or EHCache is too much. Quite often I have implemented caching solutions and have also seen production code similar to the following code snippet;

import java.util.HashMap;
import java.util.Map;

public class CacheTest {

 private Map<String, Object> myAwesomeCache = new HashMap<String, Object>(100);
 
 public Object getData(String id){
  
  Object objToReturn = null;
  
  if(myAwesomeCache.containsKey(id)){
   objToReturn = myAwesomeCache.get(id);
  }else{
   // retrieve from the database and populate the in memory cache map
  }
  
  return objToReturn;
 }
}


This is just a very basic level implementation to put out the idea across that we sometimes do use Maps to construct in-memory caching implementations. The fact that we have to note is that though there is nothing intrinsically wrong with this implementation, in an instance where your application is running low on memory, it would be a ideal if the garbage collector could remove this from memory to free up some for the other processes that need it. But since this map is a strong reference, there is no way the garbage collector can mark this reference as eligible for collection. A better solution would be to change the caching implementation from HashMap to a WeakHashMap.

The Javadoc specifies the following about the WeakHashMap;

         "A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will   automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations."

So in retrospect, I believe whenever you are in need of an in-memory caching implementation and memory is of utmost importance to you, using a WeakHashMap would be beneficial.

That concludes my findings on the Reference package and I invite you all to share your experience in this regard which is highly appreciated.

Cheers



Tuesday, November 8, 2011

Hibernate by Example - Part 2 (DetachedCriteria)

So last time we helped out justice league to effectively manage their super heroes. Today we focus on how The Avengers will be using Hibernate's Detached Criteria to find out their enemies with respect to each superhero so as to protect their super heroes. You can download the working example from here.

In this example we take only two entities into consideration. The Avenger & The Villain. We build a relationship between the two using a join table. Let us have a look at the domain mappings used in this example.




package com.avengers.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

/**
 * The domain class representing each member of the avengers
 * 
 * @author Dinuka.Arseculeratne
 * 
 */
@Entity
@Table(name = "Avengers")
public class Avenger implements Serializable {

 /**
  * The primary key of the Avenger table
  */
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "avenger_id")
 private Long avengerId;

 /**
  * The name of the avenger member
  */
 @Column(name = "avenger_name")
 private String avengerName;

 /**
  * A flag which holds whether the avenger's powers are awesome
  */
 @Type(type = "yes_no")
 @Column(name = "is_awesome")
 private boolean isAwesome;

 /**
  * The list of enemies the avenger has
  */
 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
 @JoinTable(name = "AVENGERS_AND_VILLAINS", joinColumns = { @JoinColumn(name = "avenger_id") }, inverseJoinColumns = { @JoinColumn(name = "villain_id") })
 private List<Villain> enemyList = new ArrayList<Villain>();

 public Long getAvengerId() {
  return avengerId;
 }

 public void setAvengerId(Long avengerId) {
  this.avengerId = avengerId;
 }

 public String getAvengerName() {
  return avengerName;
 }

 public void setAvengerName(String avengerName) {
  this.avengerName = avengerName;
 }

 public boolean isAwesome() {
  return isAwesome;
 }

 public void setAwesome(boolean isAwesome) {
  this.isAwesome = isAwesome;
 }

 public List<Villain> getEnemyList() {
  return enemyList;
 }

 public void addEnemy(Villain enemy) {
  enemyList.add(enemy);
 }

 @Override
 public String toString() {
  return "Avenger [avengerId=" + avengerId + ", avengerName="
    + avengerName + ", isAwesome=" + isAwesome + ", enemyList="
    + enemyList + "]";
 }

 
}

This class maps an avenger. I have used minimal fields in order to keep this example as simple and short as possible. And the Villain domain looks as follows;
package com.avengers.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

/**
 * This class represents the Villain forces against the avengers
 * 
 * @author Dinuka.Arseculeratne
 * 
 */
@Entity
@Table(name = "Villains")
public class Villain implements Serializable {

 /**
  * The primary key of the Enemy table
  */
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "villain_id")
 private Long villaiId;

 /**
  * The name of the enemy
  */
 @Column(name = "villain_name")
 private String villainName;

 /**
  * A flag which checks whether the villain is super awesome
  */
 @Type(type = "yes_no")
 @Column(name = "is_awesome")
 private boolean isAwesome;

 public Long getVillaidId() {
  return villaiId;
 }

 public void setVillaidId(Long villaidId) {
  this.villaiId = villaidId;
 }

 public String getVillainName() {
  return villainName;
 }

 public void setVillainName(String villainName) {
  this.villainName = villainName;
 }

 public boolean isAwesome() {
  return isAwesome;
 }

 public void setAwesome(boolean isAwesome) {
  this.isAwesome = isAwesome;
 }

 @Override
 public String toString() {
  return "Villain [villaiId=" + villaiId + ", villainName=" + villainName
    + ", isAwesome=" + isAwesome + "]";
 }

}

Ok now that we have defined our domains, let us see how data retrieval happens with DetachedCriteria. I have used DetachedCriteria here because The Avengers were very specific and said they do not want anything to do with the Hibernate session, so hence i used DetachedCriteria which does not require a hibernate session to be present.

Our primary objective is to retrieve The Avenger to whom a villain belongs to. Note that this assumes the same villain cannot be a villain to more than one superhero. So moving on i give below the method that retrieves an avenger based on the villain name passed.

public Avenger retrieveAvengerByVillainName(String villainName) {

  Avenger avenger = null;
  /**
   * Selected a detached criteria so we do not need a session to run it
   * within.
   */
  DetachedCriteria criteria = DetachedCriteria.forClass(Avenger.class);

  /**
   * Here we are doing an inner join with the Villain table in order to do
   * a name comparison with the villainName passed in as a method
   * parameter
   */
  DetachedCriteria villainCriteria = criteria.createCriteria("enemyList");

  villainCriteria.add(Restrictions.eq("villainName", villainName));

  villainCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

  @SuppressWarnings("unchecked")
  List<Avenger> avengerList = getHibernateTemplate().findByCriteria(
    criteria);

  if (!avengerList.isEmpty()) {
   avenger = avengerList.get(0);
   getHibernateTemplate().initialize(avenger.getEnemyList());
  }
  return avenger;

 }
In this method what we do is first we create a criteria for our master class which in this case is Avenger.class. Then we need to do a join with the Villain table and hence we create a sub criteria from our main criteria with the name of the list we defined within the Avenger domain class. Then it is a matter of equaling the property of the Villain domain to the villain name passed in.

The power of the Criteria API is such that you can create dynamic queries with ease which would be a hassle if we were to use pure HQL which would require substantial string concatenations in order to achieve the same.

A sample test class called AvengerTest.java is given with the attachment which you can find at the top of the most. Note that you need to remove the comment on avenger-context.xml in order to create the tables needed for this example. So that is about it.

The Avengers can be risk averse now that they have a system by which they can relate any super villain to a super hero within their league.

As always your comments and suggestions are always welcome and appreciated.

Thank you for taking the time to read!!!!

Tuesday, September 6, 2011

Hibernate by Example - Part 1 (Orphan removal)

So i thought to do a series of hibernate examples showing various features of hibernate. In the first part i wanted to show about the Delete Orphan feature and how it may be used with the use of a story line. So let us begin :)  

Prerequisites:
In order for you to try out the following example you will need the below mentioned JAR files:


  • org.springframework.aop-3.0.6.RELEASE.jar
  • org.springframework.asm-3.0.6.RELEASE.jar
  • org.springframework.aspects-3.0.6.RELEASE.jar
  • org.springframework.beans-3.0.6.RELEASE.jar
  • org.springframework.context.support-3.0.6.RELEASE.jar
  • org.springframework.context-3.0.6.RELEASE.jar
  • org.springframework.core-3.0.6.RELEASE.jar
  • org.springframework.jdbc-3.0.6.RELEASE.jar
  • org.springframework.orm-3.0.6.RELEASE.jar
  • org.springframework.transaction-3.0.6.RELEASE.jar.
  • org.springframework.expression-3.0.6.RELEASE.jar
  • commons-logging-1.0.4.jar
  • log4j.jar
  • aopalliance-1.0.jar
  • dom4j-1.1.jar
  • hibernate-commons-annotations-3.2.0.Final.jar
  • hibernate-core-3.6.4.Final.jar
  • hibernate-jpa-2.0-api-1.0.0.Final.jar
  • javax.persistence-2.0.0.jar
  • jta-1.1.jar
  • javassist-3.1.jar
  • slf4j-api-1.6.2.jar
  • mysql-connector-java-5.1.13-bin.jar
  • commons-collections-3.0.jar

For anyone who want the eclipse project to try this out, you can download it with the above mentioned JAR dependencies here.

Introduction:

Its year 2011. And The Justice League has grown out of proportion and are searching for a developer to help with creating a super hero registering system. A developer competent in Hibernate and ORM is ready to do the system and handle the persistence layer using Hibernate. For simplicity, He will be using a simple stand alone application to persist super heroes. This is how this example will layout:

  • Table design
  • Domain classes and Hibernate mappings
  • DAO & Service classes
  • Spring configuration for the application
  • A simple main class to show how it all works
Let the Journey Begin......................


Table Design:

The design consists of three simple tables as illustrated by the diagram below;





As you can see its a simple one-to-many relationship linked by a Join Table. The Join Table will be used by Hibernate to fill the Super hero list which is in the domain class which we will go on to see next.

Domain classes and Hibernate mappings:

There are mainly only two domain classes as the Join table in linked with the primary owning entity which is the Justice League entity. So let us go on to see how the domain classes are constructed with annotations;

 
package com.justice.league.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

@Entity
@Table(name = "SuperHero")
public class SuperHero implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6712720661371583351L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "super_hero_id")
	private Long superHeroId;

	@Column(name = "super_hero_name")
	private String name;

	@Column(name = "power_description")
	private String powerDescription;

	@Type(type = "yes_no")
	@Column(name = "isAwesome")
	private boolean isAwesome;

	public Long getSuperHeroId() {
		return superHeroId;
	}

	public void setSuperHeroId(Long superHeroId) {
		this.superHeroId = superHeroId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPowerDescription() {
		return powerDescription;
	}

	public void setPowerDescription(String powerDescription) {
		this.powerDescription = powerDescription;
	}

	public boolean isAwesome() {
		return isAwesome;
	}

	public void setAwesome(boolean isAwesome) {
		this.isAwesome = isAwesome;
	}

}

As i am using MySQL as the primary database, i have used the GeneratedValue strategy as GenerationType.AUTO which will do the auto incrementing whenever a new super hero is created. All other mappings are familiar to everyone with the exception of the last variable where we map a boolean to a Char field in the database.

We use Hibernate's @Type annotation to represent true & false as Y & N within the database field. Hibernate has many @Type implementations which you can read about here. In this instance we have used this type.

Ok now that we have our class to represent the Super Heroes, lets go on to see how our Justice League domain class looks like which keeps tab of all super heroes who have pledged allegiance to the League.

package com.justice.league.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "JusticeLeague")
public class JusticeLeague implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 763500275393020111L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "justice_league_id")
	private Long justiceLeagueId;

	@Column(name = "justice_league_moto")
	private String justiceLeagueMoto;

	@Column(name = "number_of_members")
	private Integer numberOfMembers;

	@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true)
	@JoinTable(name = "JUSTICE_LEAGUE_SUPER_HERO", joinColumns = { @JoinColumn(name = "justice_league_id") }, inverseJoinColumns = { @JoinColumn(name = "super_hero_id") })
	private List<SuperHero> superHeroList = new ArrayList<SuperHero>(0);

	public Long getJusticeLeagueId() {
		return justiceLeagueId;
	}

	public void setJusticeLeagueId(Long justiceLeagueId) {
		this.justiceLeagueId = justiceLeagueId;
	}

	public String getJusticeLeagueMoto() {
		return justiceLeagueMoto;
	}

	public void setJusticeLeagueMoto(String justiceLeagueMoto) {
		this.justiceLeagueMoto = justiceLeagueMoto;
	}

	public Integer getNumberOfMembers() {
		return numberOfMembers;
	}

	public void setNumberOfMembers(Integer numberOfMembers) {
		this.numberOfMembers = numberOfMembers;
	}

	public List<SuperHero> getSuperHeroList() {
		return superHeroList;
	}

	public void setSuperHeroList(List<SuperHero> superHeroList) {
		this.superHeroList = superHeroList;
	}

}


The important fact to note here is the annotation @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true). Here we have set orphanRemoval = true.

So what does that do exactly? Ok so say that you have a group of Super Heroes in your League. And say one Super Hero goes haywire. So we need to remove Him/Her from the League. With JPA cascade this is not possible as it does not detect Orphan records and you will wind up with the database having the deleted Super Hero(s) whereas your collection still has a reference to it.

Prior to JPA 2.0 you did not have the orphanRemoval support and the only way to delete orphan records was to use the following Hibernate specific(or ORM specific) annotation which is now deprecated;

@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

But with the introduction of the attribute orphanRemoval, we are now able to handle the deletion of orphan records through JPA. Now that we have our Domain classes

DAO & Service classes:
To keep with good design standards i have separated the DAO(Data access object) layer and the service layer. So let us see the DAO interface and implementation. Note that i have used HibernateTemplate through HibernateDAOSupport so as to keep away any Hibernate specific detail out and access everything in a unified manner using Spring.
package com.justice.league.dao;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.justice.league.domain.JusticeLeague;

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)  
public interface JusticeLeagueDAO {

	
	public void createOrUpdateJuticeLeagure(JusticeLeague league);
	
	public JusticeLeague retrieveJusticeLeagueById(Long id);
}


In the interface layer i have defined the Transaction handling as Required. This is done so that whenever you do not need a transaction you can define that at the method level of that specific method and in more situations you will need a transaction with the exception of data retrieval methods. 

According to the JPA spec you need a valid transaction for insert/delete/update functions.

So lets take a look at the DAO implementation;


package com.justice.league.dao.hibernate;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.justice.league.dao.JusticeLeagueDAO;
import com.justice.league.domain.JusticeLeague;

@Qualifier(value="justiceLeagueHibernateDAO")
public class JusticeLeagueHibernateDAOImpl extends HibernateDaoSupport
		implements JusticeLeagueDAO {

	@Override
	public void createOrUpdateJuticeLeagure(JusticeLeague league) {

		if (league.getJusticeLeagueId() == null) {
			getHibernateTemplate().persist(league);
		} else {
			getHibernateTemplate().update(league);
		}

	}
	
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = false)  
	public JusticeLeague retrieveJusticeLeagueById(Long id){
		return getHibernateTemplate().get(JusticeLeague.class, id);
	}

}


Here i have defined an @Qualifier to let Spring know that this is the Hibernate implementation of the DAO class. Note the package name which ends with hibernate. This as i see is a good design concept to follow where you separate your implementation(s) into separate packages to keep the design clean.

Ok lets move on to the service layer implementation. The service layer in this instance is just acting as a mediation layer to call the DAO methods. But in a real world application you will probably have other validations, security related procedures etc handled within the service layer.


package com.justice.league.service;

import com.justice.league.domain.JusticeLeague;

public interface JusticeLeagureService {

	public void handleJusticeLeagureCreateUpdate(JusticeLeague justiceLeague);

	public JusticeLeague retrieveJusticeLeagueById(Long id);
}


package com.justice.league.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.justice.league.dao.JusticeLeagueDAO;
import com.justice.league.domain.JusticeLeague;
import com.justice.league.service.JusticeLeagureService;

@Component("justiceLeagueService")
public class JusticeLeagureServiceImpl implements JusticeLeagureService {

	@Autowired
	@Qualifier(value = "justiceLeagueHibernateDAO")
	private JusticeLeagueDAO justiceLeagueDAO;

	@Override
	public void handleJusticeLeagureCreateUpdate(JusticeLeague justiceLeague) {
		justiceLeagueDAO.createOrUpdateJuticeLeagure(justiceLeague);
	}

	public JusticeLeague retrieveJusticeLeagueById(Long id){
		return justiceLeagueDAO.retrieveJusticeLeagueById(id);
	}
}

Few things to note here. First of all the @Component binds this service implementation with the name justiceLeagueService within the spring context so that we can refer to the bean as a bean with an id of name justiceLeagueService.

And we have auto wired the JusticeLeagueDAO and defined an @Qualifier so that it will be bound to the Hibernate implementation.

The value of the Qualifier should be the same name we gave the class level Qualifier within the DAO Implementation class. And Lastly let us look at the Spring configuration which wires up all these together;


Spring configuration for the application:

<?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"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="  
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">


	<context:component-scan base-package="com.justice.league" />
	<context:annotation-config />

	<tx:annotation-driven />

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="packagesToScan">
			<list>
				<value>com.justice.league.**.*</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
				<prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/my_test</prop>
				<prop key="hibernate.connection.username">root</prop>
				<prop key="hibernate.connection.password">password</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				
			</props>
		</property>
	</bean>

	<bean id="justiceLeageDAO"
		class="com.justice.league.dao.hibernate.JusticeLeagueHibernateDAOImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

</beans>
Note that i have used the HibernateTransactionManager in this instance as i am running it stand alone. If you are running it within an application server you will almost always use a JTA Transaction manager.

I have also used auto creation of tables by hibernate for simplicity purposes. The packagesToScan property instructs to scan through all sub packages(including nested packaged within them) under the root package com.justice.league.**.* to be scanned for @Entity annotated classes.

We have also bounded the session factory to the justiceLeagueDAO so that we can work with the Hibernate Template. For testing purposes you can have the tag <prop key="hibernate.hbm2ddl.auto">create</prop> initially if you want, and let hibernate create the tables for you. Ok so now that we have seen the building blocks of the application, lets see how this all works by first creating some super heroes within the Justice League

A simple main class to show how it all works:

As the first example lets see how we are going to persist the Justice League with a couple of Super Heroes;
package com.test;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.justice.league.domain.JusticeLeague;
import com.justice.league.domain.SuperHero;
import com.justice.league.service.JusticeLeagureService;

public class TestSpring {

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

		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"spring-context.xml");
		JusticeLeagureService service = (JusticeLeagureService) ctx
				.getBean("justiceLeagueService");

		JusticeLeague league = new JusticeLeague();
		List<SuperHero> superHeroList = getSuperHeroList();

		league.setSuperHeroList(superHeroList);
		league.setJusticeLeagueMoto("Guardians of the Galaxy");
		league.setNumberOfMembers(superHeroList.size());

		service.handleJusticeLeagureCreateUpdate(league);

	}

	private static List<SuperHero> getSuperHeroList() {

		List<SuperHero> superHeroList = new ArrayList<SuperHero>();

		SuperHero superMan = new SuperHero();
		superMan.setAwesome(true);
		superMan.setName("Clark Kent");
		superMan.setPowerDescription("Faster than a speeding bullet");

		superHeroList.add(superMan);

		SuperHero batMan = new SuperHero();
		batMan.setAwesome(true);
		batMan.setName("Bruce Wayne");
		batMan.setPowerDescription("I just have some cool gadgets");
		superHeroList.add(batMan);

		return superHeroList;
	}

}

And if we go to the database and check this we will see the following output;
mysql> select * from superhero;
+---------------+-----------+-----------------+-------------------------------+
| super_hero_id | isAwesome | super_hero_name | power_description             |
+---------------+-----------+-----------------+-------------------------------+
|             1 | Y         | Clark Kent      | Faster than a speeding bullet |
|             2 | Y         | Bruce Wayne     | I just have some cool gadgets |
+---------------+-----------+-----------------+-------------------------------+

mysql> select * from justiceleague;
+-------------------+-------------------------+-------------------+
| justice_league_id | justice_league_moto     | number_of_members |
+-------------------+-------------------------+-------------------+
|                 1 | Guardians of the Galaxy |                 2 |
+-------------------+-------------------------+-------------------+
So as you can see we have persisted two super heroes and linked them up with the Justice League. Now let us see how that delete orphan works with the below example;
package com.test;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.justice.league.domain.JusticeLeague;
import com.justice.league.domain.SuperHero;
import com.justice.league.service.JusticeLeagureService;

public class TestSpring {

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

		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"spring-context.xml");
		JusticeLeagureService service = (JusticeLeagureService) ctx
				.getBean("justiceLeagueService");

		JusticeLeague league = service.retrieveJusticeLeagueById(1l);
		List<SuperHero> superHeroList = league.getSuperHeroList();
		/**
		 * Here we remove Batman(a.k.a Bruce Wayne) out of the Justice League
		 * cos he aint cool no more
		 */
		for (int i = 0; i < superHeroList.size(); i++) {
			SuperHero superHero = superHeroList.get(i);
			if (superHero.getName().equalsIgnoreCase("Bruce Wayne")) {
				superHeroList.remove(i);
				break;
			}

		}

		service.handleJusticeLeagureCreateUpdate(league);

	}

}

Here we first retrieve the Justice League record by its primary key. Then we loop through and remove Batman off the League and again call the createOrUpdate method. As we have the remove orphan defined, any Super Hero not in the list which is in the database will be deleted.
Again if we query the database we will see that batman has been removed now as per the following;
mysql> select * from superhero;
+---------------+-----------+-----------------+-------------------------------+
| super_hero_id | isAwesome | super_hero_name | power_description             |
+---------------+-----------+-----------------+-------------------------------+
|             1 | Y         | Clark Kent      | Faster than a speeding bullet |
+---------------+-----------+-----------------+-------------------------------+

So that's it. The story of how Justice League used Hibernate to remove Batman automatically without being bothered to do it themselves.

Next up look forward to how Captain America used Hibernate Criteria to build flexible queries in order to locate possible enemies. Watch out!!!!

Have a great day people and thank you for reading!!!!

If you have any suggestions or comments pls do leave them by.

Saturday, August 13, 2011

Lessons i learnt playing Angry Birds



So i finally saved up and bought my first smart phone a few weeks back(A samsung galaxy s i9000 to be specific). I heard about the game Angry Birds even before i had a smart phone but never got a chance to play it. The hype about it was very true. The game is addictive :D. Anyhow my objective of this article is not to disseminate news how awesome Angry Birds is, which is quite obvious with the plethora of download rates it is getting, but to write about a few things that crossed my mind whilst playing it.

  • Plan before execute
       When you first start off a chapter, you are shown a glimpse of what obstacles lie ahead. You can then scroll back and forth looking at where the stinky(ok im exaggerating a bit here, but im on the bird's side after all) pigs are situated and how they are protected by the obstacles. So you plan the attack beforehand and launch it. 
          As a developer this is a very interesting point. Sometimes i rush into writing a piece of code. But if i had looked at a few possible obstacles, other possible solutions, i believe most of the time i could have come up with a much better design. 

  • Efficiency in resource utilization
           In some instances you get birds with different abilities. Some blow up, speed through, drop bombs, replicate etc. Each has their strengths and weaknesses. Before we launch an attack we see how best to use them and at which point.
           As a developer, i should know my strengths and weaknesses and apply them accordingly when given a particular task, and look at what i lack and gain knowledge in areas where i lack in order to fill the gap.
          As a project manager you should know the skills of your resources and utilize them to the tasks at hand efficiently in order to achieve the end goal of delivering a stable product to the customer. Not everyone is good at everything, so identifying your resource pool enables you to make better decisions and improve and refine your resources' knowledge base as you go on.

  • How to handle the task with minimum effort
           When you blow up all the pigs around with a few birds left up you get bonus points.
           As a developer, when given a task i must strive to see ways in which i could achieve it with minimum effort. This does not mean your a lazy bum, but that you opt to work smarter than harder. You can thereby save up time to do other things like gain knowledge on other new technologies, contribute to some open source project you love etc. In the birds example, you are left with a few birds because you used your targets efficiently. In the same way, if you apply the solution you devised in the correct manner, you will be left with some time to spare(this might depend on your supervisor ofcourse :)  )

  • Go ahead with what works for you
           In any level, you have multiple ways of approaching the obstacles. You may try a few options, but in the end you have to go with what works for you in order to send those pigs flying(again exaggeration).
           As a developer, when designing a particular module/project, there always are many ways in which that can be achieved. But in the end you have to decide on what will work for you and go ahead with it. When presented with many solutions you have to decide on what will work for you and stick to the plan to achieve the end goal. Again as the birds example sometimes the one you chose might not work, so you refine your solution and come up with a successful one in the end.

  • Perseverance

        When you embark on a mission, sometimes you cannot complete it in one shot. You need to keep on trying and eventually you will get there and make the pigs pay.
           As a developer sometimes i might not be able to come up with a viable solution for the problem at hand. But you should not be discouraged and give up. Breaking the problem into smaller understandable components might let you see things in a new perspective. So keep on trying and eventually you will get there.  

Thats it for now guys. Ofcourse im still on level 2-17 at the time of writing this post, so i might learn a few more things as i go on :)... 

Thank you for reading and please do leave by your thoughts if you have the time. Have a great day guys!!! 

   

Saturday, August 6, 2011

What i love about PHP



 First of all i must say im relatively new to the whole PHP scene. Coming from an OOP background with mostly Java/C++ experience i must say the transition was not rough as i expected it to be. Unfortunately i have not been able to code in PHP at an industrial level but use it for many of my freelance projects which has been very productive up to now. So i would love to highlight why i love PHP and why i think others who aren't using it yet, should give it a try.

  • WAMP
                WAMP is one of the best bundled package i have seen. Right out of the box you got yourself an Apache server, mysql database and PHP core. So within a matter of minutes you are ready to write some productive code without having to deal with environment setup issues. And you have a wide variety of bundled packages to chose from which fits you needs. Need a mysql client to go through the database? No need of installing another sql client. Just type http://localhost/phpmyadmin/ and your ready to create your database schemas.

  • Its Interpreted
               All java folks know how much of a pain it is to compile your project if you are working on a large scale application. You just do a small change and stare at your command line as Maven or Ant destroys 2-5 minutes on average of your precious time. Im not emphasizing on build related problems here but the truth of the fact is there is no matter what, you do waste a portion of your time compiling code. Whats great about PHP is the fact that it is interpreted.  You just do a change, go to your browser and refresh. Thats it. Saved me a ton of time in many of my freelance projects.

              Ofcourse there are PHP compilers if anyone ever needs it. Some say it increases the performance but i have personally not been able to try it. Facebook has written a nice tool that converts PHP code to C code called HipHop.

             The information presented in this site is just out of this world. Anything and everything you will ever need when working with PHP is here so there is no hassle what so ever. When i need a function i just search it up here and the community has been very active with various people suggesting better ways of calling various functions which has been very helpful to me.

  • No need of a special IDE
             Myself and many i know just use Notepad++ for our coding with PHP.  Its just easy to use and switch between different source files. I dont think anyone ever needs an IDE when coding in PHP though there are some very useful IDEs out there as listed here.

            From PHP 5 they supported classes, object creation, constructors and the whole deal. This feature made it very easy for me in the transition phase from java to php. It was more or less a seamless transition.

  • Plethora of frameworks to choose 
           You got Zend, cake php, symphony and so many more frameworks. Its just amazing. If one does not fit your need you just move to the next one and try it out. The learning curve is also not that steep as well. The MVC architecture introduced by these frameworks make you feel at home when coming from a struts background as myself. And the DAO layer separation introduced in some frameworks is also a huge plus point for me.

Im just starting out with PHP and i believe more will be added to this list as time goes on. If any PHP pros can share their opinion on why you love the language it is highly appreciated.

Cheers Guys!!!!


Saturday, July 23, 2011

The story of the ArrayList imposter

Each and everyone of us, undoubtedly has had used Array lists in our lives as programmers. This story is about an imposter who lives among us, unnoticed, undetected until WHAM you are presented with a bug that makes no sense. Let me give you an example to reveal this imposter :). I have a hypothetical system that stores information on games and their ratings. A glimpse of the DTO i would use is as follow;


/**
 * A class to hold basic data about game titles
 * @author dinuka
 *
 */
public class Game  {

	/**
	 * The name of the game
	 */
	private String title;
	/**
	 * The rating users have given the game
	 */
	private int rating;
	
	public Game(String title,int rating){
		this.title = title;
		this.rating = rating;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getRating() {
		return rating;
	}

	public void setRating(int rating) {
		this.rating = rating;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + rating;
		result = prime * result + ((title == null) ? 0 : title.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;
		Game other = (Game) obj;
		if (rating != other.rating)
			return false;
		if (title == null) {
			if (other.title != null)
				return false;
		} else if (!title.equals(other.title))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Game [title=" + title + ", rating=" + rating + "]";
	}
	
	
}

Nothing fancy. Just a plain old data holder value object with customary getter/setter methods. I have overriden equals,hashcode and tostring methods because i usually do that as a principal :). Ok moving on to reveal the culprit i will present you with a sample code and run the code and show you the problem at hand;


import java.util.Arrays;
import java.util.List;


public class Test {

	
	public static void main(String[] args) {

		Game[]gameArr = new Game[3];
		
		gameArr[0] = new Game("Metal gear solid 4",8);
		
		gameArr[1] = new Game("Unchartered 2",6);
		
		gameArr[2] = new Game("NFS Underground",2);
		
		Game[]newGameList = manipulateGames(gameArr);
		
		
	}
	
	/**
	 * Here we delete low rating games
	 * and add new game titles in place of those games
	 * @param gameArr
	 */
	private static Game[] manipulateGames(Game[]gameArr){
		List&lt;Game&gt;gameList = Arrays.asList(gameArr);
		
		for(int i=0;i&lt;gameList.size();i++){
			Game game = gameList.get(i);
			if(game.getRating()&lt;5){
				gameList.remove(game);
				Game newGame = new Game("NFS Hot pursuit 2",7);
				gameList.add(newGame);
			}
		}
		Game[]newArr = new Game[gameList.size()];
		return gameList.toArray(newArr);
	}
}


Ok these are my personal ratings i have given for the few of the games i love. Hopefully no one will take them personally because i do not want you to get off the topic here ;). So what we are doing here is, we have an array of games which we pass into a method which looks at the games with ratings lower than 5 and removes them and adds new games as substitutes. Do not consider implementation details as that is not my intention. My intention is to show you the problem at hand. So lets run this code and see what we get.

Ok what just happened? We get this really awkward error saying Unsupported exception. When i first got this i was thinking that maybe a previous version of java did not support removing from list given the object because i was at work using JDK 1.4 for work related things. But jdeclipse came to my help. If anyone has not used it, i can guarantee that it is one of the most useful plugins and a faithful companion in my eclipse workbench. Its a java decompiler which can decompile class files. Its much easier than downloading the JDK source and linking it.

I wanted to see the implementation of the Arrays.asList() method. This is where i found our little ArrayList imposter.....


public static <T> List<T> asList(T[] paramArrayOfT)
  {
    return new ArrayList(paramArrayOfT);
  }


By the looks of it, there is nothing implicitly wrong with this implementation. So most probably it should be a problem with the ArrayList. Lets see whats happening there;


private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, Serializable
  {
    private static final long serialVersionUID = -2764017481108945198L;
    private final E[] a;

    ArrayList(E[] paramArrayOfE)
    {
      if (paramArrayOfE == null)
        throw new NullPointerException();
      this.a = paramArrayOfE;
    }

    public int size()
    {
      return this.a.length;
    }

    public Object[] toArray()
    {
      return ((Object[])this.a.clone());
    }

    public <T> T[] toArray(T[] paramArrayOfT)
    {
      int i = size();
      if (paramArrayOfT.length < i)
        return Arrays.copyOf(this.a, i, paramArrayOfT.getClass());
      System.arraycopy(this.a, 0, paramArrayOfT, 0, i);
      if (paramArrayOfT.length > i)
        paramArrayOfT[i] = null;
      return paramArrayOfT;
    }

    public E get(int paramInt)
    {
      return this.a[paramInt];
    }

    public E set(int paramInt, E paramE)
    {
      Object localObject = this.a[paramInt];
      this.a[paramInt] = paramE;
      return localObject;
    }

    public int indexOf(Object paramObject)
    {
      int i;
      if (paramObject == null)
        for (i = 0; i < this.a.length; ++i)
          if (this.a[i] == null)
            return i;
      else
        for (i = 0; i < this.a.length; ++i)
          if (paramObject.equals(this.a[i]))
            return i;
      return -1;
    }

    public boolean contains(Object paramObject)
    {
      return (indexOf(paramObject) != -1);
    }
  }

Huh what is that?? Its an inner class extending the AbtractList class,residing within the Arrays class baring the name ArrayList. The problem here is that it does not override all methods available within AbtractList thus throwing the UnsupportedException as defined within the class AbtractList .

Why they have done this im not really sure. It maybe because they are syncing the Array you passed initially and what ever update you do, is done to the original Array you passed in. But why chose such an implementation is a question mark for me.

So if you ever want to remove elements when using an ArrayList composed using Arrays.asList make sure to wrap it with a call such as newArrayList(Array.asList(myArr)); This will guarantee that you will use the concrete ArrayList implementation and not our imposter we just discovered.


So that ends the story of the ArrayList imposter that bothered me last week at work :)


Thank you for reading and hope you guys have a peaceful day of coding!!!