Five ‘s Weblog

November 14, 2007

Command Pattern

Filed under: Programming — by powerdream5 @ 10:04 pm
Tags:

       I am not going to introduce the definition of Command Pattern, as well as the advantage and disadvantage of it. You can find many articles about that on the internet. Here, I just wanna give an example and realiz it by command pattern. (command pattern in wiki)

       There are two cleaner. One is responsible for sweeping the floor, and the other one is responsible for rubbing the table.  However, both of them are lazy. They never do their job until the supervisor commands them.

       There is no doubt it is suitable for command pattern to realize this problem. The following is my code:

//the command interface
public interface Command{
       public void executeCommand();
}

//concrete command 1
public class RubTableCommand implements Command{
       private Worker worker;
       public RubTableCommand(Worker worker){
             this.worker = worker;
       }

       public void executeCommand(){
            worker.doJob();
       }
}

//concrete command 2
public class SweepFloorCommand implements Command{
       private Worker worker;
       public SweepFloorCommand(Worker worker){
             this.worker = worker;
       }

       public void executeCommand(){
             worker.doJob();
       }
}

//the receiver interface
public interface Worker{
       public void doJob();

//receiver 1
public class CleanerForRubTable implements Worker{
 
      public void doJob(){
          System.out.println(“Rubbing floor”);
      }
}

//receiver 2
public class CleanerForSweepFloor implements Worker{
 
      public void doJob(){
         System.out.println(“Sweeping floor”);
      }
}

//the invoker
public class InvokeCommand{
       private Command command;

       public void setCommand(Command command){
            this.command = command;
       }

       public void sendCommand(){
            command.executeCommand();
       }
}

 //the client
public class Supervisor{
 
       public static void main(String[] args){
             Worker cleanerForSweepFloor = new CleanerForSweepFloor();
             Worker cleanerForRubTable = new CleanerForRubTable();
  
             InvokeCommand ic = new InvokeCommand();
             Command command = new RubTableCommand(cleanerForRubTable);
             ic.setCommand(command);
             ic.sendCommand();

            command = new SweepFloorCommand(cleanerForSweepFloor);
            ic.setCommand(command);
            ic.sendCommand();  
       }
}

11_14_1_2007.jpg

October 24, 2007

org.apache.commons.beanutils

Filed under: Programming — by powerdream5 @ 10:53 pm
Tags: , ,

10_24_1_2007.jpg

       Today, I found a userful utility classes package when I read my former notes. It is org.apache.commons.beanutils, one of the packages of Jakarta commons. We call the org.apache.commons.beanutils package Bean Introspection Utilities. When we use setter to initialize the properties of a Javabean, especially which has a lot of properties, we always complain that there are many setter methods needed to write. Fortunately, with the help of the org.apache.commons.beanutils, we can just use one sentence to realize that. The following is an example: (you need to download the package firstly)

//User.java a simple javabean
public class User{
        private String username;
        private String password;
        private int age;

        //the setter, getter methods
        public String getUsername(){
               return username;
        }
        public void setUsername(String username){
              this.username = username;
        }
       …omit to save space …
}

import java.util.HashMap;
//import the necessary class
import org.apache.commons.beanutils.BeanUtils;

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

              //in order to show this example, I create a map
             //if this class is a servelet, we can use request.getParameterMap()
             //get all the properties of the form stored in a map

             HashMap map = new HashMap();
             map.put(“username”,”powerdream5″);
             map.put(“password”,”5maerdrewop”);
             map.put(“age”,”23″);
 
            User user = new User();
            try{
                  BeanUtils.populate(user,map);
            }catch(Exception e){
                  e.printStackTrace();
            }

           System.out.println(“Username:”+user.getUsername());
           System.out.println(“Password:”+user.getPassword());
           System.out.println(“Age:”+user.getAge());
       }
}

       populate(java.lang.object bean, java.util.Map properties) is a static method. This method can do some basic type conversions such as from String to int. However, if there are a mismatch with the type, and cannot be converted, an exception will be thrown.

