Thursday, December 10, 2009

Reporting with "Jasper Reports"

Given simple steps shall be enough to generate reports with jasper-reports.

1. Add jasper-reports.jar & itext.jar to your application's lib folder / classpath.

2. Compose the report template file (.jrxml). You can use WYSIWYG editors like iReport or JasperAssistant plugin for eclipse to generate them.

3. Compile the .jrxml file to .jasper files with the editor or with the utility class JasperCompileManager

4. With the utility class JasperRunManager generate reports to your repository
With the utility class JasperPrintManager print the report to the configured printer.

Wednesday, November 11, 2009

Narrow the lookup...EJB

With Java EE 5 we can simply cast the EJB look-up to one of the remote interfaces.
But this will not do with J2EE.

We should use javax.rmi.PortableObject.narrow method to narrow the EJB look-up to home interface.

And the reason is, J2EE implementation requires RMI-IIOP to implement the remote interfaces.This RMI-IIOP demands that the real object must be wrapped around with a portable object.

This portable object encapsulates information about the real remote object.The client has to interogate the portable object to find the real remote object.This process ( of obtaining the real object from the portable object) is called "narrowing".

Monday, November 2, 2009

@TableGenerator - ID for your entities

@TableGenerator annotation lets you define auto generated id columns for your entities.
In a recent project with MySQL as the backend , I couldn’t create a sequence and tie it up with the JPA entity ( Still wondering how to do that…)
To resolve this, I made use of @TableGenerator annotation , created a table to store the latest id and tied it up with the entity.

private long studentId;

The @TableGenerator annotation defines that “TBL_KEYS” is the table to store the generated id for the entity.
STD_KEY is the column to store the generated id
STD_KEY_NAME is the column which has the key-name entries. The key name here is “studentkey” .
You can add another entry in TBL_KEYS named “mark_key” and map it to another entity TBL_MARKS.
@GeneratedValue annotation specifies that the id generated is of GenerationType.TABLE type and maps the already defined @TableGenerator with given name.

Tuesday, October 20, 2009

Spring & JPA for your web-application

This blog will help you to configure Spring with JPA for your web application.
1. Make sure you have these SPRING .jars in your classpath

2. Make sure you have your JPA-persistence API in your classpath. You can get it from OpenJPA / Jboss Hibernate.
In my case I chose ejb3-persistence.jar from hibernate.

3. Make sure you have your persistence provider jars in classpath (hibernate / toplink / openjpa)
In my case I chose toplink and kept these jars in classpath.
Note: Toplink requires class transformation when loading and unloading entities, so you should start your server with spring-agent.jar
In my case I started my tomcat6 server with this VM argument

4. Make sure that you have your jdbc driver jars in classpath.
I copied mysql-connector-java.jar to tomcat's lib directory.

Steps to configure JPA + Spring in your web-application

Steps:1.Define your entities in my-persistence.xml
Note: We didn't define/write a "persistence.xml" so that the servlet containerwill not bring up the default persistence unit.

2.Define your spring listeners in web.xml

<context-param> <param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener>

3.Define a spring configuration file (WEB-INF/applicationContext.xml)

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=""
xmlns:tx="" xmlns:context="" xsi:schemaLocation=" "></beans>

4.Define your datasource in applicationContext.xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/dbname" /> <property name="username" value="username" /> <property name="password" value="password" /> </bean>

5.Define your entityManagerFactory in applicationContext.xml

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter" > <property name="showSql" value="true" /> <property name="generateDdl" value="false" /> <property name="databasePlatform" value="oracle.toplink.essentials.platform.database.MySQL4Platform" /> </bean> </property>
<property name="persistenceXmlLocation" value="META-INF/my-persistence.xml" /> </bean>

6. Define your transactionManager in applicationContext.xml

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" > <property name="entityManagerFactory" ref="entityManagerFactory" /> <property name="dataSource" ref="dataSource" /> </bean>

7.Define your advice & point-cuts for transaction demarcation.I am using spring annotation for transaction demarcation.
<tx:annotation-driven />

8.Make sure that you configure these beans in applicationContext.xml for processing your JPA annotations
<bean class=""/>

Thats it !!! You have configured Spring with JPA in your web-application.

Thursday, October 8, 2009

The SPRING season...

Spring, a non-intrusive framework was developed with the aim to reduce the complexity of Java Enterprise developement.

Spring plumbs together your components (POJOs) of a modular java application, may it be enterprise or web and stays out of your code.

