Sunday, October 31, 2010

Spring framework - beans

Introduction

As we all know Spring framework represent standard in Java application development. It can be used in desktop application or on web apps. It can help us with database access, security, RMI, web layer (MVC) and it can also integrate with other technologies like cutting edge GWT, or little bit older Flex stuff. There is also great Roo stuff (GWT or flex front-end)...but I don't know is this technology mature enough.

Spring framework secret lies in its simplicity, small footprint, ability to test outside of container.

In this article we will become more familiar with framework essential stuff -- wiring and instantiating Java POJO classes (Beans).

Source for following examples can be downloaded from my google code repository.

Spring wiring

In Spring, components (mainly Java classes...nothing fancy like CORBA or DCOM don't worry) are not responsible for managing their associations with other components, instead, references are passed through container. Controlling associations between components (passing reference from one place to another) is know an wiring. And this is at heard of Spring philosophy. This components are called beans and they share similarities with Java beans. And all this philosophy started with one of the greatest book in Java ecosystem: Expert One-on-One J2EE Design and Development.

Spring also act as bean factory (see my blog post about factory pattern that is here). But unlike many implementations of factory pattern, which often can create only single type of object, spring bean factory can create many different types of beans (list, data sources,...as you will see).

Off course, container is at the core of the Spring framework. This container uses inversion of o control (please see my post about template method design pattern that follows this principle, also known as Hollywood principle - "Don't call us, we will call you!") to manage component associations. There are several Spring containers and we will use Applicationcontext container that is most widely used and provide most basic Spring features we will explore in this post.

I choose to use simple Java application and not web app, because there are already many different examples of using Spring in web application and in this way we can avoid additional configurations and complexities that comes with web apps. For testing we will not use JUnit, but simple "public static void main".

In our simple Java application we will use Spring 2.5.6 (because it is lightweight -- 1.2MB with only essential libraries, and because I want to integrate it to Google App Engine at some point), we will also use XML file for bean wiring and defining. I don't like annotations because they mix with my code and break apart non-intrusive concept. I don't shy away from XML, because I think XML is not evil if you use it in right situations (like this one).

I will not go into details with Spring framework (like life cycle of bean), but I will just show main Spring futures on example (this will be enough to learn basic concepts). So let's start!

Example introduction

We will implement simple Employee (n)<->(1) Department system. This system can (beside classic CRUD operations) find largest department (department with largest number of employees), assign employee to that department and remove employee from department...and that's that!

Example service layer

First we will implement service layer of our example application. This is because service layer is on the top of abstraction hierarchy. In service layer we define operations we want our application to support.

There are two service components in service layer defined by interfaces (it is important to program to interface not implementation!): employee and department service. Employee service handles following employee matters (it's basically simple CRUD):

public interface EmployeeService {

    Employee findEmployee(int employeeId);

    void removeEmployee(int employeeId);

    List getAllEmployees();
    
    void createNewEmployee(Employee employee);

}

Department service can provide following operations (services):

public interface DepartmentService {
   
    Department findDepartment(int departmentId);
    
    void createNewDepartment(Department department);

    void removeDepartment(int departmentId);
    
    List getAllDepartments();
   
    /**
     * Find department with largest number of employees.
     * @return
     */
    Department findLargestDepartment();

    /**
     * Assign employee into department.
     * @param employee
     * @param department
     */
    void assign(Employee employee, Department department);
    
    /**
     * Remove employee from department.
     * @param employeeId
     * @param departmentId
     */
    void remove(int employeeId, int departmentId);

}

As you can see Department service provide couple of more complex operations than simple CRUD.

We have two classes that implement these two service interfaces:

Employee service concrete implementation:

public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeDao employeeDao;

    public Employee findEmployee(int employeeId) {
        return getEmployeeDao().findById(employeeId);
    }

    public void createNewEmployee(Employee employee) {
        getEmployeeDao().create(employee);
    }

    public void removeEmployee(int employeeId) {
        Employee deleteEmployee = getEmployeeDao().findById(employeeId);
        getEmployeeDao().delete(deleteEmployee);
    }

    public List getAllEmployees() {
        return getEmployeeDao().retrieveAll();
    }

    public EmployeeDao getEmployeeDao() {
        return employeeDao;
    }
    
    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }   

Department service concrete implementation:

public class DepartmentServiceImpl implements DepartmentService {

    private DepartmentDao departmentDao;
    private EmployeeService employeeService;

    public Department findDepartment(int departmentId) {
        return getDepartmentDao().findById(departmentId);
    }

    public void createNewDepartment(Department department) {
        getDepartmentDao().create(department);
    }

    public List getAllDepartments() {
        return getDepartmentDao().retrieveAll();
    }

    public Department findLargestDepartment() {
        Department largestDepartment = getAllDepartments().size() > 0 ? getAllDepartments().get(0) : null;

        for (Department dep : getAllDepartments()) {

            if (dep.getEmployees().size() > largestDepartment.getEmployees().size()) {
                largestDepartment = dep;
            }
        }

        return largestDepartment;
    }

    public void removeDepartment(int departmentId) {
        Department deleteDepartment = findDepartment(departmentId);
        getDepartmentDao().delete(deleteDepartment);
    }

    public void assign(Employee employee, Department department) {
        if (department.getEmployees().size() < department.getMax()) {                                    
            getEmployeeService().createNewEmployee(employee);
            getDepartmentDao().addEmployee(department, employee);
        }
    }
    
    public void remove(int employeeId, int departmentId) {
       
        Department department = findDepartment(departmentId);
        Employee deleteEmployee = getEmployeeService().findEmployee(employeeId);

        getDepartmentDao().removeEmployee(department, deleteEmployee);
        
        if (department.getEmployees().isEmpty())
            removeDepartment(departmentId);
    }

    public EmployeeService getEmployeeService() {
        return employeeService;
    }

    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    public DepartmentDao getDepartmentDao() {
        return departmentDao;
    }
    
    public void setDepartmentDao(DepartmentDao departmentDao) {
        this.departmentDao = departmentDao;
    }
    
}
There is no much stuff going on here (regarding both services - Employee and Departments) , as you can see much of the responsibility is delegated to underlaying DAO (Data Access Object) bean. Data Access Object beans handle interactions with database (or some other type of data storage - flat files for example, vintage databases, ...) to read and write employees and departments informations.

Implementation of these beans are not important for understanding Spring basic, so I will omit them (you can see implementation from downloadable example if you are curious). Let just say that implementation of these DAO beans in this example is very simple and it uses only java.util.List to hold data. You will see how we initially fill this list using Spring. So no persistence logic is implemented.

As you can see we both EmployeeServiceImpl and DepartmentServiceImpl can be given a reference to its DAO bean through "set" (setEmployeeDao and setDepartmentDao) method. You can also set them through constructor.

Example wiring

We choose XML as strategy for bean wiring. Wiring beans is quite simple. We use "" tags to define one Java Bean (or any Java object, actually -- it not need to be bean) to be configured with the Spring container.

Spring beans are by default singletons, but you can make beans to act like prototypes by setting singleton="false" attribute on bean element.
So we have something like this to define DepartmentService bean (EmployeeService bean is defined in same way):

        
            
        
        
            
        
    
In this simple bean XML wiring, we define bean with id departmentService and point to the full qualify class name (this class is concrete implemented class -- not interface). At this point we added a bean into Spring container (registered it) and now we can do whatever we want with this bean.

Beans can have properties. These properties are nothing more than Java properties. So we map these bean properties into Java properties (in this case) using XML. That is that.

This technique for populating a bean property based on standard naming convention is called dependencies injection. Off course this Java properties need to have matching "get" and "set" method (like in Java beans, or like in JSP/JSF backing beans). And this process is in the core of Spring framework (OK, there is also some other things like Aspect Oriented Programming - AOP, but I will talk about that later).

We can set properties with simple types (like int, long, float, String...) or we can set references to other beans (other Java object of any kind) like in this example (using ref tag). In this way and in our example we give DepartmentServiceImpl a reference to class that implement DepartmentDao interface (ref bean="departmentDao"/>).

Referencing other beans enable us to inject other beans into existing beans and in this way we create references between classes not as part of class logic but in Spring container this help us in leveraging this job to Spring and help us create cleaner and meaner code with ability of changing references only in XML.

We can also wire collections in Spring. In our example we did't use persistence logic or database, we just use simple java.util.List collections to hold data. So we use Spring to inject this data into DAO beans. We set list of departments into Java property named departments that have following type definition: java.util.List. So, we fill up one bean property with list of departments, this list of departments is defined in Spring XML file like so (I will show only one):

        
            1
        
        
            QA
        
        
            2
        
        
            
        
        
            
                
            
        
    
In this way we initially fill up collection that list of Departments.

Spring test

In oder to test Spring you need to do following:
ApplicationContext context = new ClassPathXmlApplicationContext("simpleappcontext.xml");

EmployeeService employeeService = (EmployeeService)context.getBean("employeeService");

DepartmentService departmentService = (DepartmentService)context.getBean("departmentService");

First get instance of context and read bean definition from xml file named "simpleappcontext.xml".
Then just get beans by their names and use them. :)

