Regression Testing with SOAPUI

In Web Services development, it is very helpful to consistently test your application and ensure that the functionalities and features which already work can easily be checked in one click of a button. This was how Eviware’s SOAPUI tool helped me automate my web service regression testing.

Initially, I was just defining separate web service calls and running them manually in SOAPUI. However, exploring SOAPUI features made me realize how powerful this tool is. By creating a SOAPUI test case, I am able to create a series of web service calls interconnected to each other by passing values from one web service response to another web service request . A placeholder for values can be used – called Properties. The values from placeholder can change by using a PropertyTransfer. The PropertyTransfer is a mechanism/process which automatically transfers values from an XML response to a property. Accessing the XML responses can be achieved by using XPath. These are all represented in a series of Steps which can be defined within a SOAPUI Test Case.

This flexibilty of simulating a sequence of  Web Service calls dynamically can actually help in making sure a particular Use-Case can be tested and regression-tested. If ever a merge activity or some refactoring is done, having an automated regression test of your Web Service can be really useful in making sure your code is still stable.

A more powerful area I have not explored is to use a Groovy Script to process the XML request/responses or massage data. This will be discussed further in my next blog posts.

Posted in Best Practices | Tagged , , , | 2 Comments

Deep Copying Objects in Java

I wrote a simple code which others may find useful in their projects for making a deep copy of an object or a List of objects.

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class SerializationUtil {

    public static <T> Object clone(T oldObject) throws Exception {

        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        T newObject = null;

        if (!(oldObject instanceof Serializable)){
            throw new NotSerializableException(oldObject.getClass().getName());
        }
        try
        {
           // Convert oldObject into ObjectOutputStream
           ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
           outputStream = new ObjectOutputStream(byteArrayOS);
           outputStream.writeObject(oldObject);
           outputStream.flush();

           // Convert ObjectOutputStream byte array into inputStream
           ByteArrayInputStream bin = new ByteArrayInputStream(byteArrayOS.toByteArray());
           inputStream = new ObjectInputStream(bin);

           newObject  = (T) inputStream.readObject();
        }
        finally
        {
           if (outputStream != null)
               outputStream.close();
           if (inputStream!= null)
            inputStream.close();
        }

        return newObject;
    }

    /**
     * Creates a deep copy of a List
     * @param list
     * @param <T>
     * @return  a new copy of the list
     * @throws Exception
     */
    public static <T> List<T> deepCopy(List<T> list) throws Exception {
        List<T> newList = new ArrayList<T>();
        if (list != null ){
            for (T object : list) {
                newList.add((T) clone(object));
            }
        }
        return newList;
    }
}
Posted in Useful Tips in Java | Tagged , , , | Leave a comment

Chain of Responsibility Pattern

One of the interesting pattern I have used recently is the Chain of Responsibility pattern. It is defined in Wikipedia as :

a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains a set of logic that describes the types of command objects that it can handle, and how to pass off those that it cannot to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.

I had a chance to apply this pattern when I developed a Java application acting as a web service client which simulates calls to a series of Web Services in certain predefined sequences. Each processor in the series represents processing a Web Service request call. If there is a dependency between two or more Web Services, objects are passed in between processors.

The implementations of Processor interface can be chained together using the setNext() method. To make it more flexible to change the sequencing of process execution, the order can be configured via an XML configuration file where the class implementations can be loaded and chained.

An open source implementation of this pattern is Apache Commons Chain. A case study of this pattern will be shown in later blog posts.

What I find interesting in implementing this pattern is how it can make the design and coding more modular and makes it possible to have the business components loosely coupled by separating the business process execution into a series of ‘processors’ in a chain. If a certain business logic is introduced somewhere between the process chain, it can easily be configured as a separate class containing the business process.

Posted in Design Patterns | Leave a comment

Twitter

I have not been really using Twitter since I signed up for an account last January 2009. Since that CNN vs Ashton Kutcher race to 1 Million followers came up, I started to realize how powerful this social networking application is. It is still a very young product and could open up a lot of potential for client applications. TwitDeck and Seesmic have been providing good RIA apps written in Adobe Air.

For the weeks to come, I will start to study the Twitter API documentation and play around with it using Google App Engine as my Java hosting service. I will start posting my experiments on this blog.

Posted in Uncategorized | Leave a comment

Google App Engine For Java

Once the news of Google’s release of their App Engine for Java got out (while reading twitters from Google), I signed up for the freebie Java hosting. I thought I was not going make it to their first 10,000 users. I’m glad I did not hesitate to sign up and was able to make on time.

After installing Eclipse 3.4 and plugins for GWT 1.6 and App Engine, the deployment of a simple GWT/Web application was seamless. It was as if I deployed my application in my own computer running Tomcat.

This is just my initial post about this topic and would be adding more information about how a full blown application can be developed using Google’s APIs with support for Java Servlet API, JDO and JPA, javax.cache, and javax.mail.

Posted in Uncategorized | 4 Comments

Filtering Lists

In some instances, there would be some need to process a List of objects which may come from different data sources. This List may also undergo some business logic where business rules are applied to weed out certain objects which does not apply to a particular scenario. The output filtered list of the first process may be an input to another process which may need a new set of rules for weeding out more objects from the list.

One elegant way of tackling this issue code-wise, is to create a FilterCriteria interface:

public interface FilterCriteria<Template>{
    public boolean isAccepted(Template object);
}

We also need to create a static method to achieve the actual filtering – let’s create CollectionsUtil class with filter() method :

import java.util.List;
import java.util.Iterator;