At the core of Spring framework is the Spring Container that constructs your POJOs (on demand) and wire them together with dependency injection (a form of IoC - Inversion of Control ) to construct the application.

Spring comes with ready-made modules to support ORM,Java Enterprise Apps,Web MVC,Remoting & AOP.

Straight forward applications of Spring are
1) Plumbing / Wiring POJOs together to construct a modular application
2) Aspect Oriented Programming (AOP)
3) Dependency Injection
4) Abstraction of data access through DAO pattern
5) Abstraction of various ORMs (Hibernate, Toplink, JPA) and uniform simple access to all.

Friday, October 2, 2009

Integrate Spring with JSF1.2

With JSF1.2 the <variable-resolver> element of faces configuration (faces-config.xml) has been deprecated. The new element <el-resolver> has been added and replaces <variable-resolver> in <application> element tree.

When we integrate Spring with JSF we write in our faces-config.xml as


But with JSF1.2 we should write and integrate Spring with JSF as


Your web.xml entries remains unchanged

Note: SpringBeanFacesELResolver is available only in Spring 2.5 API

Friday, September 25, 2009

Mandatory field Marking with Custom Tags..

In a web-page’s form there always exist some mandatory fields.

We alert the end-user with a marking (*) along the side of the input fields.

Usually we tend to write labels in HTML like this in all the pages

<span >*</span>

When developing with JSP we can encapsulate this label / mark in a JSTL custom taglib and bring it in the page with our own tags.

JSTL encapsulates common functionality required for web-pages as tags.It provides a mechanism to extend and write our own functionalities.