See my example for detail insight.

Friday, October 15, 2010

Oracle ADF advanced techniques - Dynamically changing query in view object

Introduction

If you have strange requirements then you may need sometimes to dynamically change SQL query where clause in View Object. I have such requirement when customer said that I can not create additional indexes on table. I overcome that problem by dynamically change SQL query where clause (to use indexes that were available).

To use this functionality, you need to override buildWhereClause(StringBuffer sqlBuffer, int noBindVars) method in view object implementation. You use sqlBuffer parameter in this method (which contains SQL query where in StringBuffer) to change SQL in correlation to you needs. Just replace, remove, add string in this parameter. Just remember to use same bind variables names which will be use in VO SQL call (generic bind variables names are named like :vc_temp_1, :vc_temp_2,...).

Ok, here is the code:

@Override
    protected boolean buildWhereClause(StringBuffer sqlBuffer, int noBindVars) {

        //call super and see if there is where clause.
        boolean hasWhereClause = super.buildWhereClause(sqlBuffer, noBindVars);

        if (hasWhereClause) { 
            //modify existing where query.
        }
        else { 
            //or if you add where clause then return true;
            hasWhereClause = false; 

        }

        return hasWhereClause;
    }

Thursday, October 14, 2010

Oracle ADF advanced techniques - Custom view object based on JDBC or Ref Cursor

