Dec 282011
 

In this tutorial, I will guide you to integrate 2 power frameworks for Java EE application: Struts 2 and Hibernate 3 (I used the latest library version of them to the time I wrote this post). The example we will use is a simple blog, here is how it looks

struts hibernate integration blogging example thumb Struts 2 Hibernate 3 Integration Blogging Example

We will develop some main features of a blogging application:

  • To Create New Post
  • To List All Posts in One Page
  • To Manage Post: Edit/Remove Posts.

Software and Library needed:

  • Eclipse Indigo 3.7
  • Apache Tomcat 7.0
  • MySQL 5
  • MySQL Workbench
  • Struts 2.2.3.1
  • Hibernate Core 3.6.7
  • slf4j-1.6.2
  • apache-log4j-1.2.16
  • JSTL 1.2

Note: All of these are the latest up to October 2011.

1. Setup Eclipse, Tomcat and New Struts-Hibernate Project Lib

In Eclipse, select Java EE perspective. image thumb Struts 2 Hibernate 3 Integration Blogging Example

In the Server view, right click and select New to create a new Instance of Tomcat 7 (if you don’t have one).

Now from Eclipse, right click in Project Explorer then select New > Web > Dynamic Web Project

new struts hibernate project thumb Struts 2 Hibernate 3 Integration Blogging Example

Enter struts-hibernate-integration as the project name, select Tomcat 7 as the Runtime Server and you’ll be ready with a project structure like this.

image thumb1 Struts 2 Hibernate 3 Integration Blogging Example

Now you need to configure library for the application.

struts hibernate library thumb Struts 2 Hibernate 3 Integration Blogging Example

Please find the above jar file in these location:

  • struts-2.2.3.1lib
  • hibernate-distribution-3.6.7.Final
  • hibernate-distribution-3.6.7.Finallibrequired
  • hibernate-distribution-3.6.7.Finallibjpa
  • slf4j-1.6.2
  • apache-log4j-1.2.16
  • jstl-1.2

Now if you collect all of the above jar files, please copy them all to the folder WebContent > WEB-INF > lib

2. Configure Struts 2 Application

Your next step is to configure Struts 2 Application and to make sure it will work.