10_24_2_2007.jpg

       Using this package relly makes things easy. However, some people point that the performance of this package is not good, whichis not as good as using the setter method directly. In fact, we can find the factors which influence the performance. The org.apache.commons.beanutils package is based on the mechanism of reflection. Therefore, before we can assign value to the properties, we have to introspect the bean class to find proper properties, then invoke the setter methods. Compared with using setter methods directly, this method really take a detour. However, if you don’t care a little loss in the performance of your application, and want to save some effort, using this package does no harm!

10_24_3_2007.jpg

October 16, 2007

An example of JMock!

Filed under: Programming — by powerdream5 @ 8:35 pm
Tags: , , ,

        Test-Driven Development(TDD) has already been proved to be a best practice for software ddevelopment. And In the process of TDD, we frequently come across such situation that one method has to communicate with other classes to realize its function. Therefore, in order to test this method, we have to create the class it is going to communicate with firstly. However, this will deviate from the concept of unit testing. Fortunately, we have some useful tools to handle this kind of situation, such as JMock and EasyMock, which can mock the objects the method interact with, so that we don’t need to crate a real object to finish the testing for that method.

10_16_3_2007.jpg

        Today, I am going to show an example of the use of JMock. Firstly, you need to download JMock and JUnit. Do not use the latesting version (junit 4.4) of JUnit. In this example, I use JUnit 4.3.1 and JMock 2.2. Then add the following packages into your classpath: junit-4.3.1.jar, jmock-2.2.-.jar, jmock-junit4-2.2.0.jar, hamcrest-core-1.1.jar and hamcrest-library-1.1.jar.
        I am going to create a small application which can say different greetings to the client according to different time. For example, it outputs “Good morning, ***” in the morning, and outputs “Good evening, ***” in the evening. According to the procedure of TDD, we firstly create a test case.

//import some necessary classes from the package of JUnit4
import org.junit.Test;
import static org.junit.Assert.asserEquals;

public class TestJMockCase{

   @Test
   public void testSayGreeting(){
         Greeting o = new Greeting();
         String out = o.SayGreeting(“wu cao”);
         assertEquals(“Good afternoon, wu cao”, out);
   } 
}

        Because we haven’t created the class of Greeting, we will fail in compiling this test case. In order to make it through compilation, we need to code the Greeting class. And we find the Greeting class have to communicate with the other class named GreetingTime to get the the words of greeting.

public class Greeting{
        //we have to define GreetingTime as an interface
        //I am goint to explain it in the later
        private GreetingTime gt;
        public void setGreetingTime(){
               this.gt = gt;
        }

        public String sayHello(){
               String greeting = gt.getGreeting();
               return greeting+”, “+name;  
        }

        In order to compile successfully, we also need to create the class of GreetingTime. But now, our focus is not on the GreetingTime class, so we decide to use mock object.

public interface GreetingTime{
        public String getGreeting();
}

       Because we are going to mock the GreetingTime class, we have to define it as an interface, which is a prerequisite for the mock object. Therefore, we have to use the setter method to inject the instance of GreetingTime to Greeting, (we cannot use the new keyword on an interface).

       Then, we have to make some changes to the test class we created before, because we are going to mock the GreetingTime.

//import some necessary classes from the package of JUnit4
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
//import some necessary classes from the package of JMock2.2
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.Expectations;
@RunWith(JMock.class)
public class TestJMockCaseUsingJMock{
        //create the context for the mock object
        Mockery context = new JUnit4Mockery();

        @Test
         public void testSayHello()
        {
             //Mock the GreetingTime class using the technology of reflection
             //you have to define it as a final variable
             //since it is going to be used in a inner class
             final GreetingTime gt = context.mock(GreetingTime.class);
             Greeting g = new Greeting();
              g.setGreetingTime(gt);

             //set the expection for the mock object
             context.checking(new Expectations(){{
                   //the mock object will call the getGreeting method once
                  //and we assume that is returns “Good afternoon”
                  one(gt).getGreeting(); will(returnValue(“Good afternoon”));
              }});

             String out = g.sayHello(“wu cao”);
             //compare the result and expected value
             assertEquals(“Good afternoon, wu cao”,out);
         }
}

Now, you can open the command widnow to test.

10_16_2_2007.jpg

10_16_1_2007.jpg

October 13, 2007

DAO pattern for Hibernate!

Filed under: Programming — by powerdream5 @ 3:20 am
Tags: , ,

