Welcome to my blog

I blog my interests and opinions here.

Thursday, September 8, 2011

Vacation in Kerala

A vacation in Kochi during Onam harvest festival time brings pleasant rains and good food. This was the day Mahabali rose from padalam (underground). The shopping centers greet you with giant Malabali baloons or a live person dressed as Mahabali a truly unique experience. Except for the bad roads and inching traffic this time of the year is really great here.

In five years the one rupee coin has disappeared and inflation has bumped up the cost of living significantly. Nevertheless a vacation well spent is vacation well spent.

Monday, July 18, 2011

What is polymorphism really!

It's been a while I blogged. With a new baby and things that come with it life kind of has become pretty hectic.

I always thought that polymorphism was the ability to implement the same behavior in different ways. An Animal would move (public void move()) but the way a Cat would implement move would be different from the way an Elephant would implement move. But that is not the case, polymorphism is the forcing the Cat class and Elephant class to implement move() method in their own way by having them implement an IAnimal interface with a public void move(); method. It is inheritance and method implementation that we see here. Method overriding does not mean the classes are exhibiting polymorphic behavior. See the Wiki for more details http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

Monday, January 31, 2011

Using Spring and Hibernate makes developers life easier

A hibernate based application typically uses object relational mapping paradigm to map a database table
CREATE TABLE `hello` (
`id` int(11) NOT NULL,
`description` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
)

to an entity class in Java

package dto;

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

/**
* Hello generated by hbm2java
*/
@Entity
@Table(name = "hello", catalog = "test")
public class Hello implements java.io.Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String description;

public Hello() {
}

public Hello(int id) {
this.id = id;
}

public Hello(int id, String description) {
this.id = id;
this.description = description;
}

@Id
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}

public void setId(int id) {
this.id = id;
}

@Column(name = "description", length = 45)
public String getDescription() {
return this.description;
}

public void setDescription(String description) {
this.description = description;
}

}
Spring uses an application-context.xml file that specifies the bean dependency injection configurations for the data source, hibernate session factory, hibernate template and the Data Access Object (DAO)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>hello.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.HSQLDialect
</value>
</property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="mySessionFactory"/>
</property>
</bean>

<bean id="myHelloDao" class="dao.HelloDao">
<property name="hibernateTemplate">
<ref bean="hibernateTemplate"/>
</property>
</bean>

</beans>

The mapping between the entity and the database table is specified in the hibernate mapping file hello.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="dto.Hello" table="hello" catalog="test">
<id name="id" type="int">
<column name="id" />
<generator class="assigned" />
</id>
<property name="description" type="string">
<column name="description" length="45" />
</property>
</class>
</hibernate-mapping>

The Data Access Object (DAO) class would (uses the hibernate template callback mechanism in order to access the database) look like

public class HelloDao {

private HibernateTemplate hibernateTemplate;

public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
this.hibernateTemplate = hibernateTemplate;
}

public HelloDao()
{

}


/**
* Gets all the rows from test.Hello table
* @return
*/
public List<Hello> getAll() throws DataAccessException
{
List<Hello> helloList = null;

try
{
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException,SQLException {
return session.createQuery("from Hello").list();
}
};
helloList = (List<Hello>)hibernateTemplate.execute(callback);
}
catch(Exception ex)
{
throw new DataAccessException("Error when getting all records.",ex);
}

return helloList;
}
}

Introducing Spring changes the way a typical hibernate application works by
1. Reducing the number of configuration files on the server side
2. Allowing multiple clients to connect to different databases (by injecting different data source configurations in the application-context.xml) without having to change the server side code.

Friday, January 7, 2011

Java Server Faces (JSF) 2.0

The advent of Java Server Faces (JSF) 2.0 has made the life of the UI developer very much easier. A simple JSF would have very minimal files namely XHTML files, a Java bean to hold properties and a web.xml file. Usage of ManagedBean annotations has helped to avoid creating and managing faces-config.xml. Bringing about XHTML files rather than JSP files has created a clear separation of logic between the page designer and the Java Developer. A simple hello world JSF project would have the following files -
1. Hello.xhtml - A well formed XHTML file that contains the JSF tags
2. web.xml - The web descriptor specifies the faces servlet and XHTML contexts
3. HelloBean java bean - A simple Java bean with the "ManagedBean" annotation that holds the properties

