Thursday, 28 August 2008

Adapter Pattern

Adapter Pattern converts interface of a class into another interface that client expects. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

This pattern is also known as Wrapper

There are two kinds of adapters.

1. Object Adapters
2. Class Adapters

Object Adapters : Object Adapters use a compositional technique to adapt one interface to another. The adapter inherits the target interface that the client expects to see, while it holds an instance of adaptee. Object adapters enable the client and the adaptee to be completely decoupled from eachother. Only the adapter knows about both of them.

Before going deeper let us have a simple example.

Consider the scenario where our legacy code that exposes the Enumerator interface, but we want our new code to only use iterators.

Here EnumerationIterator is our Adapter.

As we know Enumerator does not support remove(). There is no way to implement a fully functioning remove() method on the adapter. So let us try to throw RunTimeException. As we know remove() method in Iterator throws Unsupported Operation Exception. As long as client is careful (watchout for potential exceptions) and the adapter is well documented it is perfectly reasonable solution.

* We are Adapting Enumeration to Iterator.
* Adapter EnumeratorIterator implements Iterator to look like an Iterator

public class EnumeratorIterator implements Iterator{
Enumeration enumeration;

public EnumeratorIterator(Enumeration enumeration){
this.enumeration = enumeration;

// Iterator's hasNext() method is delegated to Enumerator's hasMoreElements()
public boolean hasNext(){
return enumeration.hasMoreElements();

// Iterator's next() method is delegated to Enumerator's nextElement()
public Object next(){
return enumeration.nextElement();

public void remove(){
throw new UnsupportedOperationException();

How can Client use Adapter:

1. The Client makes a request to the adapter by calling a method on it using the target interface.
2. The Adapter translates that request into one or more calls on adaptee using adaptee interface.
3. The client receives the result of the call and never knows there is an adapter doing the translation.

Class Adapters : Class adapters use multiple inheritance to achieve their goals. As in the object adapter, the class adapter inherits the interface of the client's target. However, it also inherits the interface of the adaptee as well. Since Java does not support true multiple inheritance, this means that one of the interfaces must be inherited from a Java Interface type. Note that either or both of the target or adaptee interfaces could be an Java Interfaces. The request to the target is simply rerouted to the specific request that was inherited fro the adaptee interface.

Differnce between Object Adapters and Class Adapters

1. As Object Adapter uses composition it can not only adapt an adaptee class, but any of its subclasses. It is flexible.

2. Class Adapter is commited to only one adaptee. But again it has an advantage as no need to implement the entire adaptee. It can just override the behaviour of adaptee and also can override the behaviour as it is subclassing.

3. Note that class adapters have a problem with name conflicts if methods of the same signature exist on both the target and the adaptee. Note that just because two objects have methods that have the same signature (syntax), it does not guarantee that the two methods have the same meaning or behavior (sematics). That is, the two methods do not necessarily map directly to each other. Object adapters do not have this problem.

4. Class adapters are simpler than object adapters in that they involve fewer classes and are useful if total decoupling of the client and adaptee is not needed.

Why should I use Adapter Pattern:

1. Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application.

2. We can not change the library interface, since we may not have its source code.

3. Even if we did have the source code, we probably should not change the library for each domain-specific application.

4. You don’t want your object models implementing JavaVM specific interfaces becuase they might change in the future.

When to use Adapter Pattern:

Use the Adapter pattern when

1. You want to use an existing class, and its interface does not match the one you need.

2. You want to create a reusable class that cooperates with unrelated classes with incompatible interfaces.

Some of the good OO design principles behind Adapter Pattern:

1. We use object composiition to wrap adaptee with an altered interface. This approach has an added advantage that we can use an adapter with any subclass of adaptee.

2. Pattern binds the client to an interface but not to implementation. We could use several adapters, each converting a different backend set of classes or we could add new implementations after the fact, as long as they adhere to target interface.

Two-way Adapter

A two-way adapter supports both the Target and the Adaptee interface. It allows an adapted object (Adapter) to appear as an Adaptee object or a Target object.

One way to implement two-way adapters is to use multiple inheritance, which can't be done in Java.

But we can have our adapter class implement two different Java interfaces. So the adapter can act as a Old Interface or New Interface.

Comparing Adapter Pattern with other Patterns:

1. Adapter converts one interface to another, Decorator doesn't alter interface but adds responsibility. Facade makes an interface simpler.
Decorator is thus more transparent to the application than an adapter is. As a consequence, Decorator supports recursive composition, which isn't possible with pure Adapters.

2. Adapters allows client to make use of libraries and subsets without changing any code. Decorators allow new behaviour to be added to the classes with out altering the existing code.

3. Adapter make things work after they're designed, Bridge makes them work before they are.

4. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.

5. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.

6. Facade defines a new interface, whereas Adapter reuses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one.

Design networked applications in RMI using the Adapter design pattern

More about Adapter pattern Does Java BuiltIn classes really follow Adapter Pattern ??

Hope this explanation helps.

Friday, 22 August 2008

Leadership Skills

Yesterday my husband advised me to read Develop your leadership skills . I started reading today and I couldn't stop myself in between. It is a great book written by John Adair.

Leadership skills have now been universally recognised as a key skill

It is possible to develop your own abilities as a leader. All this book is about How to do that.

I just want to share few points that I found intresting about leadership

Nobody can teach you leadership. It is something you have to learn. You learn principally from experience. But experience or practice has to be illuminated by principles or ideas.

A) PERSONALITY AND CHARACTER : Personality and Character are important qualities of leadership.

A Leader should possess, exemplify and perhaps even personify the qualities expected or required in his working group. Without it he will lack credibility. (Incidentally, here is one of the first differences between leaders and managers: the latter can be appointed over others in a hierarchy regardless of whether or not they have the required qualities.)

Qualities Of Leadership:

1. Enthusiasm. Can you think of any leader who lacks enthusiasm? It is very hard to do so, isn’t it?

2. Integrity. This is the quality that makes people trust you. And trust is essential in all human relationships – professional or private. ‘Integrity’ means both personal wholeness and adherence to values outside yourself – especially goodness and truth.

3. Toughness. Leaders are often demanding people, uncomfortable to have around because their standards are high. They are resilient and tenacious. Leaders aim to be respected, but not necessarily popular.

4. Fairness. Effective leaders treat individuals differently but equally. They do not have favourites. They are impartial in giving rewards and penalties for performance.

5. Warmth. Cold fish do not make good leaders. Leadership involves your heart as well as your mind. Loving what you
are doing and caring for people are equally essential.

6. Humility. This is an odd quality, but characteristic of the very best leaders. The opposite to humility is arrogance. Who wants to work for an arrogant manager? The signs of a good leader are a willingness to listen and a lack of an overweening ego.

7. Confidence. Confidence is essential. People will sense whether or not you have it. So developing self-confidence is always the preliminary to becoming a leader. But don’t let it become overconfidence, the first station on the track leading to arrogance.

Some may question the inclusion of integrity in this list. Are there not good leaders, such as Adolf Hitler, who totally lacked integrity? There is a useful distinction between good leaders and leaders for good. Whether or not Hitler was a good leader is a debatable matter – in some respects he was and in others he was not – but he was certainly not a leader for good. But this is all a bit academic. For leadership that does not rest on the bedrock of integrity does not last: it always collapses, and usually sooner rather than later. Why? Because that is the
way of human nature.

You can see that what you are is an important strand in your leadership. Remember the Zulu proverb, ‘I cannot hear what you are saying to me because you are shouting at me.’ This strand in your leadership is also one of the three main paths up the mountain, the three lines of answering those core questions
‘What is leadership?’ and
‘Why does one person rather than another emerge as the leader in a group?’

Review your progress as the profile of your strengths and weaknesses (in terms of personality and character) begins to unfold and change in the positive direction. Always remain open to feedback on that score, however painful it may be.

B) SITUATIONAL APPROACH : Some Generic leadership qualities are situation-related, but others – such as enthusiasm, moral courage and stamina – are found in leaders in widely different situations.

The main contribution of this situational approach is that it emphasises the importance of knowledge in working life; and knowledge is linked to authority. There are four forms of authority among people:

1. The authority of position and rank – ‘Do this because I am the boss!’

2. The authority of knowledge – ‘Authority flows to the one who knows.’

3. The authority of personality – in its extreme form, charisma.

4. Moral authority – personal authority to ask others to make sacrifices.

Knowledge creates confidence in others. For this reason your acquisition of technical and professional knowledge is actually part of your development as a leader.

But don’t imagine that having the appropriate technical or professional knowledge in itself qualifies you for leadership. Again, it is necessary but not sufficient. All the main strands of authority – position, knowledge and
personality – are important.

C) GROUP APPROACH : A third line of thinking about leadership focuses on the group. This group approach, as it may be called, leads us to see leadership in terms of functions that meet group needs: what has to be done.

Again we have three important areas in this approach
Task Need
Team Maintenance need
Individual Needs

These three areas of need overlap and influence one another. Leadership is essentially an other-centred activity – not a self-centred one.

D) VISION : Leaders at all levels should stimulate and focus a sense of direction. ‘Vision’ literally means to see where you are going. Allied with some creative thinking, it can provide a new direction for a group or an organisation.

E) PLANNING : Planning means building a mental bridge from where you are now to where you want to be when you have achieved the objective before you. But the key issue is how far you should make the plan yourself or how far you should share the planning function with your team. It depends on several key factors, notably the time available to plan and the competence level of the team members.