Introduction

By default view objects read their data from the database and automate the task of working with the JDBC on our behalf. However, if we override specific methods in View Object implementation class, we can create our own mechanism for retrieving data for custom view object. We can use everything from web services, xml files, plain jdbc, or specific database constructions (like cursors in oracle database). So in this example we will show how can you create read-only view object uses cursor as alternative data source. This construction is called "ref cursor". Ok, let's begin!

Initial JDeveloper setup

1. Create Application module. In our case it is application module that have connection to FOD database.

2. Now create read-only view object that select person_id, first_name, last_name (just tree for sanity reason) from person table in FOD scheme. Don't forget to generate view object class (*Impl). Query for view object will be simple:
SELECT person_id, first_name, last_name
  FROM persons
 WHERE first_name LIKE :person_name

And how it look in JDev:


3. Then create Bind Variable with name "person_name".


Test it:



And move on...

Initial database setup

If you intent to use Ref Cursor, you need to create function in pl/sql that return Ref Cursor. we will create following package in FOD scheme.

CREATE OR REPLACE PACKAGE fod_ref_cursor
IS
   TYPE ref_cursor IS REF CURSOR;

   FUNCTION get_person_from_name (f_name VARCHAR2)
      RETURN ref_cursor;
END fod_ref_cursor;
/

SHOW errors