        In J2EE field, open source framework is pretty hot. One of the advantages of them is that they are non-intrusive, because  you don’t need to make your classes extend any classes or implement any interfaces from the framework. However, when we use the ORM framework, such as Hibernate or JDO, we still need to use some specific classes of them. Therefore, in order to make the application more extensible, we should encapsulate the persistence layer of the system.

        DAO(data access object) pattern has already been proved to be a good way to seprate the business logic layer and the persistent layer. Today, I want to show an example of applying DAO pattern to Hibernate.

       Usually, a typical DAO pattern contains a factory class, some DAO interfaces and some DAO classes which implement those interface. Now, Let’s take a blog system for an example. Because I just want to show the structure, I will not present the detail of each class.

10_11_1_2007.gif

      Firstly, we define the factory class:

public class DAOFactory{
        private static DAOFactory daoFactory;
        static{
               daoFactory = new DAOFactory();
        }
        //Define the factory method, return the instance of specific classes
        public DAOFactory getInstance(){
               return daoFactory;
        }
        public BlogDAO getBlogDAO(){
               return new BlogDAOImpl();
        }
         public BlogDAO getCommentDAO(){
               return new CommentDAOImpl();
        }
}

       Secondly, we define the DAO interfaces. The purpose of interfaces is to make our applicaiton more extensible. For example, if we want to change the hibernate framework to the JDO framework in the future, we don’t need to make any change to the business logic, just changing the implementation of the interface works well.

//Data access object interface 
public interface BlogDAO{
      //Blog are an persistence class
      //define the method for inserting a blog to the system
      public boolean insertBlog(Blog blog);
     //define the method to read a blog from the system according the id
          public Blog readBlog(Long blogId);
}

      Then, make an implementation to this interface:

//Data access object 
public class BlogDAOImpl implements BlogDAO{
      public boolean insertBlog(Blog blog){
             Session session = HibernateUtil.getSession();
             ….
      }
     public Blog readBlog(Long blogId){
             Session session = HibernateUtil.getSession();
             …. 
      }
}

//HibernateUtil is a help class
public class HibernateUtil{
        private static SessionFactory sessionFactory;
        static{
                sessionFactory = ….;
         }
        public static Session getSession(){
               return sessionFactory.openSession();
        }
}

      Now, we can create a class for testing:
public class Test{
     public static void main(String[] args){
             //insert a blog to the database
            //assume that we already get an instance of Blog class named blog

            BlogDAO blogDAO = DAOFactory.getInstance().getBlogDAO();
            blogDAO.inserBlog(blog);
     }
}

      However, there are still some drawbacks of DAO pattern. For example, we always have to get an instance of Session at the beginning of each method of the class BlogDAOImpl, which make us write the same code. Fortunately, we can make some advances to this program, for instance, we can adopt spring framework for configuring the relationship between each class.

10_11_1_3.jpeg

October 11, 2007

Ajax, IE and Firefox!

Filed under: Programming — by powerdream5 @ 1:42 am
Tags: , , ,

       As a web programmer, I believe that you must have complained the differences between IE and firefox. Sometimes, the web you designed looks perfect in one web browser, but looks ugly in other browsers. Furthermore, because IE and Firefox parse javascript in different ways, when we use the technology of ajax, sometimes, we have to program for IE and firefox separately.
      Today, I am going to show an example of using javascript to parse XML files in both IE and firefox, so the the application would behave the same in both of the web browsers.

      The interface of the example looks like:

10_1_2007.JPG