What is the use of doing it that way?
  • Your code resides in a common place.
  • When there is are requirement to change the marker ( from “*” to “#” or from “red” to “green”) its easy.
  • You get exposure to write your own custom tag ...its cool..

Steps to write a marker custom tag:

  1. Write your tag handler class.
  2. Describe your tag handler class in a .tld (tag library descriptor) file
  3. Introduce the .tld file to your web application with a fancy name in web.xml

Your custom tag is ready and you can use it in your web page.

Step # 1: Write a tag handler class
package dev.aha;


import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

* A TagHandler class to provide mandatory-marker for
* HTML forms
* Note: This class extends javax.servlet.jsp.tagext.TagSupport
* since it doesn't have a body else you should extend BodyTagSupport
* @author AhamedM
public class MandatoryTag extends TagSupport {

private static final long serialVersionUID = 1L;

* An attribute to define the color of the marker You can ignore this if not
* needed..
private String color;

public String getColor() {
return color;

public void setColor(String color) {
this.color = color;

* Note : We are overriding only the doStartTag() method because what we are
* developing is a empty-bodied-tag
public int doStartTag() throws JspException {

JspWriter out = pageContext.getOut(); // Get the writer from pageContext
try {
if (getColor() == null getColor().equals("")) {
out.write("<span style=\"color:red\">*</span>");
} else if (color.equals("blue") color.equals("green"))
out.write("<span style=\"color:" + color + "\">*</span>");
} catch (IOException iex) {

* We are returning SKIP_BODY as the body of this tag is empty
return SKIP_BODY;

Step# 2: Describe the tag & tag handler in mytaglib.tld file

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
<shortname>Ahamed Tag Lib</shortname>
<info>My Simple Tag library</info>
<!-- A Simple tag -->
Body content can have a value of empty: no body JSP: body that is
evaluated by container, then possibly processed by the tag
tagdependent: body is only processed by tag; JSP in body is not
<info> This is a simple tag to indicate mandatory fields. </info>

<!-- Optional attributes -->

Step#3: Introduce the mytaglib.tld in web.xml



That’s it…Yes..Its done…You can use this tag in your page to mark the fields..

Sample index.jsp page with our custom tag

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib uri="AhamedSampleTld" prefix="aha"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mandatory field- Sample</title>
<form action="someUrl">
<td><aha:mandate />PAN No.</td>
<td><input type="text" /></td>
<td><input type="submit" value="SUBMIT" /></td>

ENJOI !!!!!

Tuesday, September 15, 2009

Simple, Safe & Synchronized

Java compiler is free to re-arrange the instructions provided by our java program in the name of optimization.

There are many cases where access to the variables can occur in an order than specified in the program.

A straight-forward example is:

A thread T has to write a value to a variable _va and then to a variable _vb, and if _vb is not dependent on _va, the compiler can reorder these write instructions.Write to _vb can happen before a write to _va.

In general instruction re-orders cannot be a problem in single-threaded programs but when it comes to multi-threaded programs, the re-orders can result in data race (inconsistent data) if not properly synchronized.

To ensure that any thread at any time gets the updated value/state of an object (updated by other threads), our program must have read/write operations that comply with happens-before relationship.

In simple, happens-before relationship guarantees that memory writes in one specific statement is visible to another specific statement.

Some of the actions that create happens-before relationship are:

* Thread.start
* Thread.join
* Synchronization

We also have certain other actions that creates happens-before relationship.

Synchronization is an action that can effectively prevent data race and state inconsistency. Synchronized Methods & Synchronized Statements are 2 ways that Java provides to implement this synchronization action.

These 2 provisions automatically establish happens-before relationship.

How synchronized method works:

Any object in java exists with an implicit/intrinsic lock. When a thread enters a synchronized method of an object it is this lock which it acquires. Other threads must wait for that lock gets released. When the synchronized method is static the implicit lock of the class is used.

Any arbitrary thread that waits for that lock will be intimated and enter the synchronized method. This synchronize action ensures that any write that happened inside the synchronized method is visible to the new thread entering the synchronized method.

How synchronized statements works:

Synchronized statements provide a more granularity over the counterpart. With this provision you can mark a set of statements as a synchronized block and at any time only one thread can enter this block. Unlike synchronized methods, the synchronized statements must specify the object that provides the implicit lock.

Examples for synchronization will follow....

Sunday, September 13, 2009

Simple scenarios with Java generics

A prominent feature added in Java 5.0 is “generics” which enables a programmer to write more type-safe code (code that is tied to specific expected type.. so that no surprises occur at run-time). can say that an API/ code utilizes “generics” when you see strange angle brackets i.e. <> in its method signatures/ class declarations.
Java compiler makes use of a technique called “Type Erasure” to erase the information related to type parameters so that the binary form maintains compatibility with old API (before generics)
You can see that collection framework in Java 5.0 heavily utilizes “generics”
Listed are the simple scenarios where we use generics in day-to-day programming
Scenario#1 :
Declare variables of generic types and instantiate generic type classes (like ArrayList,HashMap,TreeSet,Iterator)

List<String> names = new ArrayList<String>();
/* This guarantees that the items in “names” are always instances of java.lang.String as your code expects.
This enables you to run a for loop and traverse through the list without a class casting */

ArrayList<Car> listForAnyCar=new ArrayList<Car>();
listForAnyCar.add(new Ferrari());
listForAnyCar.add(new Camry());

In the given list you can add any type of Car i.e any class that extends the class Car.

Scenario#2: Pass generic type collections to methods.
You can declare that a method expects generic type collections as argument.

public void takeOnlyListOfStrings(List<String> strings)
for(String astring: strings)
System.out.println(“One of the string is”+astring);

Example# 4:
public void updateListOfCars(List<Car> allCars)
allCars.add(new HondaAccord());

Write generic methods
A generic method means that the method declaration uses a type parameter in its signature.

public <U> boolean inspectTheList(U u) {
return allCars.contains(u);

This method intakes any object and checks if the list allCars contains the object .
This method can further improved to add some more constraints.

public <T extends Number> boolean inspectTheList(T t)
----This signature declares that method inspectTheList can take only objects of type or subtypes of Number

public <T extends Comparable> boolean inspectTheList(T t)
---This signature declares that method inspectTheList can take only objects that implements Comparable..Yes… extends in generics means extends/implements

public <T extends Comparable & Serializable> boolean inspectTheList(T t)
---This signature declares that only objects that implements Serializable AND Comparable can be passed as parameters.

Here are some points you should be aware while declaring and using generic type collections.
1. ArrayList<Car> allCar = ArrayList<HondaAccord>(); // gives compilation error
2. ArrayList<Car> allCar = ArrayList<Car>;//compiles successfully.So compiler won’t bother if this list takes HondaAccord or Ferrari but it should be a Car.

Tuesday, September 8, 2009

By the grace of ALMIGHTY ..Welcome all !!

You... Thinking Java is cool ???

I hear a BIG "Yes"..

Then we are in same page ...

Insha ALLAH I shall update this site (blog) with valuable Java contents / updates / hints that I collect from web & books in my style :)

Definitely my postings shall aid you & me in understanding & appreciating Java better...

Watch out for more...