Welcome to my blog

I blog my interests and opinions here.

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.

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

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)

Monday, November 22, 2010

JAAS Login Module pros and cons

Using a Java Authentication and Authorization (JAAS) login module for authentication and authorization is a great way to separate the authentication layer from the rest of the application. Some pros of using JAAS are
a) Layering improves performance.
b) Fail over handled seamlessly using JAAS login module chaining.
c) Multiple stores could be used like LDAP, database, properties file.
d) Having the authentication and authorization happen in one step reduces the burden on the developer.


Some of the cons of using JAAS are
a) In web applications accessing the Http Session object could be a hassle in the custom JAAS login modules.
b) Propagation of the JAAS authentication Subject to other layers is not easy.
c) Having the authorization in JAAS could be restricting for applications where multiple sections of the application could be require separate authorization.

Thursday, November 18, 2010

Mediator pattern and coupling

The mediator pattern in a behavioral pattern unlike structural patterns such as facade and adaptor.

Mediator Pattern: In layman's terms a mediator is a person who acts as a point of reference between parties. In the same sense a mediator class is one that acts as a point of reference between two classes that depend on each other. In an environment where the requirements and the system design is continuously changing such a design pattern is used.

Introducing a mediator reduces the coupling between the classes thus making maintenance of the application relative easy.

Wednesday, November 17, 2010

Difference between Facade pattern and the adaptor pattern

Both the facade and adaptor patterns are structural patterns.

Facade Pattern: In layman's terms the facade pattern could be thought of as the front end of a building. The facade pattern provides a single interface for various calling clients. It organizes the code in a better more readable fashion, hides the inner working of the system and reduces the network traffic.

Adaptor Pattern: The adaptor pattern could be thought of as a power adaptor used in UK for a device that is meant to work in USA voltage. In the adaptor pattern the calling client uses the adaptor as a single interface to perform the same operation. The adaptor in turn decides which operation should be called based on the environment.

The conclusion is that the facade pattern provides a single interface for multiple operations and the adaptor pattern provides a single interface for the same operation.

Thursday, November 11, 2010

Desert Code Camp on 11/13 at Gilbert

It is always a nice experience at the code camp as I get to see how the Microsoft technologies are innovating the world of RAD as compared to Java. It seems like there are some interesting sessions on RESTful services and enterprise architecture that I would like to attend.

Wednesday, November 10, 2010

Service Oriented Architecture (SOA) and Cloud

In the world of cloud computing service oriented architecture (SOA) is something that has revolutionized the world of internet programming.

Take the example of the Amazon Web Services (AWS: http://aws.amazon.com) that allows developers to connect and get information about items sold at Amazon. Talking about AWS I remember an application that I wrote in order to talk to the AWS for retrieval of the book details based on the ISBN. I also published an article on ASP Alliance on this.

Object oriented analysis and design

I am a strong believer in thinking object oriented. Given a real life problem, the solution becomes clearer when it is broken down using the OOAD principles Abstraction, Polymorphism, Inheritence and Encapsulation (A PIE).

Although several books and materials on the internet explain these concepts in a more technical manner, I think that things are clearer if we looked at it from a layman's perspective using an example of a small business.

Abstracion: To be more specific lets look at the payroll processing system in a small business. Any payroll processing system would have some common operations such as check balance and process payroll. These general operations could be classified as abstraction.

Polymorphism: In the payroll processing system the operation process payroll could be handled in different ways. The first one being process payroll using direct deposit and the second being process payroll with check. This could be classified as polymorphism.

Inheritence: In the payroll processing system there could be two different branches one in Arizona and the other in New York. Both the branches would process payroll by inheriting the common behavior from the parent but implement the payroll processing in different ways (as the state taxes etc. could be different). This could be classified as inheritence.

Encapsulation: In the payroll processing system when the payrols is being processed for an employee the information such as state taxes would be encapsulated. Such a data hiding technique could be classified as encapsulation.

As we can see the complex payroll processing system in not so complex anymore when looked at using the "A PIE" principle of OOAD.