public class CollectionsUtil {

    public static <Template> void filter(List<Template> list, FilterCriteria<? super Template> filterCriteria){
        Iterator<Template> iterator = list.iterator();
        while (iterator.hasNext()){
            if (!filterCriteria.isAccepted(iterator.next()))
                iterator.remove();
        }
    }
}

If we apply this concept to filter our playerList from our example in the arcticle using “Using Comparable and Comparator Interfaces” , we may need to filter our list by implementing FilterCriteria with the following code:

public class MyFilter implements FilterCriteria<Player>{

    public boolean isAccepted(Player player) {
        return player.getPointAverage() > 28;
    }
}

This code filters all the Player objects which has a point average less than or equal than 28.  Finally, the code will look something like this :

        FilterCriteria myFilter = new MyFilter();
        CollectionsUtil.filter(playerList, myFilter);
        for (IPerson person : playerList){
            System.out.println(person);
        }

The output based on our examples would be the following:

Jordan, Michael 32.4
Bryant, Kobe 29.2
James, Lebron 28.3

Observe the striking similarities with our approach and how Collections.sort()  and  Comparator interfaces work. Once again, applying this technique decouples the List processing from the business rule(s) which need to be applied to the List. It also provides programmatic flexibility when applying a particular FilterCriteria in your Lists.

Posted in Coding Techniques | Tagged , | Leave a comment

Using Comparable and Comparator Interfaces

Sorting objects  is commonly used especially in the presentation layer of an enterprise application.  Developers unfamiliar with the Collections Framework API would write their own sorting algorithm unaware of the availability of Comparable and Comparator interfaces to satisfy their needs.

The Comparable interface is used if you need to implement a default sorting behavior of the object you need sorted. Let’s have the following class as an example :

public class Player{
    private final String lastName;
    private final String firstName;
    private final Float pointAverage;

    public Player(String lastName, String firstName, Float pointAverage) {
        this.lastName = lastName;
        this.firstName = firstName;
        this.pointAverage = pointAverage;
    }

    public String getLastName() {
        return lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public Float getPointAverage() {
        return pointAverage;
    }
    @Override
    public String toString() {
        return lastName + ", " + firstName + " " + pointAverage;
    }
}

Let’s create a List of Player objects :

        List<Player> playerList = new ArrayList<Player>();
        playerList.add(new Player("Jordan", "Michael", 32.4f));
        playerList.add(new Player("James", "Lebron", 28.3f));
        playerList.add(new Player("Bryant", "Kobe", 29.2f));
        playerList.add(new Player("Paul", "Chris", 26.2f));

To be able to sort playerList by last name, we can modify Player class to implement the compareTo() method of the Comparable interface :

public class Player implements Comparable<Player> {
    private final String lastName;
    private final String firstName;
    private final Float pointAverage;

    public Player(String lastName, String firstName, Float pointAverage) {
        this.lastName = lastName;
        this.firstName = firstName;
        this.pointAverage = pointAverage;
    }

    public String getLastName() {
        return lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public Float getPointAverage() {
        return pointAverage;
    }
    @Override
    public String toString() {
        return lastName + ", " + firstName + " " + pointAverage;
    }

    public int compareTo(Player player) {
        return this.getLastName().compareTo(player.getLastName());
    }
}

We can now do the following :

        Collections.sort(playerList);
        for (IPerson person : playerList){
            System.out.println(person);
        }

An the output is

Bryant, Kobe 29.2
James, Lebron 28.3
Jordan, Michael 32.4
Paul, Chris 26.2

As you can see, using the Comparable interface can only be used as a default sorting technique. Most of the time, you may need to sort a certain List of records by their field values. This where the Comparator interface comes very useful where you have to implement the compare() method:

import java.util.Comparator;

public class PlayerComparator implements Comparator<Player> {

    public enum SortType {
        ASCENDING, DESCENDING
    }

    public enum SortField {
        LAST_NAME,
        FIRST_NAME,
        POINT_AVERAGE
    }
    private final SortType sortType;
    private final SortField sortField;

    public PlayerComparator(SortType sortType, SortField sortField) {
        this.sortType = sortType;
        this.sortField = sortField;
    }

    public int compare(Player person1, Player person2) {
        int compare = 0;

        switch (sortType){
            case ASCENDING:
                compare = handleSortField(person1, person2, compare);
                break;
            case DESCENDING:
                compare = handleSortField(person2, person1, compare);
        }
        return compare;
    }

    private int handleSortField(Player person1, Player person2, int compare) {
        switch (sortField){
            case LAST_NAME :
                compare = person1.getLastName().compareTo(person2.getLastName());
                break;
            case FIRST_NAME :
                compare = person1.getFirstName().compareTo(person2.getFirstName());
                break;
            case POINT_AVERAGE:
                compare = person1.getPointAverage().compareTo(person2.getPointAverage());
        }
        return compare;
    }
}

Now, should have more flexibility in our code to sort the list:

        Collections.sort(playerList, new PlayerComparator(PlayerComparator.SortType.DESCENDING,
                                                          PlayerComparator.SortField.POINT_AVERAGE));
        for (IPerson person : playerList){
            System.out.println(person);
        }

And now, we get the following output:

Jordan, Michael 32.4
Bryant, Kobe 29.2
James, Lebron 28.3
Paul, Chris 26.2

As you can see, understanding how Comparable and Comparator interfaces can sort your List can save you a lot of coding your own sort algorithms.

Posted in Best Practices, Coding Techniques | Tagged , , , , | Leave a comment