CREATE OR REPLACE PACKAGE BODY fod_ref_cursor
IS
   FUNCTION get_person_from_name (f_name VARCHAR2)
      RETURN ref_cursor
   IS
      the_cursor   ref_cursor;
   BEGIN
      OPEN the_cursor FOR
         SELECT person_id, first_name, last_name
           FROM persons
          WHERE first_name LIKE f_name;

      RETURN the_cursor;
   END get_person_from_name;
END fod_ref_cursor;
/

SHOW errors
You can test Ref cursor in following way:
SET serveroutput on;

DECLARE
   the_cursor     fod_ref_cursor.ref_cursor;
   p_id           persons.person_id%TYPE;
   p_first_name   persons.first_name%TYPE;
   p_last_name    persons.last_name%TYPE;
BEGIN
   the_cursor := fod_ref_cursor.get_person_from_name ('Steven');

   LOOP
      FETCH the_cursor
       INTO p_id, p_first_name, p_last_name;

      EXIT WHEN the_cursor%NOTFOUND;
      DBMS_OUTPUT.put_line (p_id);
   END LOOP;
END;

Customizing framework

Then you need to override some methods from PersonsImpl.java.

(This code bellow is taken from Oracle Fusion advance ADF examples and little bit simplify).

public class PersonImpl extends ViewObjectImpl {

    private static final String FUNCTION_NAME =
        "fod_ref_cursor.get_person_from_name(?)";
    private static final String BIND_VARIABLE_NAME = "person_name";

    private void fillAttributes(ViewRowImpl r,
                                ResultSet rs) throws SQLException {
        populateAttributeForRow(r, 0, rs.getLong(1));
        populateAttributeForRow(r, 1, rs.getString(2));
        populateAttributeForRow(r, 2, rs.getString(3));
    }


    /**
     * This is the default constructor (do not remove).
     */
    public PersonImpl() {
    }

    /**
     * Overridden framework method.
     *
     * Executed when the framework needs to issue the database query for
     * the query collection based on this view object. One view object
     * can produce many related result sets, each potentially the result
     * of different bind variable values. If the rowset in query is involved
     * in a framework-coordinated master/detail viewlink, then the params array
     * will contain one or more framework-supplied bind parameters. If there
     * are any user-supplied bind parameter values, they will *PRECEED* the
     * framework-supplied bind variable values in the params array, and the
     * number of user parameters will be indicated by the value of the
     * numUserParams argument.
     */
    protected void executeQueryForCollection(Object qc, Object[] params,
                                             int numUserParams) {
        storeNewResultSet(qc, retrieveRefCursor(qc, params));
        super.executeQueryForCollection(qc, params, numUserParams);
    }

    /**
     * Overridden framework method.
     *
     * Wipe out all traces of a built-in query for this VO
     */
    protected void create() {
        getViewDef().setQuery(null);
        getViewDef().setSelectClause(null);
        setQuery(null);
    }

    /**
     * Overridden framework method.
     *
     * The role of this method is to "fetch", populate, and return a single row
     * from the datasource by calling createNewRowForCollection() and populating
     * its attributes using populateAttributeForRow().
     */
    protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {
        /*
     * We ignore the JDBC ResultSet passed by the framework (null anyway) and
     * use the resultset that we've stored in the query-collection-private
     * user data storage
     */
        rs = getResultSet(qc);

        /*
     * Create a new row to populate
     */
        ViewRowImpl r = createNewRowForCollection(qc);

        try {
            /*
       * Populate new row by attribute slot number for current row in Result Set
       */
            fillAttributes(r, rs);
        } catch (SQLException s) {
            throw new JboException(s);
        }
        return r;
    }

    /**
     * Overridden framework method.
     *
     * Return true if the datasource has at least one more record to fetch.
     */
    protected boolean hasNextForCollection(Object qc) {
        ResultSet rs = getResultSet(qc);
        boolean nextOne = false;
        try {
            nextOne = rs.next();
            /*
       * When were at the end of the result set, mark the query collection
       * as "FetchComplete".
       */
            if (!nextOne) {
                setFetchCompleteForCollection(qc, true);
                /*
         * Close the result set, we're done with it
         */
                rs.close();
            }
        } catch (SQLException s) {
            throw new JboException(s);
        }
        return nextOne;
    }