First thing to do is to configure Struts 2 Filter in web.xml file (find this file under WebContent > WEB-INF folder. Configure it like this: web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>struts-hibernate-integration</display-name>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Create an XML file with name: struts.xml and put it under your src folder (to make sure it will visible in build folder when we deploy), with the following content.

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="default" extends="struts-default" namespace="/blog">
		<action name="listBlog" method="listBlog"
			class="com.googlecode.frameworksintegration.action.BlogAction">
			<result name="success">/blog_listing.jsp</result>
		</action>
		<action name="newBlog" method="renderAddBlog"
			class="com.googlecode.frameworksintegration.action.BlogAction">
			<result name="success">/blog_adding.jsp</result>
		</action>

		<action name="addBlog" method="addBlog"
			class="com.googlecode.frameworksintegration.action.BlogAction">
			<result name="success">/notifications.jsp</result>
		</action>

		<action name="manageBlog" method="manageBlog"
			class="com.googlecode.frameworksintegration.action.BlogAction">
			<result name="success">/blog_manage.jsp</result>
		</action>

		<action name="deleteBlog" method="deleteBlog"
			class="com.googlecode.frameworksintegration.action.BlogAction">
			<result name="success">/notifications.jsp</result>
		</action>
	</package>
</struts>

You can see in the above struts config file that all the action we use in this example is point to BlogAction class, here is its content:

package com.googlecode.frameworksintegration.action;

import java.util.List;

import com.googlecode.frameworksintegration.dao.BlogDAO;
import com.googlecode.frameworksintegration.dao.BlogDAOImpl;
import com.googlecode.frameworksintegration.domain.Blog;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Struts 2 Integrated with Hibernate 3 blogging example.
 * http://java.searchdaily.net
 * @author namnvhue
 *
 */
public class BlogAction extends ActionSupport {
	private BlogDAO blogDAO = null;
	private List<Blog> blogs;
	private Blog blog;
	private String message;
	private String blogId;

	/**
	 *
	 */
	public BlogAction() {
		this.blogDAO = new BlogDAOImpl();
	}

	private static final long serialVersionUID = -4901097198092626247L;

	public String listBlog() {
		this.blogs = blogDAO.listBlogs();

		return SUCCESS;
	}

	public String manageBlog() {
		this.blogs = blogDAO.listBlogs();

		return SUCCESS;
	}

	public String renderAddBlog() {
		this.blog = new Blog();
		return SUCCESS;
	}

	public String addBlog() {
		blogDAO.save(this.blog);
		this.message = "Blog has been created successfully.";
		return SUCCESS;
	}

	public String deleteBlog() {
		this.blog = this.blogDAO.find(Integer.parseInt(blogId));
		this.blogDAO.delete(blog);
		this.message = "Blog has been removed successfully.";
		return SUCCESS;
	}

	public String editBlog() {
		return SUCCESS;
	}

	public String detail(String id) {
		return SUCCESS;
	}

	public List<Blog> getBlogs() {
		return blogs;
	}

	public void setBlogs(List<Blog> blogs) {
		this.blogs = blogs;
	}

	public Blog getBlog() {
		return blog;
	}

	public void setBlog(Blog blog) {
		this.blog = blog;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getBlogId() {
		return blogId;
	}

	public void setBlogId(String blogId) {
		this.blogId = blogId;
	}

}

If you enter all the above code now, Eclipse will give you some compiling error, but don’t worry, we will fix it softly.

3. Prepare MySQL database and Configure JPA persistence unit

We will use MySQL 5 as the database and JPA over Hibernate 3, first thing to do is to create a new schema named blog and create a blog table with the following structure:

CREATE TABLE `blog` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `CONTENT` text,
  `POSTED_BY` varchar(255) DEFAULT NULL,
  `POSTED_DATE` datetime DEFAULT NULL,
  `TITLE` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

Now in the src folder of the project, create a folder name: META-INF and create inside it a file name: persistence.xml.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="blogds">
		<class>com.googlecode.frameworksintegration.domain.Blog</class>
		<properties>
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/blog" />
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.password" value="mysql_password" />
			<property name="hibernate.connection.username" value="mysql_user" />
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
		</properties>
	</persistence-unit>
</persistence>
4. Configure Hibernate and DAO layer for Struts Application.

Now you will see how to configure an entity for using Hibernate. Here is the Blog class you see as the domain object in BlogAction action before.

package com.googlecode.frameworksintegration.domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * Struts 2 Integrated with Hibernate 3 blogging example.
 * http://java.searchdaily.net
 * @author namnvhue
 *
 */
@Entity
@Table(name = "BLOG")
public class Blog {

	private Integer id;
	private String title;
	private String content;
	private Date postedDate;
	private String postedBy;

	@Id
	@GeneratedValue
	@Column(name = "ID")
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(name = "CONTENT")
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Column(name = "POSTED_DATE")
	@Temporal(TemporalType.TIMESTAMP)
	public Date getPostedDate() {
		return postedDate;
	}

	public void setPostedDate(Date postedDate) {
		this.postedDate = postedDate;
	}

	@Column(name = "POSTED_BY")
	public String getPostedBy() {
		return postedBy;
	}

	public void setPostedBy(String postedBy) {
		this.postedBy = postedBy;
	}

	@Column(name = "TITLE")
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

}

The blogDAO interface:

package com.googlecode.frameworksintegration.dao;

import java.util.List;

import com.googlecode.frameworksintegration.domain.Blog;

/**
 * Struts 2 Integrated with Hibernate 3 blogging example.
 * http://java.searchdaily.net
 *
 * @author namnvhue
 *
 */
public interface BlogDAO {
	public Blog find(Integer id);

	public List listBlogs();

	public void save(Blog blog);

	public void delete(Blog blog);
}

The implementation of blogDAO using Hibernate

package com.googlecode.frameworksintegration.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.googlecode.frameworksintegration.domain.Blog;
/**
 * Struts 2 Integrated with Hibernate 3 blogging example.
 * http://java.searchdaily.net
 * @author namnvhue
 *
 */
public class BlogDAOImpl implements BlogDAO {
	private EntityManagerFactory entityManagerFactory;
	private EntityManager entityManager;

	public BlogDAOImpl() {
		this.entityManagerFactory = Persistence
				.createEntityManagerFactory("blogds");
		this.entityManager = entityManagerFactory.createEntityManager();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List listBlogs() {
		Query q = entityManager.createQuery("select blog from Blog blog");
		return q.getResultList();

	}

	@Override
	public void save(Blog blog) {
		entityManager.getTransaction().begin();
		entityManager.persist(blog);
		entityManager.flush();
		entityManager.getTransaction().commit();
	}

	@Override
	public void delete(Blog blog) {
		entityManager.getTransaction().begin();
		entityManager.remove(blog);
		entityManager.flush();
		entityManager.getTransaction().commit();
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@Override
	public Blog find(Integer id) {
		return entityManager.find(Blog.class, id);

	}

}

You won’t see any import from Hibernate here, because we use Hibernate as a Persistence Provider to JPA and for a standard rule, more and more projects are using it this way.

 Posted by at 3:20 pm
Sep 132011
 

In this post I will share some frequently use methods for Date/Time processing. These methods are needed for almost every project or project starters. Feel free to use and add more features to my class.

First are some Date Time Formatter like date formatter, 24h time formatter, 24h date time formatter…

public static final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
public static final SimpleDateFormat monthYearFormater = new SimpleDateFormat("MM/yyyy");
public static final SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm:ss");
public static final SimpleDateFormat datetimeFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
public static final SimpleDateFormat datetimeFormatterNoSecond = new SimpleDateFormat("dd/MM/yyyy HH:mm");
public static final SimpleDateFormat hourMinuteFormater = new SimpleDateFormat("HH:mm");
public static final SimpleDateFormat timeStampFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

You will use these formatters to parse String into Date so that you can use for calculation. Or you can use these formatters to format a Date into String so that you can use it to print out a console or notify user via a message.

Next is methods needed to get a Calendar instance, to operate with Date object, you definitely will need Calendar object.

public static Calendar getCalendar(Date date) {
	Calendar c = Calendar.getInstance();
	c.setTime(date);
	return c;
}

public static Calendar getCalendar() {
	Calendar c = Calendar.getInstance();
	c.setTime(new Date());
	return c;
}

Now what if you know date/month/year and want to have a Date object? The following methods will help you to build Date

	/**
	 * Build Date from date/month/year. Zero-based for Month (0=January).
	 * 
	 * @return
	 */
	public static Date buildDate(int year, int month, int date) {
		Calendar calendar = getCalendar();
		calendar.set(year, month, date);
		return calendar.getTime();
	}

	/**
	 * Build Datetime from date/month/year/hour/minute/second. Zero-based for
	 * Month (0=January).
	 * 
	 * @param year
	 * @param month
	 * @param date
	 * @param hour
	 * @param minute
	 * @param second
	 * @return
	 */
	public static Date buildDateTime(int year, int month, int date, int hour, int minute, int second) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, date, hour, minute, second);
		return calendar.getTime();
	}

Sometime you will also need to remove the Time part from a Datetime object, here is the method for that purpose

	/**
	 * Delete time from Date.
	 * 
	 * @param date
	 * @return
	 */
	public static Date removeTime(Date date) {		
		if (date == null) {
			return null;
		}

		// Obtain an instance of the Calendar.
		Calendar calendar = getCalendar(date);

		// Mark no automatic correction
		calendar.setLenient(false);

		// Remove the hours, minutes, seconds and milliseconds.
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);

		// Return the date again.
		return calendar.getTime();
	}

And not only to build a new Date object, you can use the following methods to adjust date, like get the previous date or get the next date or get yesterday or get tomorrow date

Continue reading »

Sep 102011
 

You’ve seen the Observer Pattern where subscriber get notified from publisher about events when something happened. It’s about the Listener/ Observer, how about another famous pattern named “Callback Pattern”?

What is Callback Pattern?

I can tell you that there’s some similarity about the notification, but the Callback Pattern is very much “Architectural Pattern” and only these diagram and definition can help you to distinguish.

image thumb20 Callback Pattern with RMI Client Callback

Callback Pattern is an Architectural Pattern that allows a client to register with a server for extended operations. This enables the server to notify the client when the operation has been completed.

image thumb21 Callback Pattern with RMI Client Callback

What can Callback Pattern help you?

Use the Callback pattern for a client-server system with time-consuming client operations, and when one or both of the following are true:

  • You want to conserve server resources for active communication.
  • The client can and should continue work until the information becomes available. This can be accomplished with simple threading in the client.
Callback Pattern Example

This Design Pattern is an architectural pattern and needs a server/client application to apply, so I will use the same example in my previous post about Proxy Pattern using RMI for the demo. To save your time, I won’t tell the story again but you should read and run the RMI example first before taking the next step.

First, I will define a BankClientCallback interface, which will act as a standardized channel for the server to interact with the client.

package net.searchdaily.java.design.pattern.callback;

import java.rmi.Remote;
import java.rmi.RemoteException;
/**
 * Callback Pattern with RMI tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public interface BankClientCallback extends Remote {
	public void notifyAction(String action) throws RemoteException;
}

As you can see to allow the server to interact with the client, the client’s now actually a server, so it’s much like server-to-server conversation. Next is for the Server interface

Continue reading »

Sep 082011
 

Go around and look for some method to remember Design Pattern, I saw a site summarize each Design Pattern with a line like this:

  • Abstract Factory: Creates an instance of several families of classes
  • Prototype: A fully initialized instance to be copied or cloned
  • Singleton: A class in which only a single instance can exist

But how can you remember it all? I cannot imagine that I can recall “Abstract Factory” is “Creates an instance of several families of classes” at all.

Design Pattern is so abstract and so hard to remember, so each time I write an entry about Design Pattern I do my best to put an easy to remember example. I believe the real life examples will be easier to understand and remember than the descriptions and principles.

Now let’s me summarize some Design Patterns by using Images of real life example.

 Singleton Pattern
searchdaily net java singleton design pattern thumb Remember Design Patterns by Images singleton pattern example images thumb Remember Design Patterns by Images

 

It’s the pattern of single service but multiple user like: there’s one receptionist at a hotel and there are multiple visitors. There is one President in a country and million citizens to manage

 Abstract Factory Pattern

Just think of the abstract Vehicle Factory that ferrari vs audi r8 thumb Remember Design Patterns by Imagescan produce any cars. And there are real Vehicle Factory like one is based in Germany (Audi and Mercedes) or factory is based in Italy like Ferrari and Iveco.

The same type of  products are created by different factories give different result in the end.

Factory Method Pattern

image thumb7 Remember Design Patterns by ImagesThe Factory method is much like Abstract Factory: to create different objects. But the difference is that Factory Method is not based on the different Factories but to base on different Parameters passed to the creator.

Take the calculator for example, base on the type of calculator we select, the different calculators will be created

 

Chain of Responsibility Pattern

The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver, by giving more than one object a chance to handle the request. Mechanical coin sorting banks use the Chain of Responsibility. Rather than having a separate slot for each coin denomination coupled with receptacle for the denomination, a single slot is used. When the coin is dropped, the coin is routed to the appropriate receptacle by the mechanical mechanisms within the bank.

chain of responsibility pattern thumb Remember Design Patterns by Images

Continue reading »

Sep 082011
 

You may hear of “Observer” or “Listener” somewhere especially when working with Swing or AWT. Do they have a difference? Some guys may even confuse between Observer and Listener, while actually they are the same concept in Java.

What is Observer Pattern?

Observer is a Behavior Design Pattern defined by GoF and the definition is maybe like this: “The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.” – from wiki.

Now let me take you to a closer look by observing an example:

observer pattern example thumb Observer Pattern Java Example

As you can read from the diagram, I will use a cellphone (BlackBerry in this case) to demonstrate this pattern. Each time there’s a call or an sms coming, a BlackBerry can notify you by multiple ways: via the ringtone, via a LED indicator or or via the Vibration…I treat these devices as the Observer object which will subscribe the SMSReceiver all the time for new SMS. If new SMS comes, these devices will be notified by the SMSReceiver to work accordingly.

Observer Pattern Example in Java

Now let’s see how we will explain the above example again in Java language.

blackberry sms receiver thumb Observer Pattern Java Example

First I will define the BBObserver object that can make BlackBerry device do something when some event happens.

package net.searchdaily.java.design.pattern.observer;

/**
 * Observer pattern example by searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public interface BBObserver {
	public void handleEvent();
}

Next is for the BBObservable object that can contain a list of subscriber object, and when some other objects tell it, it will notify all other subscribers about the event.

Continue reading »

Sep 052011
 

A programmer uses the keyboard more often than the mouse, and when typing, a right click to select a function also costs much time and effectiveness.

No matter you’re an eclipse user or a new comer to Eclipse, the following list of shortkeys can help you to save much time.

Ctrl + Shift + O : to open Resource.

image thumb5 Use short keys to save your time with Eclipse

You can use this shortkey to open almost everything, and the good news is that you can use expression character like * or extension like .java or .html… eg: if I want to search for a Java file that contains “Test” in the file name, I can use the expression like the above: *Test*.java.

Ctrl + / : to comment a line, Ctrl + Shift + / to comment multiple lines
Ctrl + E : to open current editors, you can use expression here to search for file name.

image thumb6 Use short keys to save your time with Eclipse

Ctrl + O : to open Inherited Members of class.

image thumb7 Use short keys to save your time with Eclipse

Tips: you can also use expression to search and jump to methods or fields.

Ctrl + Shift + O: To organize Imports

Most of the time, Eclipse can automatically imports classes in other packages for you. But sometimes you need to import them manually. Use Ctrl + Shift + O can help you import unique class automatically and for classes that have the same name, it will popup a selector for you.

Continue reading »

Aug 272011
 
What is Proxy Pattern?

Proxy is one of famous structural design pattern to “provide a surrogate or placeholder for another object to control access to it” (G.o.F).

image thumb96 Proxy Pattern tutorial and RMI example

In this diagram, you can see that Client want to doSomething() by the RealSubject. But we don’t want Client to interact with ReadSubject directly. Maybe there’s security reason or RealSubject is very costly, we can not deliver it to each Client. Instead we provide a proxy to each client, and when the client request to doSomething(), the RealSubject will do then.

When to use Proxy Pattern?

You use Proxy Pattern when you want to provide a representative of another object, for reasons such as access, speed, or security.

Proxy Pattern Example

bank atm proxy thumb Proxy Pattern tutorial and RMI example

Let take ATM and Bank as our example. The bank has so many customers and the cost for accessing to the Bank is so high (cost for traveling to the bank, cost for paying receptionist…). So that they provide ATMs, and via the ATM, customer can use the IBank to interact with the bank. Forgive me if I’m not good at describing but I will explain this better in Java language wlEmoticon smile33 Proxy Pattern tutorial and RMI example

First I will create an iBank interface which define some basic interactions between customers and bank.

package net.searchdaily.java.design.pattern.proxy;

/**
 * Proxy Pattern tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public interface IBank {
	/**
	 * Check account and return current balance
	 * 
	 * @param accountId
	 * @return
	 */
	public double checkBalance(String accountId);

	/**
	 * Withdraw amt $ from bank and return new balance if success, if not return
	 * current balance.
	 * 
	 * @param accountId
	 * @param amt
	 * @return
	 */
	public double withDraw(String accountId, double amt);

	/**
	 * Deposite $amt into account, if success return new balance, if not return
	 * current balance.
	 * 
	 * @param accountId
	 * @param amt
	 * @return
	 */
	public double deposit(String accountId, double amt);
}