        Each time, after selecting a country from the drop list of country, a request will be sent to the server for the xml files. For this example, I prepare two xml files, china.xml and united_state.xml separately. Then, the client will get the response from the server, and it will parse the xml file and display the cities of the coutry in the list under the lable of city.

//china.xml
<?xml version=”1.0″ encoding=”gb2312″?>
<cities>
      <city>Beijing</city>
      <city>Shanghai</city>
      <city>Chengdu</city>
      <city>Wuhan</city>
      <city>Changsha</city>
</cities>

//united_state.xml
<?xml version=”1.0″ encoding=”gb2312″?>
<cities>
      <city>New York</city>
      <city>Sanfrancisco</city>
      <city>Los Angeles</city>
      <city>Philadelphia</city>
      <city>Chicago</city>
      <city>Seattle</city>
      <city>Houston</city>
</cities>

The core javascript code are showed below:

    //create the ajax coonnection
    //for IE

    var req = null;
    if(window.ActiveXObject)
    {
          req = new ActiveXObject(“Microsoft.XMLHTTP”);
    }
    //for Firefox
    else if(window.XMLHttpRequest)
    {
          req = new XMLHttpRequest();
    }
    //define the file requested
    var url = document.form1.country.options[selected].value+”.xml”;
    //define which function to deal with the result of the request
    req.onreadystatechange = getCities;
    //using Post or get method to send the request,we use get method here
    req.open(“GET”,url, true);
    //send request to the server
    //there is a trick, when you don’t want to send any parameters
    //you need to use null, otherwise, there will be some problem in Firefox

       req.send(null);

function getCities(){
   //when the request is complete
   if(req.readyState == 4){
       //check if the request is success
      if(req.status == 200){
            //req.responseText represents the returning text from the server
           var response = req.responseText;
           var xmlDoc;
           var value;
           document.form1.city.options.length = 0;
          //for IE
         if (window.ActiveXObject)
        {
             //crate xml docuemnt object in IE
            xmlDoc=new ActiveXObject(“Microsoft.XMLDOM”);
            xmlDoc.async=”false”;
            xmlDoc.loadXML(response);
            var x = xmlDoc.documentElement;
            //navigate the xml docuemnt object
            //take notice: firstly, we assign 0 to i, then i adds 1 each time

           for (var i=0;i<x.childNodes.length;(i = i+1))
          {
                 value = x.childNodes[i].childNodes[0].nodeValue;
                 //add the city to the list one by one
                 document.form1.city.options[i] = new Option(value,value);
          }    
       }
        //for Firefox
       else
       {
           //create the xml docuemnt object in firefox
           var parser=new DOMParser();
           xmlDoc=parser.parseFromString(response,”text/xml”);
           var x = xmlDoc.documentElement;
           var num = 0;
           //take notice: firstly, we assign 1 to i, then i adds 2 each time
           for (var i=1;i<x.childNodes.length;(i = i+2))
           {
                 value = x.childNodes[i].childNodes[0].nodeValue;
                 //add the city to the list one by one
                 document.form1.city.options[num] = new Option(value,value);
                 num++;
            }   
         }
       }
     }
  }

The html code is listed below:

<form name=”form1″>
     <table width=”300″ border=”0″>
          <tr>
              <td width=”150″ align=”center”>Country</td>
              <td width=”150″ align=”center”>City</td>
          </tr>
          <tr>
              <td valign=”top” align=”center”>
                    <select name=”country” onchange=”getTheCity()”>
                         <option></option>
                         <option value=”china”>China</option>
                         <option value=”united_state”>United State</option>
                    </select>
              </td>
               <td>
                     <select name=”city” size=”10″ style=”width:140px”>
                     </select>
               </td>
          </tr>
     </table>
 </form>

You can see the perfomance of this example through this link

10_2_2007.JPG

October 10, 2007

An introductin to Dom4j!

Filed under: Programming — by powerdream5 @ 12:52 am
Tags:

        SOA(service oriented architecture) is a popular word in the enterprise application field. Service is defined by the messages exchanged among services. Up to now, most people admit that using web services to connect different parts of the application or different applications and using xml files to define the format of the messages are the best practices.
        Therefore, XML plays a significant role in building SOA. How to parse xml files will be one of the core problems we need to consider. Today, I want to make an introduction to Dom4j, an open source framework for handling xml files on the Java platform. At the front beginning, you need to download Dom4j, and add the dom4j.jar package into your classpath.