    /**
     * Overridden framework method.
     *
     * The framework gives us a chance to clean up any resources related
     * to the datasource when a query collection is done being used.
     */
    protected void releaseUserDataForCollection(Object qc, Object rs) {
        /*
     * Ignore the ResultSet passed in since we've created our own.
     * Fetch the ResultSet from the User-Data context instead
     */
        ResultSet userDataRS = getResultSet(qc);
        if (userDataRS != null) {
            try {
                userDataRS.close();
            } catch (SQLException s) {
                /* Ignore */
            }
        }
        super.releaseUserDataForCollection(qc, rs);
    }


    /**
     * Return a JDBC ResultSet representing the REF CURSOR return
     * value from our stored package function.
     */
    private ResultSet retrieveRefCursor(Object qc, Object[] params) {
        ResultSet rs =
            (ResultSet)callStoredFunction(OracleTypes.CURSOR, FUNCTION_NAME,
                                          new Object[] { getNamedBindParamValue(BIND_VARIABLE_NAME,
                                                                                params) });
        return rs;
    }

    private Object getNamedBindParamValue(String varName, Object[] params) {
        Object result = null;
        if (getBindingStyle() == SQLBuilder.BINDING_STYLE_ORACLE_NAME) {
            if (params != null) {
                for (Object param : params) {
                    Object[] nameValue = (Object[])param;
                    String name = (String)nameValue[0];
                    if (name.equals(varName)) {
                        return (String)nameValue[1];
                    }
                }
            }
        }
        throw new JboException("No bind variable named '" + varName + "'");
    }

    /**
     * Store a new result set in the query-collection-private user-data context
     */
    private void storeNewResultSet(Object qc, ResultSet rs) {
        ResultSet existingRs = getResultSet(qc);
        // If this query collection is getting reused, close out any previous rowset
        if (existingRs != null) {
            try {
                existingRs.close();
            } catch (SQLException s) {
            }
        }
        setUserDataForCollection(qc, rs);
        hasNextForCollection(qc); // Prime the pump with the first row.
    }

    /**
     * Retrieve the result set wrapper from the query-collection user-data
     */
    private ResultSet getResultSet(Object qc) {
        return (ResultSet)getUserDataForCollection(qc);
    }


    //----------------[ Begin Helper Code ]------------------------------
    public static int NUMBER = Types.NUMERIC;
    public static int DATE = Types.DATE;
    public static int VARCHAR2 = Types.VARCHAR;

    /**
     * Simplifies calling a stored function with bind variables
     *
     * You can use the NUMBER, DATE, and VARCHAR2 constants in this
     * class to indicate the function return type for these three common types,
     * otherwise use one of the JDBC types in the java.sql.Types class.
     *
     * NOTE: If you want to invoke a stored procedure without any bind variables
     * ====  then you can just use the basic getDBTransaction().executeCommand()
     *
     * @param sqlReturnType JDBC datatype constant of function return value
     * @param stmt stored function statement
     * @param bindVars Object array of parameters
     * @return function return value as an Object
     */
    protected Object callStoredFunction(int sqlReturnType, String stmt,
                                        Object[] bindVars) {
        CallableStatement st = null;
        try {
            st =
 getDBTransaction().createCallableStatement("begin ? := " + stmt + "; end;",
                                            0);
            st.registerOutParameter(1, sqlReturnType);
            if (bindVars != null) {
                for (int z = 0; z < bindVars.length; z++) {
                    st.setObject(z + 2, bindVars[z]);
                }
            }
            st.executeUpdate();
            return st.getObject(1);
        } catch (SQLException e) {
            throw new JboException(e);
        }
    }

    /**getEstimatedRowCount - overridden for custom java data source support.
     */
    public long getEstimatedRowCount() {
        long value = super.getEstimatedRowCount();
        return value;
    }


    /**
     * Returns the bind variable value for person_name.
     * @return bind variable value for person_name
     */
    public String getperson_name() {
        return (String)getNamedWhereClauseParam("person_name");
    }