Planning requires that the what, why, when, how, where and who questions are answered.

F) BRIEFING : Briefing is the function of communicating objectives and plans to the team. It usually involves standing or sitting in front of the team and briefing them in a face-to-face way.

Like all functions, briefing can be done with skill, for there is a right way to brief a group and a wrong way. Briefing, in fact, is part of a much larger communication skill: effective speaking.

Here are some guidelines:

a. Be prepared. Rehearse and practise. Make sure that you have some professional-looking visual aids: ‘A picture is
worth a thousand words.

b. Be clear. Double-check that what you are saying is not vague, ambiguous or muddied – leave talk like that to the

c. Be simple. Reduce complicated matter to its simplest form without oversimplifying. Avoid technical language or
jargon that your audience will not understand.

d. Be vivid. Colour your message with enthusiasm, confidence and humour. Make it live – make it exciting and challenging and fun.

e. Be natural. You do not need to be a great orator. Just be yourself – your best self.

Speak properly, and in as few words as you can, but always plainly; for the end of speech is not ostentation, but to be understood. -- By William Penn
Briefing is not something that you do only at the outset of a project and then forget about. Most probably, especially if the team is new or inexperienced, you will have to repeat the objective and plan as work progresses. It is always a function waiting to be performed.

But again remember that listening is co-equal in importance. You need to be a listening leader.

