Calculate Timings using Commons Lang StopWatch

You need to calculate timings of your code execution so you know how long a particular method or some block in your code take to finish it execution. Basically you can do this by capturing the start time and the end time using System.currentTimeMillis() and find the different. Another way to do it is to use the StopWatch class from Apache Commons Lang library. The StopWatch class can be found in the org.apache.commons.lang.time package.

The simplest steps to use the StopWatch is to create an instance of the StopWatch class, start the stopwatch by calling the start() method. After the stopwatch is started you can execute the target method or block of code you want to watch and call the stop() method to complete the timing session. To get the time of the stopwatch you can call the getTime() method.

Now, let’s see the code for the process described above.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.time.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        demo.timingOne();
    }

    private void timingOne() {
        // Create an instance of StopWatch.
        StopWatch stopWatch = new StopWatch();

        // Start the watch, do some task and stop the watch.
        stopWatch.start();
        doSomeTask(5000);
        stopWatch.stop();

        // Print out the total time of the watch
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Here is the output of the code above:

Time: 5000

Beside doing a simple timing calculation using the start() and stop() followed by the getTime() methods, the StopWatch class also provides methods for splitting the time, suspend and resuming the stopwatch. You can use the split(), suspend() and resume() method respectively. To get the split time you can call the toSplitString() method.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.time.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        demo.timingTwo();
    }    

    private void timingTwo() {
        // Create an instance of StopWatch and start the stopwatch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Do some task and split the stopwatch time.
        doSomeTask(3000);
        stopWatch.split();
        System.out.println("Split 1: " + stopWatch.toSplitString());

        // Suspend the stopwatch and resume the stopwatch.
        stopWatch.suspend();
        doSomeTask(4000);
        stopWatch.resume();

        // Do some task and split the stopwatch time.
        doSomeTask(2500);
        stopWatch.split();
        System.out.println("Split 2: " + stopWatch.toSplitString());

        // Do some task and split the stopwatch time.
        doSomeTask(1000);
        stopWatch.split();
        System.out.println("Split 3: " + stopWatch.toSplitString());

        // Stop the stopwatch and the the total execution time.
        stopWatch.stop();
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above will output something like this:

Split 1: 0:00:03.000
Split 2: 0:00:05.525
Split 3: 0:00:06.525
Time: 6525

Another method that you can find in the StopWatch class is the getStartTime() which will return the stopwatch start time. The reset() method will reset the stopwatch. To remove a split you can call the unsplit() method.

How to implement the hashCode and equals method using Apache Commons?

This code snippet show you how to use HashCodeBuilder and EqualsBuilder class from the Apache  Commons Lang library to implement the hashCode() and equals() method of an object. To use both of these classes we just need to create instance of these class and append the properties that we will use the calculate the hashcode and to test for equality.

Implementing the hashCode() method first by creating the hashCode() method. Add the @Override annotation to make sure that we’ve override the correct method. Then we create an instance of HashCodeBuilder. Append the fields we’re gonna use to calculate the hashcode. The final result of the actual hashcode can be obtained by calling the toHashCode() from the instance of HashCodeBuilder.

/**
 * Implement the hashCode method using HashCodeBuilder.
 */
@Override
public int hashCode() {
    return new HashCodeBuilder().append(id).append(name).toHashCode();
}

We do the same to create the equals() method. First create the method, it takes a single argument type of java.lang.Object. Add the @Override annotation to make sure we override the correct method. On the first line you can check to see if the passed object is an instance of the same object, we use the instanceof operator. We then compare the values stored in both object using the EqualsBuilder class. To get the equality result you must remember to call the isEquals() method.

/**
 * Implement the equals method using the EqualsBuilder.
 */
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof DummyUser)) {
        return false;
    }
    DummyUser that = (DummyUser) obj;
    return new EqualsBuilder().append(this.id, that.id)
            .append(this.name, that.name).isEquals();
}