    /**
     * Sets value for bind variable person_name.
     * @param value value to bind as person_name
     */
    public void setperson_name(String value) {
        setNamedWhereClauseParam("person_name", value);
    }
}

You can use this exactly same code, you just need to change FUNCTION_NAME and BIND_VARIABLE_NAME and complete code for fillAttributes method in oder to properly map JDBC result set to View Object attribute set. Simple as that.

As I can see, this kind of data pulling in View Object in some circumstances event speed up data load.

Plain JDBC data pull

If you want to use plain JDBC instead of Cursor, you can do something like this:
protected Object callStoredFunction(int sqlReturnType, String stmt,
                                        Object[] bindVars) {
        PreparedStatement st = null;
        try {
                        
            st = getDBTransaction().createPreparedStatement("SELECT person_id, first_name, last_name\n" + 
            "  FROM persons where person_id = 100", 0);
            
            return st.executeQuery();
        } catch (SQLException e) {
            throw new JboException(e);
        }
    }


Code for this example can be downloaded from here: http://codingwithpassionblog.googlecode.com/files/CustomViewObject.zip

Saturday, October 9, 2010

XPath tutorial for busy programmer

Introduction

As w3.org standard say: XPath is a language for addressing parts of an XML document. Ok...that is simple enough. XPath is just basically a mean to traverse XML document and perform search on it. We can use structure of the XML document (semantics of data), or on data itself to perform that search. We can use XPath in XML transformations (XSLT), in SOA (BPEL language). And as I can see jQuery use similar logic for its selector search operations.

XML document

XPath can query any part of the XML document (any node at any level - XML documents are treated as trees of nodes). As a result of search, XPath may return null, string, number or another XML node (that can also be queried). XPath is used to navigate through elements or attribute of an XML document.

We will use following XML document:


 
  Arcade
  MAME
  true
 
 
  Pocket
  Sony PSP
  false
   
 
  Console
  Nintendo Wii
  true
 
  
  Console
  Sony PS2
  true
 


Basic node selection

To navigate through XML document we are using path expressions. The most to common expressions we will use are slashes : single ("/"), or double ("//").

Single slash will perform search from root node. In our XPath search as: "/game-systems/system/type" will return following result (in XMLSpy):




Double slash will perform traverse through XML tree and find out all nodes that match the selection no matter where they are in XML. So selection: "//type" in our example will produce same result as previous example.



Also common expression path to select XML nodes are: "@, ., ..".

"@" is used to select attribute, as in: "/game-systems/system/emulator/@usable", where we select value of usable attribute in system node.



"." will select current node, and ".." parent node. This is similar like selecting file path in file system!

Selecting parent of emulator node (hint: system): "/game-systems/system/emulator/..".



Finding specific node

To find some specific nodes we use predicates. With this construction we can perform search to find node with specific element or attribute value. Also we can extract specific result from node set result (if there is more that one node as result from previously search). Predicates are always embedded in square brackets.

Finding first system/emulator value can be done with following search:
"/game-systems/system[1]/emulator".

To find all system name with usable emulator we will write:
"/game-systems/system/emulator[@usable='true']/../name" -- here we use ".." as a way to move up to previous element in XML tree.



Finding node-set relative to the current node

We can also use XML tree structure (you know, children, parents and stuff) to find specific nodes.

For example, we can write previous example as follows: "/game-systems/system/emulator[@usable='true']/ancestor::system/name.

This is somewhat longer but it does same thing. Here we are using ancestor function that return ancestor of current element (system in this case). You can also search for child, attributes, descendants and similar searches that you can also perform (in most cases) using basic node selectors and predicates.

Monday, October 4, 2010

Design Patterns in Java - Template Method

Introduction

This is first article about OO design patterns, we will start with the most useful pattern.
Template method (GoF - Gang Of Four) present good example of using concrete inheritance. If you ask me, using inheritance in this way is far more productive than using concrete inheritance for code reuse. Everything you think you can do with concrete inheritance, you can do also with plain object composition. But, ok...never mind about that, let's write something about template method pattern.

