- Using Spring 2.0 and Java 5, it is possible to declare the transactions using annotation-based approach.
- Spring framework supports @Transactional annotation for declarative transaction handling, this annotation can be used on a concrete class or method (with public visibility) of a concrete class. This annotation can be used on an interface, but this will only work as you would expect it to if you are using interface-based proxies.
- The default @Transactional settings are:
- The propagation setting is PROPAGATION_REQUIRED
- The isolation level is ISOLATION_DEFAULT
- The transaction is read/write
- The transaction timeout defaults to the default timeout of the underlying transaction system, or none if timeouts are not supported
- Any RuntimeException will trigger rollback, and any checked Exception will not.
- Enabling the configuration of transactional behavior based on annotations can be done as follows
<tx:annotation-driven transaction-manager=”txManager”/> where txManager points the underlying transaction manager and the tx namespace refers to http://www.springframework.org/schema/tx
- Transaction rollback can be controlled though Transactional annotation for the property ‘rollbackFor’ and ‘rollbackForClassName’.
- Timeout for the transaction can be controlled through the Transactional annotation for the property ‘timeout’.
- Example usage for Declarative transaction with Annotations
(more…)
Written by Ravi Nallakukkala on April 10th, 2007 with no comments.
Read more articles on Spring.
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.

Guidelines for Unit Test Cases
- Write the test before implementing the functionality using a test driven approach. Every software component (business modules, services, DAOs, models or controllers of the presentation tier) will be designed to be tested.
- When a bug is identified in the code and later fixed, as a good practice write a unit test to validate it.
- Use Mock Object to collaborate with other components.
- Write the tests for normal success case, boundary conditions or any exceptional conditions.
- Make a decision if it’s really appropriate to write tests for simple methods or simple classes. These will get tested later during Integration Testing (like DTOs, get/set,..).
- Unit Test for Business Objects that only encapsulate data is not necessary. Only if the BO implements Business Logic, then this has to be tested using a unit test.
- While testing the Business Logic Layer, unit tests need to be written for every service interface. Use Mock Objects for DAO’s. Components used within the service implementation that contain validation logic will need to be tested independently. E.g. Validators, Convertors.
- For the Presentation Layer one would need to set up the page, pageView, pageModel and the PageContext. Mock Objects will be used to model the PageContext.
- The Test Coverage should be continuously monitored. Clover/ Cobertura could be used to for code coverage.
- The names of Java source files for testing end with ‘Test’, as in MyClassTest.java.
- While testing the Data Access Layer, make sure every DAO method has been tested. After each test the transaction should be rolled back so cleaning of the database is not required. (spring framework will do job of automatic rollback of data changes to the database).
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.
- While writing unit tests, any class that contains test methods should subclass the TestCase class. A TestCase can define any number of public testXXX() methods.
- To check the expected and the actual test results, one has to invoke the variation of assert() method.
- The Test Class having several testXXX() methods can use the setup() and teardown() methods to initialize and release any common objects under test.
- TestCase instances can be composed into TestSuite hierarchies so that all test methods are invoked
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:
- Create a Mock Object for the interface we would like to simulate
- Setup the Expected behavior. Record the expected method calls.
- Switch the Mock Object to replay state. If no expected behavior is set, then call to any methods of the collaborator class with throw an exceptions.
- Call object under test
- Validate if the expectations have been met.
- Code Snippet using JUnit & EasyMock
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.
In my new project, my team was using IntelliJ as their IDE and I come from a strong Eclipse background, Initially it was hard time to find out all the Shortcut Keys for IntelliJ so thought I could document the shortcut keys that I commonly use, I will update this list as my learning experience continues with IntelliJ
| Description |
Eclipse shortcut |
IntelliJ Shortcut |
| Navigate a Java Type |
CTRL + ALT + T |
CTRL + N |
| Navigate a Resource |
CTRL + ALT + R |
CTRL + SHIFT +N |
| Last Modified Source |
ALT + Left arrow |
CTRL + ALT + left arrow |
| Debug |
F11 |
Shift + F9 |
| Open Declaration |
F3 |
CTRL + SHIFT + B |
| Open Hierarchy |
F4 |
CTRL + H |
| Organize Imports |
CRTL + SHIFT + O |
CTRL + ALT + O |
| Find |
CTRL + F |
CTRL + F |
| Find Again/ previous |
F3 / SHIFT + F3 |
F3 / SHIFT + F3 |
| Step Into |
F5 |
F7 |
| Step Over |
F6 |
F8 |
| Step Out |
F7 |
Shift + F8 |
| Resume |
F8 |
F9 |
| To find impl of an abstract Method |
? |
Ctrl + Alt + B |
Written by Ravi Nallakukkala on April 6th, 2007 with no comments.
Read more articles on Editors.
Java serialization is a process of saving an object’s state to a byte stream and rebuilding the bytes into a Java object (may be at some future time).
As serialization is a concept based on maintaining the state of the object, so every attribute inside the object will have an impact on the amount of data serialized.
To explain the impact of unused variables on Java serialization lets take an example.
(more…)
Written by Ravi Nallakukkala on April 4th, 2007 with no comments.
Read more articles on Java/ J2EE.
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)
- There is no extra conversation To / From Dto/ Bo.
- It also possible for some cases to load the attribute without loading the entire Business Object.
- This approach also leaves the developer to use native SQL for complex sql which may not be implemented through some Persistence API.
Written by Ravi Nallakukkala on April 1st, 2007 with no comments.
Read more articles on Design.
No older articles
Newer articles »