        Now, I presume there is a xml file(books.xml), as the following shows:
<?xml version=”1.0″ encoding=”gb2312″?>
<books>
      <book>
           <title category=”J2EE”>Enterprise Application Architecture</title>
           <author>Martin Flower</author>
      </book>
      <book>
           <title category=”Software Engineering”>Domain Driven Design</title>
           <author>Eric Evans</author>
      </book>
</books>

       The progrm used to parse this xml file(TestDom4j.java) is:

import java.io.File;
import java.util.Iterator;

//import the class from the dom4j.jar package
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.Element;
import org.dom4j.Attribute;
import org.dom4j.tree.DefaultElement;

public class TestDom4j{

     public Document parse(File file) throws DocumentException{
           //create document object for the xml file, then we can navigate the document object
           SAXReader reader = new SAXReader();
           Document document = reader.read(file);
           return document;
 }

 public void display(Element root) throws DocumentException{
        //using Iterator to output each child of the root element
        for(Iterator i=root.elementIterator();i.hasNext();){

               Element element = (Element)i.next();
               System.out.println(“\t<“+element.getName()+”>”);
              
//List all the children of a element, and change the list into an array
               List children = element.elements();
               Object[] child = children.toArray();
               for(int k=0; k<child.length;k++)
             {
                    DefaultElement de= (DefaultElement)child[k];
                    System.out.print(“\t\t<“+de.getName());
                    //get the attribute of category of a child

                    Attribute category = de.attribute(“category”);
                   // if a child has the attribute of category, print it out

                   if(category != null)
                   {
                          System.out.print(” category=\””+category.getValue()+”\”>”);
                    }else{
                          System.out.print(“>”);
                    }
                    System.out.print(de.getText());
                    System.out.println(“</”+de.getName()+”>”);
               }
               System.out.println(“\t</”+element.getName()+”>”);
       }
 }

       public static void main(String[] args) throws Exception {
              File file = new File(“books.xml”);
              TestDom4j t = new TestDom4j();

              //get the document object of the xml file
              Document document = t.parse(file);
             //get the root element of the xml file, and print it out
              Element element = document.getRootElement();
              System.out.println(“<“+element.getName()+”>”);
             //Beginning from the root element, naviagte the xml file
              t.display(element);
              System.out.println(“</”+element.getName()+”>”);
       }
}

The running result of this program is:

9_1_2007.JPG

         After reading the example, I hope you can have some basic ideas of using Dom4j. By the way, the example just demonstrates one way of handling xml files by dom4j. There are still a lot of other ways of using dom4j to parse xml files. You can refer to the official website of dom4j for more informaiton.

        At last, I have to say, to be honest, I don’t like parsing the xml files, because I have to make a specific program to parse a specific xml file each time, and this program cannot parse any other xml files. Therefore, I prefer to database to stroing data, However, sometimes, xml is our only choice.

9_2_2007.jpg

October 8, 2007

Applying Java reflection to Ioc and AOP (2)

Filed under: Programming — by powerdream5 @ 3:30 am
Tags: , , ,

        Today, let’s continue the example of applying java reflection to AOP(Aspect-oriented programming). Because the core of AOP is proxy, I want to make a brief description of it firstly.
        The two important tasks of proxy are interface implementation and delegation. Interface implementation means the proxy class need to implement all the interfaces the target class implements, and delegation means the proxy will catch all the calls to the target class, so that it is easy to add functions before or after the target methods.

blog.JPG

           java.lang.reflect.Proxy helps us create a proxy of the target class dynamically, and java.lang.reflect.InvocationHandler interface will allow the proxy class delegate the calls to the target class.
          The following example shows how to use proxy to realize the function of logging. By extracting the function of logging from the method, we can concentrate our method in business logic.

//TargetInterface.java
//Define the interface the target class implements

public interface TargetInterface{
     public void print();
}

//TargetImplementation.java
//The class implements the interface

public class TargetImplementation implements TargetInterface{
    public void print(){
          System.out.println(“print method”);
    }
}

//ProxyTarget.java
//Create the proxy class and delegate the calls to the target class

import java.lang.reflect.*;
public class ProxyTarget implements InvocationHandler{
      public static Object createProxy(Object obj){
            //creat the proxy class according the instance of the target class                 
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                                                                           obj.getClass().getInterfaces(),
                                                                           new ProxyTarget(obj));
       }