All the latest developments on JSF are available in the Mojarra project at http://javaserverfaces.java.net

Tuesday, December 14, 2010

EJB3: More programming less configuration

Using EJB3 makes programming a lot more fun that the previous versions. The advent of Java 5 annotations have made the life of programmers a lot more easier. Here is a simple Hello World stateles session bean EJB.

1. HelloWorldSessionBeanLocal - This is the EJB local interface that contains several methods that need to be implemented by the Session bean.

package hello;

import javax.ejb.Local;

import dto.Hello;

@Local
//@Local annotation indicates that the class is a EJB Local class
public interface HelloWorldSessionBeanLocal {

public String sayHello();

public String sayHelloFromDB();

public String sayHelloFromHibernate();

public void insertHelloUsingHibernate(Hello hello);

public Hello updateHelloUsingHibernate(Hello hello);

public void deleteHelloUsingHibernate(Hello hello);

}


2. HelloWorldSessionBean - The session bean has several methods.
a) sayHello method simply writes the string "Hello from Session bean" out.
b) sayHelloFromDB method writres the string out by reading from the database using Java Persistence API (JPA).
c) sayHelloFromHibernate method writes the string out by reading from the database using the Hibernate Dto Hello.class
d) insertHelloUsingHibernate(Hello hello) inserts a new record into the table using Hibernate
e) updateHelloUsingHibernate(Hello hello) updates the record in the database using Hibernate
f) deleteHelloUsingHibernate(Hello hello) deletes a record from the database using Hibernate


package hello;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import dto.Hello;
import dto.HelloHome;

/**
* Session Bean implementation class HelloWorldSessionBean
*/
@Stateless
// @Stateless indicates that this is a stateless session bean
public class HelloWorldSessionBean implements HelloWorldSessionBeanLocal {

@PersistenceContext(unitName="HelloWorldDS")
//@PersistenceContext indicates the JPA persistence context defined in the persistence.xml
EntityManager entityManager;

@EJB
// @EJB indicates that this HelloHome is an EJB. A reference is dynamically injected by the container rather than having to do JNDI lookups
HelloHome helloHome;

/**
* Default constructor.
*/
public HelloWorldSessionBean() {
// TODO Auto-generated constructor stub
}

public String sayHello()
{
return "Hello from Session Bean!";
}

public String sayHelloFromDB()
{
String ret = "";

try
{
javax.persistence.Query query = entityManager.createQuery("select Description from hello where id=1");
//org.hiberante.ejb.QueryImpl hs = (QueryImpl)query;
///org.hibernate.Query hbQuery = hs.getHibernateQuery();
ret = (String)query.getSingleResult();

}
catch(Exception ex)
{
System.out.println("Error when reading from DB"+ex.getMessage()+"\n"+ex.getStackTrace());
}


return ret;
}

public String sayHelloFromHibernate()
{
String ret = "";

try
{
Hello hello = helloHome.findById(1);
ret = hello.getDescription();

}
catch(Exception ex)
{
System.out.println("Error when reading from DB(Hibernate) "+ex.getMessage()+"\n"+ex.getStackTrace());
}


return ret;
}

public void insertHelloUsingHibernate(Hello hello)
{
try
{
helloHome.persist(hello);

}
catch(Exception ex)
{
System.out.println("Error when inserting DB(Hibernate) "+ex.getMessage()+"\n"+ex.getStackTrace());
}


}

public Hello updateHelloUsingHibernate(Hello hello)
{
Hello ret = null;

try
{
ret = helloHome.merge(hello);

}
catch(Exception ex)
{
System.out.println("Error when updating DB(Hibernate) "+ex.getMessage()+"\n"+ex.getStackTrace());
}


return ret;
}

public void deleteHelloUsingHibernate(Hello hello)
{
try
{
helloHome.remove(hello);

}
catch(Exception ex)
{
System.out.println("Error when deleting DB(Hibernate) "+ex.getMessage()+"\n"+ex.getStackTrace());
}


}

}

