Design

You are currently browsing the articles from Java Blog - Java, J2EE, SOA, Spring and Hibernate matching the category Design.

Exception handling framework using Spring AOP

In this article I will look at the various features which are required for a good exception handling framework and how Aspect oriented programming (AOP) will be used in the design of an Exception handling framework.

Lets Look at the key feature of an Exception handling framework

Learn more about exceptions here and find out the difference between Checked and unchecked exceptions here.

By large, Exceptions are classified in two categories

(more…)

Written by Ravi Nallakukkala on November 29th, 2007 with no comments.
Read more articles on Design.

Spring Based JUnit Integration Test approach

The Spring Framework provides a good support for the integration tests for enterprise software applications and these support classes are packaged in spring-mock.jar and all these classes are JUnit test classes. org.springframework.test package provides valuable JUnit TestCase superclasses for integration testing using a Spring container and this approach is completely independent of any web/ application server.

Spring out-of-box provide the following functionality:

On Surface, Spring Test cases can be classified into

Spring based JUnit with Dependency Injection

For JUnit Classes which need to use Dependency injection feature of spring will be required to inherit the class ‘AbstractDependencyInjectionSpringContextTests‘ and the subclass need to implement the superclass’s abstract method ‘protected abstract String[] getConfigLocations();’ the implementation of this method need to return the spring configuration XML files which are required to participate in the execution of the test case.
E.g,
public final class ExampleDaoTests extends AbstractDependencyInjectionSpringContextTests {

// this reference will be automatically injected through spring
private ExampleDao exampleDao;

// a setter method to enable DI for the Dao instance variable
public void setExampleDao(ExampleDao exampleDao) {
this.exampleDao = exampleDao;
}

public void testExample() throws Exception {
BusinessObject bo = this.exampleDao.loadBo(new Long(10));
assertNotNull(title);
}

// specifies the Spring configuration to load for this test.
protected String[] getConfigLocations() {
return new String[] { “classpath:com/foo/daos.xml” };
}
}

<< Spring Configuration file >>

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

<!– this bean will be injected into the ExampleDaoTests class –>
<bean id=”exampleDao” class=”com.foo.dao.hibernate.ExampleDao”>
<property name=”sessionFactory” ref=”sessionFactory”/>
</bean>

<bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
<!– dependencies elided for clarity –>
</bean>
</beans>

Spring based JUnit with Transaction Control/ Integration Test

One common problem in integration test is to access a database and still maintain the state of the persistence store. When using a database, changes to the database state may effect the future tests and CURD operations can’t be verified outside a transaction.

The org.springframework.test.AbstractTransactionalSpringContextTests superclass (and subclasses) exist to meet this requirement. By default, this class create and rollback a transaction for each test. From a developer/ development point of view, You simply write code that assumes the existence of a transaction.

It has to be noted that, this class extends AbstractDependencyInjectionSpringContextTests so spring dependency injection is made available for all the subclasses extending AbstractTransactionalSpringContextTests

Spring based JUnit also provides an option to commit a transaction (unusual, but occasionally useful when you want a particular test to populate the database) - you can invoke the setComplete() method inherited from AbstractTransactionalSpringContextTests. This will force the transaction to commit instead of roll back.

There is also convenient ability to end a transaction before the test case ends, through calling the endTransaction() method. This will roll back the transaction by default, and commit it only if setComplete() had previously been called. This functionality is useful if you want to test the behavior of ‘disconnected’ data objects, such as Hibernate-mapped objects that will be used in a web or remoting tier outside a transaction. Often, lazy loading errors are discovered only through UI testing; if you call endTransaction() you can ensure correct operation of the UI through your JUnit test suite.
E.g,

//as this test class extends ‘AbstractTransactionalSpringContextTests’ so all the
//test methods will be bound with a transaction.
public final class ExampleDaoTests extends AbstractTransactionalSpringContextTests {

// this reference will be automatically injected through spring
private ExampleDao exampleDao;

// a setter method to enable DI for the Dao instance variable
public void setExampleDao(ExampleDao exampleDao) {
this.exampleDao = exampleDao;
}

public void testExample() throws Exception {
BusinessObject bo = createBo(); // create the Business Objects
exampleDao.create(bo); // Business Object will be created

//now retrieve the object which was created in the database.
BusinessObject returnedObject = exampleDao.findById(bo.getId());
assertEquals(bo.getId(), returnedObject.getId());
//after the execution of the test method, data which was inse
}

// specifies the Spring configuration to load for this test.
protected String[] getConfigLocations() {
return new String[] { “classpath:com/foo/daos.xml” };
}
}

<< Spring Configuration file >>

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

<!– this bean will be injected into the ExampleDaoTests class –>
<bean id=”exampleDao” class=”com.foo.dao.hibernate.ExampleDao”>
<property name=”sessionFactory” ref=”sessionFactory”/>
</bean>

<bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
<!– dependencies elided for clarity –>
</bean>

</beans>

Written by Ravi Nallakukkala on November 29th, 2007 with no comments.
Read more articles on Design and Spring.

Equals and hashcode Approach/ Implementation for Business Objects (Bo)

A common source for bugs while writing code Business Objects for relational database using Object Relation Mapping tools is the implementation of the Equals and Hashcode methods.

If you would like to know more about the Equals and Hashcode importance for an ORM Click here.

To summarize the ORM implementation, There are two types of keys: Technical Keys and Business keys.

Technical keys are the primary key on the for a table to uniquely identify a database row, these numbers are auto generated sequence number (Item Unique IDentification/ IUID).

Business keys are the Business primary (/ composite) keys which uniquely identify the business objects in the database tables.

One of the important factor while writing a equals and hashcode method is to decide on what attributes needs to go into these methods; Some guidelines for deciding the attributes for Equals and hashcode methods.

Implementation wise, Apache commons-lang has a very good implementation for hashcode and equals method. Here’s an example of equals and hashcode methods using the apache commons-lang.

@Entity
@Table(name = "APP_CONFIGURATION")
@SequenceGenerator(name = "OPS_SEQ", sequenceName = "SQ_CONFIGURATION_CNTR")
public class ConfigurationBo extends AbstractBo {

private static final long serialVersionUID = -5098377177228374794L;

@Column(name = “ITEMNAME”, length = 100)
private String name;

@Column(name = “STRINGVALUE”, length = 100)
private String stringValue;

@Column(name = “INTVALUE”)
private Integer intValue;

@Column(name = “TYPENAME”, length = 20)
private String type;

public Integer getIntValue() {
return intValue;
}

public void setIntValue(Integer intValue) {
this.intValue = intValue;
}

public String getName() {
return name;
}

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

public String getStringValue() {
return stringValue;
}

public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj.getClass() == this.getClass())) {
return false;
}
ConfigurationBo other = (ConfigurationBo) obj;

return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(this.name, other.name)
.append(this.type, other.type)
.isEquals();
}

/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return new HashCodeBuilder()
.appendSuper(super.hashCode())
.append(this.name)
.append(this.type)
.toHashCode();
}

/**
* {@inheritDoc}
*/
@Override
public String toString() {
return super.toString() + “[name=” + name + “, type=” + type + “]”;
}

}

Written by Ravi Nallakukkala on April 15th, 2007 with 4 comments.
Read more articles on Design and Hibernate.

Unit Testing - Junit Approach

Unit Testing involves testing unit components or modules of Code and validating that they work properly. It’s a proactive procedure, which means that code written by developers needs to be unit tested at the unit level. All test cases are independent of each other and are to be written and executed by development team.

Prior fixing a bug, write a unit test to reproduce it. When the bug is fixed, verify the fix using the unit test. All methods need to be covered by the tests. The tests need to covers all paths through the unit. Unit Tests will ensure errors are picked up at the earlier stage and will facilitate easy integration.

Unit Testing Process

The figure below illustrates the Unit Testing Procedure and it encourages developers to write test cases before they start developing their use cases.

Unit test life cycle

Guidelines for Unit Test Cases

Unit Testing Tools
Consider a combination of JUnit and EasyMock to write Unit Test Cases. These tools are integrated with Eclipse (hopefully with Intellij) to merge unit tests with the development process.

Unit Testing Framework - JUnit
JUnit provides a Java based framework for unit testing. In order to setup JUnit one has to download the junit.jar file which is freely downloadable and append it to your classpath. JUnit will be integrated with the Eclipse development environment.

EasyMock
EasyMock, an open source library provides an easy medium to generate mock objects for a given interface. This facilitates running Junit tests for individual classes with the collaborators being simulated with Easy Mock Objects.

To get a Mock Object, we need to perform the following steps:

import junit.framework.TestCase;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reset;
import static org.easymock.EasyMock.verify;

public class UserServiceImplTest extends TestCase {
private UserDao userDaoMock;
private UserService us;
public void setUp() throws Exception {

// 1. create the mock for our DAO
userDaoMock = createMock(UserDao.class);

// 2. create an instance of the class under test
us = new UserServiceImpl();

// 3. wire test object and mock
us.setUserDao(userDaoMock);

}

/**
* after each test method call the mock has to be reset
*/
public void tearDown() throws Exception {
reset(userDaoMock);
}
}

Written by Ravi Nallakukkala on April 8th, 2007 with no comments.
Read more articles on Design.

SOA based Search Design - Handling of bulk data on server side

Its me again, For past few days my life is all about searching, search criteria and analyzing its result. The product I work has to scale up-to returning search results of the magnitude of few hundred records. Unfortunately we don’t have the luxury of having the pagination for these search results, hence there is a high amount of tuning required on the server side.