Here the complete look of the snippet.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class DummyUser {
    private Long id;
    private String name;

    /**
     * Constructor to create an instance of this class.
     */
    public DummyUser() {
    }

    public static void main(String[] args) {
        DummyUser user1 = new DummyUser();
        user1.setId(10L);
        user1.setName("Carol");

        DummyUser user2 = new DummyUser();
        user2.setId(10L);
        user2.setName("Carol");

        System.out.println("user1.hashCode() = " + user1.hashCode());
        System.out.println("user2.hashCode() = " + user2.hashCode());

        System.out.println("user1.equals(user2) = " + user1.equals(user2));
    }

    //
    // Getters & Setters
    //
    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * Implement the hashCode method using HashCodeBuilder.
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(id).append(name).toHashCode();
    }

    /**
     * Implement the equals method using the EqualsBuilder.
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DummyUser)) {
            return false;
        }
        DummyUser that = (DummyUser) obj;
        return new EqualsBuilder().append(this.id, that.id)
                .append(this.name, that.name).isEquals();
    }
}

The result of our code are:

user1.hashCode() = 64902380
user2.hashCode() = 64902380
user1.equals(user2) = true

How do I create a database connection pool?

This example show you how to create a connection pool implementation using the Apache Commons DBCP library.

package org.kodejava.example.commons.dbcp;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ConnectionPoolExample {
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost/kodejava";
    public static final String USERNAME = "kodejava";
    public static final String PASSWORD = "kodejava123";

    private GenericObjectPool connectionPool = null;

    public DataSource setUp() throws Exception {
        // Load JDBC Driver class.
        Class.forName(ConnectionPoolExample.DRIVER).newInstance();

        // Creates an instance of GenericObjectPool that holds our
        // pool of connections object.
        connectionPool = new GenericObjectPool();
        connectionPool.setMaxActive(10);

        // Creates a connection factory object which will be use by
        // the pool to create the connection object. We passes the
        // JDBC url info, username and password.
        ConnectionFactory cf = new DriverManagerConnectionFactory(
                ConnectionPoolExample.URL,
                ConnectionPoolExample.USERNAME,
                ConnectionPoolExample.PASSWORD);

        // Creates a PoolableConnectionFactory that will wraps the
        // connection object created by the ConnectionFactory to add
        // object pooling functionality.
        PoolableConnectionFactory pcf =
                new PoolableConnectionFactory(cf, connectionPool,
                        null, null, false, true);
        return new PoolingDataSource(connectionPool);
    }

    public GenericObjectPool getConnectionPool() {
        return connectionPool;
    }

    public static void main(String[] args) throws Exception {
        ConnectionPoolExample demo = new ConnectionPoolExample();
        DataSource dataSource = demo.setUp();
        demo.printStatus();

        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = dataSource.getConnection();
            demo.printStatus();

            stmt = conn.prepareStatement("SELECT * FROM m_users");
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                System.out.println("Username: " + rs.getString("username"));
            }
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        }

        demo.printStatus();
    }

    /**
     * Prints connection pool status.
     */
    private void printStatus() {
        System.out.println("Max   : " + getConnectionPool().getMaxActive() + "; " +
                "Active: " + getConnectionPool().getNumActive() + "; " +
                "Idle  : " + getConnectionPool().getNumIdle());
    }
}

The code show the following status as output example:

Max   : 10; Active: 0; Idle  : 0
Max   : 10; Active: 1; Idle  : 0
Username: wsaryada
Username: jdoe
Max   : 10; Active: 0; Idle  : 1

How do I create a BasicDataSource object?

This example demonstrates how to use the BasicDataSource class of Apache Commons DBCP to create a basic requirements for database connection. The configuration of the data source can be defined using some properties method provided by this class. The basic properties is the driver classname, connection url, username and password.

After the datasource ready we can obtain a connection by calling the getConnection() method of the datasource. This method might throw an SQLException when errors occurs.

package org.kodejava.example.commons.dbcp;