G) CONTROLLING : Controlling is the function of ensuring that all the energy of the team, and the resources at its disposal, are turning wheels and making things happen.

Success at directing, regulating, restraining or encouraging individual and team efforts on the task (and in meetings) is the criterion for testing a leader’s effectiveness as a ‘controller’.

H) EVALUATING : Performance has to be judged in relation to those values, which are usually implicit in the organisation’s purpose.

As a leader, you should have a relationship with each member of the team – an equal but different relationship – as well as a relationship with the team as a whole. That will involve you in talking and listening to each individual. Your observations and conversations may lead you with some of them to take the role of a coach and counsellor.

I) MOTIVATION : As a leader you must understand needs in individuals and how they operate, so that you can work with the grain of human nature and not against it. You can refer
A H Maslow’s concept of a hierarchy of needs

Fifty per cent of our motivation comes from within us, as our unique pattern of individual needs unfolds inside ourselves and points us in certain directions. But the other 50 per cent comes from outside ourselves,
and especially from the leadership that we encounter. Therefore as a leader you can have an immense
effect upon the motivation of those around you.

Key principles for motivating others

1. Be motivated yourself. If you are not fully committed and enthusiastic, how can you expect others to be?

2. Select people who are highly motivated. It is not easy to motivate the unwilling. Choose those who have the seeds of high motivation within them.

3. Set realistic and challenging targets. The better the team and its individual members, the more they will respond to objectives that stretch them, providing these are realistic.

4. Remember that progress motivates. If you never give people feedback on how they are progressing, you will soon demotivate them.

5. Provide fair rewards. Not easy. Do you reward the whole team, or each individual, or both? Either way, the perception of unfair rewards certainly works against motivation.

6. Give recognition. This costs you nothing, but praise and recognition based upon performance are the oxygen of the human spirit.

J) ORGANISING : Organising function concerns more than structuring or restructuring the architecture of organisations. Systems, Admin and TimeManagement also come under Organising.

H) PROVIDING AN EXAMPLE : ‘Leadership is example,’It may take many shapes and forms, but it has to be there.