Then I will create a Central Computer for the Bank, this computer will hold all of account and do all transactions (supposed so)

package net.searchdaily.java.design.pattern.proxy;

import java.util.HashMap;
import java.util.Map;

/**
 * Proxy Pattern tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public class BankCentralComputer implements IBank {
	Map accounts = new HashMap();

	public BankCentralComputer() {
		accounts.put("12345", 20000.0);
		accounts.put("11223", 30000.0);
		accounts.put("33112", 60000.0);
	}

	@Override
	public double checkBalance(String accountId) {
		if (validateAccount(accountId)) {
			return this.accounts.get(accountId);
		} else {
			System.out.println("Invalid Account");
			return 0.0;
		}
	}

	@Override
	public double withDraw(String accountId, double amt) {
		if (validateAccount(accountId)) {
			double currentBalance = this.accounts.get(accountId);
			double newBalance = currentBalance - amt;
			if (newBalance >= 0.0) {
				// Save account data
				this.accounts.put(accountId, newBalance);
				return newBalance;
			} else {
				System.out.println("You don't have enough money");
				return currentBalance;
			}
		} else {
			System.out.println("Invalid Account");
			return 0.0;
		}
	}

	@Override
	public double deposit(String accountId, double amt) {
		if (validateAccount(accountId)) {
			double currentBalance = this.accounts.get(accountId);
			double newBalance = currentBalance + amt;
			this.accounts.put(accountId, newBalance);
			return newBalance;
		} else {
			System.out.println("Invalid Account");
			return 0.0;
		}
	}

	boolean validateAccount(String accountId) {
		return this.accounts.containsKey(accountId);
	}

}

Now as it’s costly to use the Bank, they provide ATM everywhere for their customers

package net.searchdaily.java.design.pattern.proxy;

/**
 * Proxy Pattern tutorial by http://java.searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public class ATM implements IBank {
	private IBank proxifiedBank;

	public ATM(IBank realBank) {
		if (realBank != null) {
			this.proxifiedBank = realBank;
		} else {
			this.proxifiedBank = new BankCentralComputer();
		}
	}

	@Override
	public double checkBalance(String accountId) {
		return this.proxifiedBank.checkBalance(accountId);
	}

	@Override
	public double withDraw(String accountId, double amt) {
		return this.proxifiedBank.withDraw(accountId, amt);
	}

	@Override
	public double deposit(String accountId, double amt) {
		return this.proxifiedBank.deposit(accountId, amt);
	}

}

As you can see, the ATM can do exactly what the Central Computer of the Bank do. Actually, the ATM  cannot do stuff like withDraw, deposit or checkBalance, but they have to ask another subject to do it. In this case if we construct the ATM without any specific real subject for it, it will use the Central Computer.

Now let’s see how some engineer will test the ATM at his weekend wlEmoticon smilewithtongueout7 Proxy Pattern tutorial and RMI example

Continue reading »

Aug 242011
 

What will you do if you want to add more features to an existing class without changing it? The simplest answer would be to extends it, another good answer for this is to do like what the Composite Pattern does – to make a wrapper of the class. But for a better answer, we should use both of them with the Decorator Pattern.

What is Decorator Pattern?

To make it simple: the Decorator Pattern is one of the Structural Patterns that utilizes the combination of Extending and Wrapping a class in a standard way to add more features to a component.

And for an in-depth design, please see the example below:

decorator pattern example thumb Use Decorator Pattern to Enhance your Component

As you can see in the picture, there are three famous Text Editor that everybody knows: Notepad, Notepad++ and Word.

  • Notepad is the simplest text editor, it can create new text file and save them, everything is in plain-text only.
  • Notepad++ supports user by giving format various type of text file: .java, .php, .html (with color and folding), and it can save file with various file format too.
  • And finally Word is the biggest text editor here, with it you can edit and publish press: RichText format, picture, table, calculation and more are supported, save file in .DOC and .HTML and more if you need to.

That’s for the story about three characters we will use in the demonstration.

Decorator Pattern Example

First let’s see how we will define a standard for Notepad or Notepad++ or Word or whatever text editor must conform to: The TextEditor interface.

package net.searchdaily.java.design.pattern.decorator;

/**
 * Decorator Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public interface TextEditor {
	public String create(); // create text file

	public String edit(); // edit the file

	public String save(); // save the change to hard disk
}

And now we will create a decorator which wrapped the TextEditor to enhance it feature and also implements TextEditor interface to conform standard.

package net.searchdaily.java.design.pattern.decorator;

/**
 * Decorator Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public abstract class TextEditorDecorator implements TextEditor {
	protected TextEditor enhancedTextEditor; // will support more features later

	public TextEditorDecorator(TextEditor textEditor) {
		this.enhancedTextEditor = textEditor;
	}

	@Override
	public String create() {
		return this.enhancedTextEditor.create();
	}

	@Override
	public String edit() {
		return this.enhancedTextEditor.edit();
	}

	@Override
	public String save() {
		return this.enhancedTextEditor.save();
	}

}

Basic function like create(), edit() or save() we will ask the basic TextEditor to do it wlEmoticon smile31 Use Decorator Pattern to Enhance your Component

Continue reading »

Aug 232011
 

You have probably heard of Session Façade when you join some class or course for Enterprise JavaBean (EJB). But can you tell how to implement the Façade Pattern? In this post I will help you.

What is Façade Pattern?

The Session Façade implements exactly the idea of Façade Pattern. Let’s see how the EJB-specs describes the Session Façade by giving us this picture:

facade design pattern session facade thumb Façade Design Pattern Tutorial

As you can see, the above picture now can give you a first look at the definition of Façade: It’s the way of wrapping and hiding the complicated details from the client. Instead it give the client a simpler interface to do the job.

And for the formal one, we can say that: Façade is a Structural Design Pattern to provide a simplified interface to a group of subsystems or a complex subsystem.

Façade Pattern Example:

Let’s give an example by watching how a computer boot-upfacade pattern computer boot thumb Façade Design Pattern Tutorial

A computer is combined of so many parts/devices like: the CPU, the memory (RAM/ROM), the storage unit (HDD,CD,USB Flash)…and many others.

The process of booting a computer is as follow: CPU, Memory and Hard Drive are turn on() and then the CPU freeze() to wait for instructions to load() in to memory. CPU will then execute() command by command to startup the OS.

That’s for the story. Now as always, I will demo the above story with some Java source code:

Continue reading »

Aug 222011
 

Have you read or watch the anime named: Voltron: Defender of the Universe? That’s one good example of the Composite Design Pattern.

voltron composite design pattern thumb Composite Design Pattern Tutorial

As you can see there are 5 Lions combined to form Voltron for a greater power to defend the Universe. wlEmoticon openmouthedsmile3 Composite Design Pattern Tutorial That’s for the story and here is how we map it to technical definition:

“The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly” (From wiki)

When to use Composite Design Pattern?
  • When there is a component model with a branch-leaf structure (whole-part or container-contained).
  • When the structure can have any level of complexity, and is dynamic.
  • When you want to treat the component structure uniformly, using common operations throughout the hierarchy.
Composite Pattern Example

That’s quite long for the introduction, let’s me show you the example of the Voltron Super Robot wlEmoticon smile29 Composite Design Pattern Tutorial

Suppose that all Robots have names and they can fire() (with electric or laser I guess)

package net.searchdaily.java.design.pattern.composite;

/**
 * Composite Design Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public abstract class Robot {
	protected String name;

	/**
	 * Fire function.
	 * 
	 * @return true if fire successful, false if weapon error.
	 */
	abstract protected boolean fire();
}