        private Object target;
        private ProxyTarget(Object target)
        {
                this.target = target;
         }
 
        //Implements the method of InvocationHandler interface
        //This method will catch all the calls to the target class
        //and redispatch them       

        public Object invoke(Object proxy, Method method, Object[] args)
        {
                 Object result = null;
                 try{
                        //add function before redispatching
                        System.out.println(“Before “+method.getName());
                        //redispatch the call
                        result = method.invoke(target,args);
                        //add function after redispatching
                        System.out.println(“After “+method.getName());
                 }catch(Exception e){
                        System.out.println(e.getMessage());
                 }
                 return result;
          }
}

//TestProxyTarget.java
//the test class

public class TestProxyTarget{
        public static void main(String[] args){
                 TargetInterface t = (TargetInterface)ProxyTarget.createProxy(
                                                                                   new TargetImplementation());
                 //this will call the invoke method of the ProxyTarget class automatically and transparently 
                 t.print();
        }
}

The running result of the TestProxyTarget is:

blogcmd.JPG

         After reading the examples, I hope you can have some basic ideas of Ioc and Aop, and figure out the relationship between java reflection and Ioc and AOP. Of course, if you want to learn more, please search more materials about them.

xiaoran.jpg

 

October 7, 2007

Applying Java reflection to Ioc and AOP (1)

Filed under: Programming — by powerdream5 @ 1:10 am
Tags: , ,

reflection

         JDK1.5 has introduced many useful features, including annotation and reflection. And now, IOC(Inversion of Control) and AOP(Aspect-oriented programming) would be the most popular words in the J2EE field. Today, I am not going to explain what is IOC and what is AOP. I just want to show two examples to present the technology of java reflection plays an important role in IOC and AOP.

        The first example would be a little bit different from the the concept of IOC, but the common thing is that both load the calss dynamically. In this example, I use properties file as the configuration file, but in a real application, we mostly use xml files.

//InjectionInterface.java 
//Firstly, we define a interface

public interface InjectionInterface{
       public void print();
}

//InjectionClass_1.java
//implements the InjectionInterface
public class InjectionClass_1 implements InjectionInterface{
       public void print(){
               //print out the name of the class the object belongs to
               System.out.println(“the print method of class InjectionClass_1”);
       }
}

//InjectionClass_2java
//implements the InjectionInterface

public class InjectionClass_2 implements InjectionInterface{
      public void print(){
              //print out the name of the class the object belongs to
              System.out.println(“the print method of class InjectionClass_2”);
     }
}

//Ioc.java-the testing class 
import java.util.Properties;
import java.io.*;

public class Ioc{
      private InjectionInterface injectionClass;

      //using setter injection
     public void setInjectionClass(InjectionInterface injectionClass)
    {
            this.injectionClass = injectionClass;
    } 

    public void print()
   {
            injectionClass.print();
    }

    public static void main(String[] args)
   {
            try{
                  Properties props = new Properties();
                  props.load(new FileInputStream(“injection.properties”));
                  String classname = props.getProperty(“iocclass”);
                 //dynamically load the class according to the class name
                  Class cls = Class.forName(classname);
                  Ioc ioc = new Ioc();
                 //get an instance of the loaded class
                  ioc.setInjectionClass((InjectionInterface)cls.newInstance());
                  ioc.print();
            }catch(Exception e){
                    e.printStackTrace();
            }
        }
}

//injection.properties – the properties file
iocclass=InjectionClass_1

The running result of the program is: the print method of class InjectionClass_1

Now, you can change the properties file: iocclass=InjectionClass_2. you don’t need to compile the java files again, and just run the class directly. you can see the result would be different.

ioc.JPG

        After reading the example, I hope you have a better understanding of IOC. And tomorrow, I will show the example about using the technology of reflection in AOP.

Create a free website or blog at WordPress.com.