A short course on leadership.

The six most important words…
‘I admit I made a mistake.’

The five most important words…
‘I am proud of you.’

The four most important words…
‘What is your opinion?’

The three most important words…
‘If you please.’

The two most important words…
‘Thank you.’

The one most important word…

And the last, least important, word…

The Chinese philosopher Lao Tzu summed it up in the sixth century before the Christian era:

A leader is best
When people barely know that he exists;
Not so good when people obey and acclaim him;
Worst when they despise him.
Fail to honour people,
They fail to honour you.
But of a good leader, who talks little,
When his work is done, his aim fulfilled,
They will all say, ‘We did this ourselves.’

You cannot avoid being an example of some kind or other, simply because the people who work with you will always observe what you are and what you do as well as what you say.

One very powerful form of leading by example is sharing fully in the dangers, hardships and privations experienced by the team.

and finally....

Never be afraid of failure. The path forward will be strewn with the results of your failures as a leader. For the only way you can move from being a good leader – where you are now – to becoming a very good leader, even an excellent or a great one, is by aiming higher. And that is bound to generate shortfalls. But persevere. In the end they may say of you that you are a born leader!

About the Author

John Adair is the world’s leading authority on leadership and leadership development. Over a million managers worldwide have taken part in the action-centred leadership programmes he pioneered.

John had a colourful early career. He served as a platoon commander in the Scots Guards in Egypt, and then became the only national serviceman to serve in the Arab Legion, where he became adjutant of the Bedouin regiment. He was virtually in command of the garrison of Jerusalem in the front line for six weeks. After national service he qualified as a deckhand in Hull and sailed an Arctic steam trawler to Iceland. He then worked as an orderly in the operating theatre of a hospital.

After being senior lecturer in military history and adviser in leadership training at the Royal Military Academy Sandhurst, and Associate Director of the Industrial Society, in 1979 John became the world’s first Professor of Leadership Studies at the University of Surrey.

Between 1981 and 1986 John worked with Sir John Harvey-Jones at ICI, introducing a leadership development strategy that helped to change the loss-making, bureaucratic giant into the first British company to make £1 billion profit.

John has written over 40 books, translated into many languages. Recent titles include How to Grow Leaders and Effective Leadership Development. Apart from being an author, he is also a teacher and consultant.

From St Paul’s School he won a scholarship to Cambridge University. John holds the higher degrees of Master of Letters from Oxford University and Doctor of Philosophy from King’s College London, and he is also a Fellow of the Royal Historical Society. Recently the People’s Republic of China awarded him the title of Honorary Professor in recognition of his ‘outstanding research and contribution in the field of Leadership’.

Some of the Great Leaders

Leadership developement

Some of the great Leaders about leadership

A leader should know how to manage failure by Former Indian President APJ Abdhul Kalam

The Essence of Leadership by NarayanMurthy

‘It is easy to find a thousand soldiers but very difficult to find a general,’ says the Chinese proverb.
Then why cant you be the one...

Hope ths article helps you to excel your leadership qualities.

Thursday, 21 August 2008

Command Pattern

Command Pattern encapsulates request as an object, there by allowing you to parameterize other objects with different requests, and support the undoable operations.

Now we know that Command Pattern encapsulates request by binding together a set of actions on a specific receiver. To acheive this it packages the action and the receiver up into an object that exposes just one method, execute(). When called execute() causes the action to be invoked on the receiver. From outside no other objects really know what actions get performed on what receiver. They just know that if they call the execute() method, their requests will be served.

Command Pattern allows you to decouple the requester of an action from object that actually performs the action by introducing command objects.

This pattern works very well in GUI code, but it can be applied wherever it is possible and worthwhile to make operations reversible.

Commands may also be used to logging,queuing requests and transactional systems.

It is also possible for a command to be a collection of commands, called a Macro Command. Macro Commands are simple extension of Command that allow multiple commands to be invoked and they can easily support undo operations.

Before making our hand dirty just let us have a glance at the Structure of Command Pattern

Let us look at simple example