The LionRobot is-a Robot which has its own firing capability.

package net.searchdaily.java.design.pattern.composite;

/**
 * Composite Design Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class LionRobot extends Robot {
	public LionRobot(String name) {
		this.name = name;
	}

	@Override
	protected boolean fire() {
		System.out.println(name + " is shooting ");
		return true;
	}

}

Next is the VoltronRobot class:

package net.searchdaily.java.design.pattern.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * Composite Design Pattern Tutorial by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class VoltronRobot extends Robot {
	List fiveLions;

	public VoltronRobot() {
		fiveLions = new ArrayList();
	}

	public void add(LionRobot lion) {
		if (null == fiveLions) {
			fiveLions = new ArrayList();
		}

		fiveLions.add(lion);
	}

	public void remove(LionRobot lion) {
		if (null != fiveLions && fiveLions.contains(lion)) {
			fiveLions.remove(lion);
		}
	}

	@Override
	protected boolean fire() {
		if (null != fiveLions && fiveLions.size() == 5) {
			for (LionRobot lion : fiveLions) {
				lion.fire();
			}
			System.out.println("SUPER LIONS POWER COMBINED FIRE AT ONCE");
		} else {
			System.out.println("Err...Voltron didn't collect enough Lions.");
		}
		return false;
	}

}

You can see that Voltron Robot has a list of list of Lions, and the Five Lions will be integrated into him later (composite). So for it easier to integrate, The Voltron Robot has the power to add() a lion to him or remove() it away.

Continue reading »