You can download example of this Java code from my repository on google code:
https://code.google.com/p/codingwithpassionblog/source/browse/trunk/src/org/codingwithpassion/patterns/templateMethod/DecorateData.java

Usage

This pattern address common problem: we know the steps of an algorithm and the order in which they should be performed, but we don't know (or don't care) how to perform all of the steps. Template method encapsulate individual steps we don't know how to perform to abstract methods in abstract superclass. Concrete subclass will implement these methods. These method represent individual steps in an algorithm. In this way, superclass (abstract one) will control the flow (workflow) of algorithm. Subclasses just fill the gaps in superclass algorithm.

In this example this centralized workflow logic is example of inversion of control. In this approach the superclass is calling methods from subclass. This is fundamental approach for lean and clean code and code reuse.

Let's see example (this example can be put in one file for easy testing - it have only one public class):
/**
 * Abstract implementation -- class that control flow.
 * Describe algorithm for generic object creation.
 *
 */
abstract class CreateObject {
 
 protected Object[] datas = {"Kimmi", "Zuco", 1, 21};
 
 public void setData(Object[] data) {
  CreateObject.this.datas = data;
 }
 
 /**
  * Algorithm that control flow (IOC - Inversion of Control).
  * @return Object String representation. 
  */
 public String decorate() {
  StringBuilder sb = new StringBuilder();
  objectStart(sb);
  
  for (int i = 0; i < datas.length; i++) {
   Object data = datas[i];
   if (data instanceof String) {
    stringValue(sb, data, i);
   } else if (data instanceof Integer) {
    numberValue(sb, data, i);
   }
  }
  objectEnd(sb);  
  return sb.toString();
 }
 
 //these classes (down) need to be implemented in subclasses.
 abstract void objectStart(StringBuilder sb);
 
 abstract void objectEnd(StringBuilder sb);
 
 abstract void stringValue(StringBuilder sb, Object value, int indx);
 
 abstract void numberValue(StringBuilder sb, Object value, int indx);
 
}

/**
 * Object creation for JSON objects;
 *
 */
class JSONObject extends CreateObject {
 
 protected void objectStart(StringBuilder sb) {
  sb.append("\"Object\":").append("\n{");
 }
 
 protected void objectEnd(StringBuilder sb) {
  sb.append("\n}");
 }
 
 protected void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append("\"").append(value).append("\",")
    .append("\n");
    
 }
 
 protected void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append(value).append(",")
    .append("\n");
 }
}

/**
 * Object creation for xml objects.
 *
 */
class XmlObject extends CreateObject {
 
 protected void objectStart(StringBuilder sb) {
  sb.append("").append("\n");  }    protected void objectEnd(StringBuilder sb) {   sb.append("");
 }
 
 protected void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
 protected void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
}

public class DecorateData {
 
 public static void main(String[] args) {
  CreateObject xml = new JSONObject();
  System.out.println(xml.decorate());
 }
 
}
Lot of stuff going of there, but don't worry. Main thing to understand is flowing:

6 - 32: We declare abstract class that encapsulate workflow of creating string representation of object.
18 - 32: Implementation of algorithm - workflow. This algorithm use abstract methods (35 - 42) that need to be implemented by subclasses (He calls these methods from subclasses, hence Inversion of Control paradigm).
49 - 73: First implementation that implement abstract method and create JSON string object representation...nothing fancy.
79 - 111: Same thing, but for Xml Object representation.

112 - 120: Testing...

Conclusion

Such patterns as this offer good paradigm for separation of concerns. We can for example create superclass that will concentrate on business logic (and flow of that business logic), and use subclasses for primitive operation (technical stuff, JPA, servlets, parsing, JDBC,...).

It is useful to use Template method patter to capture an algorithm in one place, but deffer implementation of simple steps to subclasses. This has the potential to avoid bugs, by getting tricky operations right once in superclass and simplifying user code.