interface Command {
void execute();

class DomesticEngineerCommand implements Command {

Receiver receiver=null;

DomesticEngineerCommand(Receiver receiver) {

public void execute() {

class PoliticianCommand implements Command {

Receiver receiver=null;

PoliticianCommand(Receiver receiver) {

public void execute() {

class ProgrammerCommand implements Command {

Receiver receiver=null;

ProgrammerCommand(Receiver receiver) {

public void execute() {

public interface Receiver {

public void perform();

* Acts like an receiver

public class DomesticEngineer implements Receiver{

public void perform() {
System.out.println("Domestic Engineer::->take out the trash" );


* Acts like an receiver

public class Politician implements Receiver {

public void perform() {
System.out.println("Politician::->take money from the rich, take votes from the poor" );


* Acts like an receiver

public class Programmer implements Receiver {

public void perform() {
System.out.println("Programmer::->sell the bugs, charge extra for the fixes" );

public class Invoker {

private List<Command> queue = new ArrayList<Command>();

public void produceRequests(Command command) {

public void workOffRequests() {
for (Iterator<Command> it = queue.iterator(); it.hasNext(); )

public class Main {

public static void main(String[] args) {

// Initializing Receivers
Receiver engineerReceiver = new DomesticEngineer();
Receiver politicianReceiver =new Politician();
Receiver programmerReceiver = new Programmer();
// end of Initializing Receivers

// Initializing Commands
Command engineer = new DomesticEngineerCommand(engineerReceiver);
Command politician = new PoliticianCommand(politicianReceiver);
Command programmer = new ProgrammerCommand(programmerReceiver);
// End of Initializing Commands

// Initializing Invoker
Invoker invoker=new Invoker();

// Adding Commands
// End of Adding Commands




Command Pattern concept does not include or require undo. But it is a very intuitive and extensible way to implement it.

Difference between Strategy Pattern and Command Pattern

1. Both patterns involve multiple implementations of the same abstraction (as do several other design patterns), but that's only part of the story.

2. A Strategy Pattern is simply a particular algorithm plugged into calling code, that the calling object may delegate part of its work, but Command Pattern may be used for several purposes in a single run of its lifecycle: as well as being used to do some work, it may also be stored and recalled later for, say, auditing or undo functionality.

3. Where the patterns really differ is in what they conceptually encapsulate.

4. The Strategy Pattern involves encapsulation of an algorithm, but the Command Pattern effectively encapsulates method invocation.

Problem with Command Pattern

One of the problems with this pattern is that it can cause an explosion of little command classes. It is important to have a good naming convention and to do your best to factor common classes.

For more information on Command Pattern refer

Tuesday, 19 August 2008

Strategy Pattern


The Strategy Pattern defines a family of algorithms,encapsulates each one, and makes them interchangable. Strategy lets algorithm vary independently from clients that use it. This allows you to switch the algorithm that you are using at any time.

Advantages Of Using Strategy Pattern:

1. There are several advantages of using this. First, if you have several different behaviours that you want an object to perform, it is much simpler to keep track of them if each behaviour is a separate class, and not buried in the body of some method. Should you ever want to add, remove, or change any of the behaviours, it is a much simpler task, since each one is its own class. Each such behaviour or algorithm encapsulated into its own class is called a Strategy.

2. This will allow you to make code changes with less unintended consequences and adds more flexibility to your code

When should I use Strategy Pattern:

1. When you have several objects that are basically the same, and differ only in their behaviour, it is a good idea to make use of the Strategy Pattern.. like in the below example, we have differnt countrues who have struggled for independence but their struggle strategies are different.

Before designing the Client and Family Of Algorithms We should have a glance at some design priciples

1. Identify the aspects of your application that vary and seperate them from what stays the same.In our example all the three Countries celebrated Independence, but the strategy of struggle differs. So seperate the StruggleStrategy from FreedomStruggle Class.

2. Encapsulate what varies
So have a StruggleStrategy reference in FreedomStruggle class.

// Family of Algorithm

public interface StruggleStrategy {
void struggle();

public class Violence implements StruggleStrategy{
public void struggle(){
System.out.println("Violent struggle through War or someother way");

public class NonViolence implements StruggleStrategy{
public void struggle(){
System.out.println("NonViolent struggle through protests and noncooperation movements");

// End of Family Of Algorithm

public class FreedomStruggle {

StruggleStrategy struggleStrategy;

public void celebrateIndependence(){
System.out.println("Celebrate Independence");

public StruggleStrategy getStruggleStrategy() {
return struggleStrategy;

public void setStruggleStrategy(StruggleStrategy struggleStrategy) {
this.struggleStrategy = struggleStrategy;


public class IndianFreedomStruggle extends FreedomStruggle{
public IndianFreedomStruggle(){
struggleStrategy = new NonViolence();

public class AlgerianFreedomStruggle extends FreedomStruggle{
public AlgerianFreedomStruggle(){
struggleStrategy = new Violence();

public class AfricanFreedomStruggle extends FreedomStruggle{

public AfricanFreedomStruggle(){
struggleStrategy = new NonViolence();

public class StruggleResult {
public static void main(String[] args) {

FreedomStruggle nonviolentStruggle = new IndianFreedomStruggle();

FreedomStruggle violentStruggle = new AlgerianFreedomStruggle();

FreedomStruggle mixedStruggle = new AfricanFreedomStruggle();

//now try to change the behaviour (strategy of struggle) at rumtime
mixedStruggle.setStruggleStrategy(new Violence());



Hope the explanation helps.

Sunday, 17 August 2008

How to store and retrieve BLOB object using hibernate

As my first Blog entry, I just wanted to share one problem I faced yesterday while doing my personal project.

Problem :

How to store and retrieve BLOB object using hibernate. My requirement was to upload and download .doc files.


1) Declare a column resume having MEDIUMBLOB as datatype.

2) Inside hibernate business Object declare the resume field with type byte[] and have the methods to convert the BLOB object from database into byte array.

public class UserDetails extends GenericBO{

private byte[] resume;

public byte[] getResume() {
return resume;
public void setResume(byte[] resume) {
this.resume = resume;

/** Don't invoke this. Used by Hibernate only. */
public void setResumeBlob(Blob resume) {
this.resume = this.toByteArray(resume);

/** Don't invoke this. Used by Hibernate only. */
public Blob getResumeBlob() {
return Hibernate.createBlob(this.resume);

private byte[] toByteArray(Blob fromBlob) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
return toByteArrayImpl(fromBlob, baos);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (baos != null) {
try {
} catch (IOException ex) { } } } }

private byte[] toByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos)
throws SQLException, IOException {
byte[] buf = new byte[4000];
InputStream is = fromBlob.getBinaryStream();
try { for (;;) {
int dataSize =;
if (dataSize == -1) break;
baos.write(buf, 0, dataSize); } } finally { if (is != null) {
try { is.close(); } catch (IOException ex) { } } }
return baos.toByteArray(); }


public abstract class GenericBO implements Serializable,Auditable {

private String lastUpdatedBy;

public String getLastUpdatedBy() {
return lastUpdatedBy;

public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;

public Serializable save() {
return HibernateUtil.getInstance().currentSession().save(this);

public void delete() {

3. Include property resume in hibernate mapping file

<property name="resumeBlob" type="blob" column="resume" />

4. If you are using apache behieve as your Presentation layer framework, the data type of the resume field must be of type FormFile like below

public class UserDetailsTO implements Serializable{

private FormFile file;

// this is used only when retriving from database.
private byte[] resume;

public byte[] getResume() {
return resume;
public void setResume(byte[] resume) {
this.resume = resume;
public FormFile getFile() {
return file;
public void setFile(FormFile file) {
this.file = file;


5. To insert the resume in business process layer , first you have to read bytes from file using Input Stream.

public Long postResume(UserDetailsTO userDetailsTO){
Long id = new Long(0);
try {
Session session =HibernateUtil.getInstance().currentSession();
Transaction transaction= session.beginTransaction();

UserDetails resumeDetails = new UserDetails();

//reading bytes from InputStream
InputStream inputStream=userDetailsTO.getFile().getInputStream();
byte[] b = new byte[inputStream.available()];;


id = (Long);

} catch (Exception e) {
throw new RuntimeException(e);
return id;

6. How to download the file

public class ShowResume extends HttpServlet {

javax.servlet.ServletOutputStream servletoutputstream = null;

public void service(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
throws ServletException, IOException
HttpSession session=httpservletrequest.getSession(false);

UserDetailsTO resumeDetailsTO = null;


byte b[]=resumeDetailsTO.getResume();

try {
httpservletresponse.setHeader("Content-Disposition", "inline;filename=report.doc");
servletoutputstream = httpservletresponse.getOutputStream();
servletoutputstream.write(b, 0, b.length);
servletoutputstream = null;
b = null;
}catch(Exception ex) {

Hope this code helps for those who are having the same requirement...