3. Hello - This is the auto generated Hibernate Dto class that maps to the hello table in the database

package dto;

// Generated Sep 13, 2010 2:17:01 PM by Hibernate Tools 3.3.0.GA

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

/**
* Hello generated by hbm2java
*/
@Entity
// @Entity indicates that this is an database entity class
@Table(name = "hello", schema = "public")
// @Table indicates that this Dto maps to the database table "hello" in the "public" schema
public class Hello implements java.io.Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String description;

public Hello() {
}

public Hello(int id, String description) {
this.id = id;
this.description = description;
}

@Id
@Column(name = "id", unique = true, nullable = false)
//@Column indicates that this is a database column name
public int getId() {
return this.id;
}

public void setId(int id) {
this.id = id;
}

@Column(name = "description", nullable = false)
public String getDescription() {
return this.description;
}

public void setDescription(String description) {
this.description = description;
}

}

4. HelloHome - This is a stateless EJB that acts as the persistence manager for Hibernate to perform the datbase operation

package dto;

// Generated Sep 13, 2010 2:17:01 PM by Hibernate Tools 3.3.0.GA

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Home object for domain model class Hello.
* @see dto.Hello
* @author Hibernate Tools
*/
@Stateless
// @Stateless indicates that this is a Stateless session bean
public class HelloHome {

private static final Log log = LogFactory.getLog(HelloHome.class);

@PersistenceContext(unitName="HelloWorldDS")
private EntityManager entityManager;

public void persist(Hello transientInstance) {
log.debug("persisting Hello instance");
try {
entityManager.persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}

public void remove(Hello persistentInstance) {
log.debug("removing Hello instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
} catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}

public Hello merge(Hello detachedInstance) {
log.debug("merging Hello instance");
try {
Hello result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

public Hello findById(int id) {
log.debug("getting Hello instance with id: " + id);
try {
Hello instance = entityManager.find(Hello.class, id);
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}

5. META-INF/persistence.xml - This file defines the persistence unit that the Hibernate entity manager should use. It in turn depends on the data source deployed on the application server such as JBoss / Websphere / Weblogic etc.

&lt;?XML:NAMESPACE PREFIX = [default] http://java.sun.com/xml/ns/persistence NS = "http://java.sun.com/xml/ns/persistence" /&gt;&lt;persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"&gt;
&lt;!-- The name if this persistence unit is used by the JPA provider class --&gt;
&lt;persistence-unit name="HelloWorldDS"&gt;
&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
&lt;jta-data-source&gt;java:PostgresDS&lt;/jta-data-source&gt;
&lt;/persistence-unit&gt;
&lt;/persistence&gt;

If you notice there are not many config files defined here. The Java 5 annotations in the class definitions took care of the attributes associated with the classes. Thus making life easier for the programmer.

Wednesday, November 24, 2010

JON (JBoss Operations Network) for performance monitoring vs application migration

JON is a lightweight performance and server monitoring tool offered by the JBoss community. JON agents could be configured to discover JBoss servers such as JBoss Web and JBoss EAP in order to visually monitor the performance of the various applications. JON could monitor the classes, memory usage, CPU usage and so on.

Although JON could be used to run scripts fo automation of application releases, it would not be the best tool for that. Especially when there are continious integration tools such as Hudson. The JON command line interface (CLI) tool allows to run javascripts to communicate with the JBoss Server and release web archives (WAR), enterprise archives (EAR) and so on.

Tuesday, November 23, 2010

Jboss Mod Cluster with Apache Httpd

Setting up a load balancing environment with Apache 2.2 (a web server that acts as reverse proxy for JBoss), JBoss Web 2.1 (Jboss version of Tomcat) and Jboss EAP 5.1 is quite easy.

The AJP connector for JBoss would automatically hookup with the Apache Httpd web server if the parameters were correctly specified in the conf/httpd.conf file.

Detailed instructions on seeting up mod cluster is available at the link http://docs.jboss.org/mod_cluster/1.0.0/html/ and the following link has step by step instructions on setting up mod cluster https://access.redhat.com/kb/docs/DOC-34508 (this link would require registration at the Red Hat Customer Service portal)