import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BasicDataSourceExample {
    public static void main(String[] args) throws Exception {
        // Creates a BasicDataSource and defines its properties
        // including the driver class name, jdbc url, username
        // and password.
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost/kodejava");
        dataSource.setUsername("kodejava");
        dataSource.setPassword("kodejava123");

        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            //
            // Get a connection from the data source and do some
            // database query with the obtained connection.
            //
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement("SELECT * FROM m_users");
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                System.out.println("Username: " + rs.getString("username"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
    }
}

We can simplify the code above so that we don’t have to close the PreparedStatement and Connection manually like we did in the finally block in the code snippet. We can use try-with-resources to automatically close resources. An example can be seen in the following example: How to automatically close resources in JDBC?.

How do I set mapped property value of a bean?

This example demonstrate how to use PropertyUtils.setMappedProperty() method to modify a Map typed property value of a bean. To set the property we need to pass bean instance, property name, map key and map value to PropertyUtils.setMappedProperty() method.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

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

public class PropertySetMappedExample {

    public static void main(String[] args) {
        //
        // Create an instance of Recording bean.
        //
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("Introduction");

        //
        // Create a map to hold recording tracks.
        //
        Map tracks = new HashMap<>();
        tracks.put("track-one", new Track());
        tracks.put("track-two", new Track());
        tracks.put("track-three", new Track());
        recording.setMapTracks(tracks);

        try {
            //
            // We add another tracks to the recording track using
            // a PropertyUtils.setMappedProperty() method.
            //
            PropertyUtils.setMappedProperty(recording, "mapTracks", "track-four", new Track());
            PropertyUtils.setMappedProperty(recording, "mapTracks", "track-five", new Track());
        } catch (Exception e) {
            e.printStackTrace();
        }

        tracks = recording.getMapTracks();
        System.out.println("New Track Numbers: " + tracks.size());
        for (String key : tracks.keySet()) {
            System.out.println(key + " = " + tracks.get(key));
        }
    }
}

How do I set indexed property value of a bean?

In this example we display how to set the value of an indexed property. In the code below we modified the value of an array type. We’ll change the second colors of MyBean‘s colors property.

We do it in the same way as using the PropertyUtils.setSimpleProperty method. For indexed property we use the PropertyUtils.setIndexedProperty method and passes four arguments, they are the instance of bean to be manipulated, the indexed property name, the index to be changes and the finally the new value.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

import java.util.Arrays;

public class PropertySetIndexedExample {
    public static void main(String[] args) {
        String[] colors = new String[]{"red", "green", "blue"};

        MyBean myBean = new MyBean();
        myBean.setColors(colors);
        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));

        try {
            PropertyUtils.setIndexedProperty(myBean, "colors", 1, "orange");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));
    }
}
package org.kodejava.example.commons.beanutils;

public class MyBean {
    private String[] colors;

    public void setColors(String[] colors) {
        this.colors = colors;
    }

    public String[] getColors() {
        return colors;
    }
}

The output of this code is:

Colors = [red, green, blue]
Colors = [red, orange, blue]

How do I set property value of a bean?

The Commons BeanUtils component provides a class called PropertyUtils that supplies method for manipulating a bean such as our Track class below. For this demo we use a Track class that have a property called id, title and duration.

To set the value of a bean we can use the PropertyUtils.setProperty() method. This method ask for the bean instance whose property value to be set, the property name and the value.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