In this article I will be describing a SOA based search design for handling bulk data in a multi layered architecture; The project I was working was architect to have 3 layers: Facade Layer, Services Layer and a DAO Layer.

Facade layer was implemented though EJB 3 and as expected was the main communication interface for the client, our clients talk to the server side Facade though the Data Transfer Objects (Dto); One of the main responsibility of the facade is to convert Dto objects passed by the clients to the Business Object (Bo) for request processing and during response scenario, facade also converts the Business objects to the Dto and send the response to the client.

Service Layer is the place where the main business logic will placed,the communication to/ from the services layers always happens through the Business Objects. Main responsibilities of this layer include invoking the Data Access Object Layer (Dao) and invoking other Services.

Data Access Object Layer is mainly responsible for invoking the persistence api (most of the cases, it will be ORM like hibernate, JPA).

To achieve the flexibility in the design approach, Dto are used to communicate between the client and server, but it has to be noted that all the processing on the server side happens on Business Objects.

Considering this architecture, Even for a search case too, search criteria will be passed to the server in the form of a Dto, and in the facade layer this search criteria dto will be converted to a Bo and then the criteria in the form of a Business object will be passed to the Dao and based on the persistence technology an appropriate query will be executed and the results in the form of the Bo will be returned to the facade, where again the Bo will be converted to the Dto objects.

Now, this approach works very well for low to medium volume search result sites; in order to optimize this search we have been looking around for some options and finally arrived at saying “For searches, why not allow the criteria (Dto equivalent) to be passed to the Dao layer and get the results from Dao in the form of Dto”. Essentially, all we are doing is eliminating the conversions from Bo to Dto and vice-versa. For large volume Search results, the conversation to/ from Dto/Bo makes a big differences (time consuming process). This approach also gives us a flexibility of selecting any specific attribute in an entity (unlike the case-of the Query though Business Objects, the entire Business Object will be loaded even though you need a single attribute of that entity)

There is already some support by JPA to support this kind of architecture for searches, for example look at the following query

select new com.alpha.beta.SearchResult(emp.id, emp.name, emp.salary) from Employee emp

Now the ‘SearchResult’ class should have a constructor matching to the above construct

i.e,

public class SearchResult{

private Long id;
private String name;
private BigDecimal salary;

public SearchResult(Long id, String name,BigDecimal sal){
this.id = id;
this.name = name;
this.salary = sal
}
}

If the query retuns a ‘List’, In this example the list will contain a list of ‘SearchResult’ Objects.

To Summarize the advantage of this approach (of bi-passing the layers for search)

Written by Ravi Nallakukkala on April 1st, 2007 with no comments.
Read more articles on Design.

Search Pagination Design (Server side pagination using Hibernate)

One of the biggest problem which is commonly faced in searches is pagination; On the first day of my new job, I was asked to looked the performance issues related in the search functionality of the application. When I looked at the application, application is slow when the users gets a search results of magnitude of 6000 records( each record had 10 fields to be displayed) and all the results were displayed in a single HTML page (Even if you had designed one search implementation, you would have guessed what the problem is).

There is no pagination concept implemented for this search/ problem, its a logical thing to say this search program is using whole lots of memory and slow. Assuming the search queries are already fine-tuned, Slowness can be mainly attributed to the HTML rendering by the browser. IE browser render the complete HTML and then displays it to the user so the slowness can be easily be found compared to Firefox 2, where the browser starts displaying the data as it receives (rather completely render it and displays it).

Given this background, Now we started seriously looking at pagination as the only option. In pagination, could think three approaches as a potential solutions

Lets go in details of each one of them.

Real time pagination on the server side :

This is an approach where from the UI, always pass the search criteria plus the page start record and the end record (or size of the page). So your server implementation will have these two extra arguments along with your query and returns you only the required result set which needs to be passed to front end.

On the implementation front, you could handle this scenario at two levels

Query q = s.createQuery( “your query….” );
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();

Lets looks at the pros and cons of this approach

Criteria Caching based pagination on Server side

This is an approach where all records matching to the search criteria will be fetched from the database to the the server and cached. Caching is based the search criteria and a timeout period.

From the UI point of view, request will contain the search criteria plus the start record and the size( r the end record) to be fetched.

Lets looks at the pros and cons of this approach

Pagination on the UI front

This is an approach where all the records corresponding the search criteria will be retrieved from the database and held in the controller of the UI Framework and using custom tag libraries the records could be displayed in the Jsp/ Servlet.

Here are some of the recommendations for writing your own custom pagination tab lib

Lets looks at the pros and cons of this approach

Written by Ravi Nallakukkala on March 30th, 2007 with 2 comments.
Read more articles on Design and Hibernate.