Please check post about Strategy design pattern that is very similar like Template, but instead abstract class uses interface.

Design Patterns in Java - Strategy

Introduction

Strategy pattern is alternative to Template method. But in case of Strategy pattern we use interface instead of abstract class. Please read more about this type of encapsulating logic in post about Template method if you are interested. Here we will here just show differences in correlation to TM.

You can download example of this Java code from my repository on google code:
https://code.google.com/p/codingwithpassionblog/source/browse/trunk/src/org/codingwithpassion/patterns/strategyMethod/DecorateData.java

Example

So in this case, class that knows the algorithm is not an abstract superclass, but a concrete class that uses a helper that implements an interface defining individual steps. You will use this type of pattern if you need to use concrete inheritance for some other purpose (because as we all knows Java and similar languages does not support multiple inheritance), or you just like this approach better because you are not forced to inherit from abstract class. Whatever is you reason, here is example:
/**
 * Concrete Object implementation. 
 * Here we implement workflow.
 */
class CreateObject {
 
 protected Object[] datas = {"Kimmi", "Zuco", 1, 21};
 
 public void setData(Object[] data) {
  CreateObject.this.datas = data;
 }
 
 /**
  * Algorithm that control flow (IOC - Inversion of Control).
  * @return Object String representation. 
  */
 public String decorate(DecoratorHelper helper) {
  StringBuilder sb = new StringBuilder();
  helper.objectStart(sb);
  
  for (int i = 0; i < datas.length; i++) {
   Object data = datas[i];
   if (data instanceof String) {
    helper.stringValue(sb, data, i);
   } else if (data instanceof Integer) {
    helper.numberValue(sb, data, i);
   }
  }
  helper.objectEnd(sb);  
  return sb.toString();
 }   
}
/**
 * Helper interface to which we defer individual steps.
 *
 */
interface DecoratorHelper {
 
 void objectStart(StringBuilder sb);
 
 void objectEnd(StringBuilder sb);
 
 void stringValue(StringBuilder sb, Object value, int indx);
 
 void numberValue(StringBuilder sb, Object value, int indx);
}

/**
 * Object creation for JSON objects;
 *
 */
class JSONObject implements DecoratorHelper {
 
 public void objectStart(StringBuilder sb) {
  sb.append("\"Object\":").append("\n{");
 }
 
 public void objectEnd(StringBuilder sb) {
  sb.append("\n}");
 }
 
 public void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append("\"").append(value).append("\",")
    .append("\n");
    
 }
 
 public void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("prop")
    .append("\"").append(indx).append("\":")
    .append(value).append(",")
    .append("\n");
 }
}

/**
 * Object creation for xml objects.
 *
 */
class XmlObject implements DecoratorHelper {
 
 public void objectStart(StringBuilder sb) {
  sb.append("").append("\n");
 }
 
 public void objectEnd(StringBuilder sb) {
  sb.append("");
 }
 
 public void stringValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
 public void numberValue(StringBuilder sb, Object value, int indx) {
  sb.append("")
    .append("prop")
    .append(indx)
    .append("")
    .append(value)
    .append("")
    .append("")
    .append("\n");  
 }
 
}
/**
 * Testing...
 *
 */
public class DecorateData {
 
 public static void main(String[] args) {
  CreateObject xml = new CreateObject();
  
  System.out.println(xml.decorate(new XmlObject()));
 }
 
}
37 - 46: First we move template methods into an interface. Definition is same as in previous example.
52 - 76, 82 - 114: In implementation of our interface we do not need to subclass anything anymore. But note that we must change access mode of method to public because this time we will to access them from outside class hierarchy.
17: Note that we need to provide interface type to our template method. This type will be substitute to concrete instance of class at runtime (Polymorphism is great stuff!). Method is exactly same as in TM example.

Which to choose?

This approach is more complex, but is more flexible. This is classic example of trade-off between concrete inheritance and delegating to an interface. Decision what to choose is completely up to you and may be influenced by circumstances like: Class implementing steps needs its own inheritance hierarchy, how many steps are involved, how many different implementation will you have...