public class PropertySetExample {
    public static void main(String[] args) {
        Track track = new Track();
        try {
            PropertyUtils.setProperty(track, "id", 10L);
            PropertyUtils.setProperty(track, "title", "Hey Jude");
            PropertyUtils.setProperty(track, "duration", 180);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Track = " + track);
    }
}

Some exceptions could be thrown by this method, so we need to handle the IllegalAccessException, InvocationAccessException and NoSuchMethodException. To make the code simple we will just catch it as java.lang.Exception.

These exception could happen if we don’t have access to the property, or the bean’s accessor throws an exception or if the method we tried to manipulate doesn’t exist.

How do I connect to FTP server?

The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files between a client and server on a computer network. The example below shows you how to connect to a FTP server.

In this example we are using the FTPClient class of the Apache Commons Net library. To connect to the server we need to provide the FTP server name. Login to the server can be done by calling the login() method of this class with a valid username and password. To logout we call the logout() method.

Let’s try the code snippet below:

package org.kodejava.example.commons.net;

import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;

public class FtpConnectDemo {
    public static void main(String[] args) {
        FTPClient client = new FTPClient();

        try {
            client.connect("ftp.example.org");

            // When login success the login method returns true.
            boolean login = client.login("admin", "admin123**");
            if (login) {
                System.out.println("Login success...");

                // When logout success the logout method returns true.
                boolean logout = client.logout();
                if (logout) {
                    System.out.println("Logout from FTP server...");
                }
            } else {
                System.out.println("Login fail...");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Closes the connection to the FTP server
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.4</version>
</dependency>

How do I read mapped bean’s property value?

In this example you’ll see how to read mapped property value of a bean. We use PropertyUtils.getMappedProperty() method the read the mapped property of the Recording object that consist of Track objects.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

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

public class ReadMapProperty {
    public static void main(String[] args) {
        Recording recording = new Recording();
        recording.setTitle("Please Please Me");

        Track track1 = new Track();
        track1.setTitle("I Saw Her Standing There");

        Track track2 = new Track();
        track2.setTitle("Misery");

        Map tracks = new HashMap<>();
        tracks.put("Track One", track1);
        tracks.put("Track Two", track2);

        recording.setMapTracks(tracks);

        try {
            Track track = (Track) PropertyUtils.getMappedProperty(recording, "mapTracks(Track One)");
            System.out.println("track.getTitle() = " + track.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.example.commons.beanutils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Recording {
    private Long id;
    private String title;
    private List tracks = new ArrayList<>();
    private Map mapTracks = new HashMap<>();

    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

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

    public List getTracks() {
        return tracks;
    }

    public void setTracks(List tracks) {
        this.tracks = tracks;
    }

    public void setMapTracks(Map mapTracks) {
        this.mapTracks = mapTracks;
    }

    public Map getMapTracks() {
        return mapTracks;
    }
}

And here is the result of our program.

track.getTitle() = I Saw Her Standing There

How do I read indexed bean’s property value?

In this example you’ll see how to read an indexed property of an object such as List or array. Using the PropertyUtils.getIndexedProperty() method we can do it easily. This method take the bean and the name of indexed property including the element to be read. Let’s see the example below for more details.

package org.kodejava.example.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;

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

public class ReadIndexedProperty {
    public static void main(String[] args) {
        Recording recording = new Recording();
        recording.setId(1L);
        recording.setTitle("With The Beatles");

        List tracks = new ArrayList<>();
        Track track1 = new Track();
        track1.setTitle("It Won't Be Long");

        Track track2 = new Track();
        track2.setTitle("All I've Got To Do");

        Track track3 = new Track();
        track3.setTitle("All My Loving");

        tracks.add(track1);
        tracks.add(track2);
        tracks.add(track3);

        recording.setTracks(tracks);

        try {
            Track trackOne = (Track) PropertyUtils.getIndexedProperty(recording, "tracks[0]");
            Track trackThree = (Track) PropertyUtils.getIndexedProperty(recording, "tracks[2]");

            System.out.println("trackOne.getTitle() = " + trackOne.getTitle());
            System.out.println("trackThree.getTitle() = " + trackThree.getTitle());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.example.commons.beanutils;

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

public class Recording {
    private Long id;
    private String title;
    private List tracks = new ArrayList<>();

    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

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

    public List getTracks() {
        return tracks;
    }

    public void setTracks(List tracks) {
        this.tracks = tracks;
    }
}

Our program results are:

trackOne.getTitle() = It Won't Be Long
trackThree.getTitle() = All My Loving