How do I generate random alphanumeric strings?

The following code snippet demonstrates how to use RandomStringGenerator class from the Apache Commons Text library to generate random strings. To create an instance of the generator we can use the RandomStringGenerator.Builder() class build() method. The builder class also helps us to configure the properties of the generator. Before calling the build() method we can set the properties of the builder using the following methods:

  • withinRange() to specifies the minimum and maximum code points allowed in the generated string.
  • filteredBy() to limits the characters in the generated string to those that match at least one of the predicates supplied. Some enum for the predicates: CharacterPredicates.DIGITS, CharacterPredicates.LETTERS.
  • selectFrom() to limits the characters in the generated string to those who match at supplied list of Character.
  • usingRandom() to overrides the default source of randomness.

After configuring and building the generator based the properties defined, we can generate the random strings using the generate() methods of the RandomStringGenerator. There are two methods available:

  • generate(int length) generates a random string, containing the specified number of code points.
  • generate(int minLengthInclusive, int maxLengthInclusive) generates a random string, containing between the minimum (inclusive) and the maximum (inclusive) number of code points.

And here is your code snippet:

package org.kodejava.commons.text;

import org.apache.commons.text.CharacterPredicates;
import org.apache.commons.text.RandomStringGenerator;

public class RandomStringDemo {
    public static void main(String[] args) {
        RandomStringGenerator generator = new RandomStringGenerator.Builder()
                .withinRange('0', 'z')
                .filteredBy(CharacterPredicates.DIGITS, CharacterPredicates.LETTERS)
                .build();

        for (int i = 0; i < 10; i++) {
            System.out.println(generator.generate(10, 20));
        }
    }
}

Below are examples of generated random alphanumeric strings:

weJDtVARLIFS96WXje
FYrNzTR3Q3dUrLT3Xsc
4F1fu8nSsA
nIQi3a4Oyv9
l6QcsP9bejdbaLd2jd
Cc9YgTfgwo
2B8un8YCcxn9m2
RAN2dZAWalUIWeZeoS
jPQspicyaKfAzS14twH
GTurc0lWkSid03rG0JZ

Apache Logo

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.10.0</version>
</dependency>

Maven Central

Using DigestUtils.sha1hex() method to generate SHA-1 digest

In this example you’ll learn how to generate an SHA-1 digest using the Apache Commons Codec DigestUtils class. In the last two examples you’ve already seen how to generate the MD5 digest using the same library. Compared to the MD5 version the SHA-1 digest is known to be stronger to brute force attacks, but it is slower to generate. The SHA-1 produces a 160 bit (20 byte) message digest while the MD5 produces only a 128 bit message digest (16 byte).

In the code snippet below we demonstrate three different ways to use the DigestUtils.sha1Hex() method. In the first method in the example, the byteDigest(), we calculate the digest from an array of byte data. Followed by the second method, the inputStreamDigest() where we calculate the digest of an InputStream object. And on the last method we call the overload version of the sha1Hex() method to calculate the digest of a string.

Let’s see the full code snippet.

package org.kodejava.commons.codec;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class SHAHashDemo {
    public static void main(String[] args) {
        SHAHashDemo demo = new SHAHashDemo();
        demo.byteDigest();
        demo.inputStreamDigest();
        demo.stringDigest();
    }

    /**
     * Calculates SHA-1 digest from byte array.
     */
    private void byteDigest() {
        System.out.println("SHAHashDemo.byteDigest");
        byte[] data = "The quick brown fox jumps over the lazy dog."
                .getBytes(StandardCharsets.UTF_8);
        String digest = DigestUtils.sha1Hex(data);
        System.out.println("Digest          = " + digest);
        System.out.println("Digest.length() = " + digest.length());
    }

    /**
     * Calculates SHA-1 digest of InputStream object.
     */
    private void inputStreamDigest() {
        System.out.println("SHAHashDemo.inputStreamDigest");
        String data = System.getProperty("user.dir") + "/data.txt";
        File file = new File(data);
        try (InputStream is = new FileInputStream(file)) {
            String digest = DigestUtils.sha1Hex(is);
            System.out.println("Digest          = " + digest);
            System.out.println("Digest.length() = " + digest.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Calculate SHA-1 digest of a string / text.
     */
    private void stringDigest() {
        System.out.println("SHAHashDemo.stringDigest");
        String data = "This is just a simple data message for SHA digest demo.";
        String digest = DigestUtils.sha1Hex(data);
        System.out.println("Digest          = " + digest);
        System.out.println("Digest.length() = " + digest.length());
    }
}

When you run the code it will output the following result:

SHAHashDemo.byteDigest
Digest          = 408d94384216f890ff7a0c3528e8bed1e0b01621
Digest.length() = 40
SHAHashDemo.inputStreamDigest
Digest          = da39a3ee5e6b4b0d3255bfef95601890afd80709
Digest.length() = 40
SHAHashDemo.stringDigest
Digest          = 4290d13ca383c2159c442d75355d83e310a2ea15
Digest.length() = 40

Maven Dependencies

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.16.0</version>
</dependency>

Maven Central

How do I generate MD5 digest from a File or an InputStream object?

In the How do I calculate the MD5 digest of a string? example you can see how to calculate the MD5 digest from a text or a string. We are using the Apache Commons Codec library and use the DigestUtils.md5Hex() method to generate the MD5. I’ve mentioned in that post that we can also generate the MD5 digest of a byte array and InputStream object. In the example below you’ll see an example to generate the MD5 digest of a text data stored in a file.

package org.kodejava.commons.codec;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MD5FileHashDemo {
    public static void main(String[] args) {
        // Define the data file path and create an InputStream object.
        String data = System.getProperty("user.dir") + "/data.txt";
        File file = new File(data);

        try (InputStream is = new FileInputStream(file)) {
            // Calculates the MD5 digest of the given InputStream object.
            // It will generate a 32-character hex string.
            String digest = DigestUtils.md5Hex(is);
            System.out.println("Digest = " + digest);
            System.out.println("Length = " + digest.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The first thing we need to do is to add the import statement to our class to import the org.apache.commons.codec.digest.DigestUtils class. The DigestUtils.md5Hex() method define as a static method so that we don’t have to create an instance of DigestUtils class before we can use it. Before we create the InputStream object we define the path to our data file. Next we create the File object from the defined path followed by creating the InputStream object of the file.

To generate the digest, we can simply pass the instance of the InputStream object into the DigestUtils.md5Hex() method. And if there is no error occurred during the process, we will get a 32 character of hex string as the output. One last thing that you have to do is the catch the possible exception thrown by the method. So we add the try-catch block and print the error stack trace to help us identify any error.

And here is the example output generated by the code snippet above:

Digest = d41d8cd98f00b204e9800998ecf8427e
Length = 32

Maven Dependencies

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.16.0</version>
</dependency>

Maven Central

How do I calculate the MD5 digest of a string?

In this post you will learn how to calculate the MD5 digest of a string. One of the most commonly use for this functionality in an application is to secure a password. For security reasons, you will never want to store user passwords in the application database in a plain text. There are other more secure hash algorithm out there such as the SHA-1 (Secure Hash Algorithm) but the MD5 message digest offer a faster implementation compared to SHA-1.

You can calculate the MD5 digest using the message digest library provided by the Java Standard Edition library, but the Apache Commons Codec library gives you a simple and easy to use API for generating the MD5 hash. On the example below you will see how to generate to hash to secure a password and also to generate the hash for a longer text. The text is what you might want to send to a friend via an email. To make sure that your friend receive your original message without any modification you can send the generated hash in separated email that can be used to verify the message.

package org.kodejava.commons.codec;

import org.apache.commons.codec.digest.DigestUtils;

public class MD5HashDemo {
    public static void main(String[] args) {
        // Calculates the MD5 digest for the password text and returns
        // the value as a 32 character hex string.
        String password = "s3cretw0rd**";
        String digest = DigestUtils.md5Hex(password);

        // Prints the plain text password, the digest and the length of
        // the digest.
        System.out.println("Password        = " + password);
        System.out.println("Password Digest = " + digest);
        System.out.println("Length          = " + digest.length());

        // Calculates the MD5 digest for the long texts.
        String md5 = """
                The MD5 message-digest algorithm is a formerly \
                widely used cryptographic hash function that produces \
                a 128-bit (16-byte) hash value. Specified in RFC 1321, \
                MD5 has been utilized in a wide variety of security \
                applications, and is also commonly used to check data \
                integrity. MD5 was designed by Ron Rivest in 1991 to \
                replace an earlier hash function, MD4. An MD5 hash value \
                is typically expressed as a hexadecimal number, 32 \
                digits long.
                """;
        String fingerprint = DigestUtils.md5Hex(md5);

        // Prints the text, the fingerprint and the length of the
        // digest / fingerprint.
        System.out.println("Text            = " + md5);
        System.out.println("Fingerprint     = " + fingerprint);
        System.out.println("Length          = " + fingerprint.length());
    }
}

As can be seen in the code example above, we use the DigestUtils.md5Hex() method to generate the MD5 digest. This class is part of the Apache Commons Codec under the org.apache.commons.codec.digest package. The method is a static method, so we don’t need to create an instance of the class before we can utilize the method. The md5Hex() method takes a string argument and produce a 32 characters hex string. The length will always 32 characters regardless the length of the processed text / string.

Besides, accepting a string argument, the overload version of the DigestUtils.md5Hex() method can accept an array of byte or a java.io.InputStream object as the argument.

Here is an example of the output produces:

Password        = s3cretw0rd**
Password Digest = 203c603a7330ab3ea032f4b9f140cf95
Length          = 32
Text            = The MD5 message-digest algorithm is a formerly widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. Specified in RFC 1321, MD5 has been utilized in a wide variety of security applications, and is also commonly used to check data integrity. MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4. An MD5 hash value is typically expressed as a hexadecimal number, 32 digits long.

Fingerprint     = a1e848ba8024fd5e38f567c107f0f4d2
Length          = 32

Maven Dependencies

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.16.0</version>
</dependency>

Maven Central

How do I print the contents of an array variable?

You need to print the contents of an array variable. The long way to it is to user a loop to print each element of the array. To simplify this, you can use the Apache Commons Lang ArrayUtils.toString() method. This method can take any array as a parameter and print out the contents separated by commas and surrounded by curly brackets. When you need to print a specific string when the array is null, you can provide the second string argument to this method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsToString {
    public static void main(String[] args) {
        // Print an int array as string.
        int[] numbers = {1, 2, 3, 5, 8, 13, 21, 34};
        System.out.println("Numbers = " + ArrayUtils.toString(numbers));

        // Print string array as string.
        String[] grades = {"A", "B", "C", "D", "E", "F"};
        System.out.println("Grades = " + ArrayUtils.toString(grades));

        // Print a multidimensional array as string.
        int[][] matrix = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
        System.out.println("Matrix = " + ArrayUtils.toString(matrix));

        // Return "Empty" when the array is null.
        String[] colors = null;
        System.out.println("Colors = " + ArrayUtils.toString(colors, "None"));
    }
}

The output of the code snippet above:

Numbers = {1,2,3,5,8,13,21,34}
Grades = {A,B,C,D,E,F}
Matrix = {{0,1,2},{1,2,3},{2,3,4}}
Colors = None

If you are using the JDK 1.5, or later, you can actually use the java.util.Arrays class to do the same thing as the org.apache.commons.lang.ArrayUtils class does.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

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

package org.kodejava.commons.lang;

public class ObjectHashCodeDemo {

    public static void main(String[] args) {
        Book book1 = new Book(1L, "Spring Boot in Action", "Craig Walls");
        Book book2 = new Book(2L, "Docker in Action", "Jeff Nickoloff");
        Book book3 = book1;

        System.out.println("book1.hashCode() = " + book1.hashCode());
        System.out.println("book2.hashCode() = " + book2.hashCode());
        System.out.println("book3.hashCode() = " + book3.hashCode());
    }
}
package org.kodejava.commons.lang;

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

import java.io.Serializable;

public class Book implements Serializable {
    private Long id;
    private String title;
    private String author;

    public Book(Long id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    //~ Implements getters and setters here.

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof Book)) {
            return false;
        }

        Book that = (Book) o;
        return new EqualsBuilder()
            .append(this.id, that.id)
            .append(this.title, that.title)
            .append(this.author, that.author)
            .isEquals();

        // You can also use reflection of the EqualsBuilder class.
        // return EqualsBuilder.reflectionEquals(this, that);
    }

    public int hashCode() {
        return new HashCodeBuilder()
            .append(id)
            .append(title)
            .append(author)
            .toHashCode();

        // Or even use the simplest method using reflection below.
        // return HashCodeBuilder.reflectionHashCode(this);
    }
}

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I checks if two dates are on the same day?

In this example, you will learn how to find out if two defined date objects are on the same day. It means that we are only interested in the date information and ignoring the time information of these date objects. We will be using an API provided by the Apache Commons Lang library. So here is the code snippet:

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.DateUtils;

import java.util.Calendar;
import java.util.Date;

public class CheckSameDay {
    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = new Date();

        // Checks to see if the dates is on the same day.
        if (DateUtils.isSameDay(date1, date2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", date1, date2);
        }

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        // Checks to see if the calendars is on the same day.
        if (DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is on the same day.%n", cal1, cal2);
        }

        cal2.add(Calendar.DAY_OF_MONTH, 10);
        if (!DateUtils.isSameDay(cal1, cal2)) {
            System.out.printf("%1$te/%1$tm/%1$tY and %2$te/%2$tm/%2$tY " +
                    "is not on the same day.", cal1, cal2);
        }
    }
}

The example results produced by this snippet are:

31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 31/10/2021 is on the same day.
31/10/2021 and 10/11/2021 is not on the same day.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

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 property method provided by this class. The basic properties are 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 error occurs.

package org.kodejava.commons.dbcp;

import org.apache.commons.dbcp2.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) {
        // Creates a BasicDataSource and defines its properties
        // including the driver class name, JDBC url, username
        // and password.
        try (BasicDataSource dataSource = new BasicDataSource()) {
            dataSource.setUrl("jdbc:mysql://localhost/kodejava");
            dataSource.setUsername("kodejava");
            dataSource.setPassword("s3cr*t");

            // Get a connection from the data source and do a
            // database query with the obtained connection.
            try (Connection conn = dataSource.getConnection();
                 PreparedStatement stmt = conn.prepareStatement("SELECT * FROM author")) {
                ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    System.out.println("Author name: " + rs.getString("author_name"));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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?.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.10.0</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create a database connection pool?

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

package org.kodejava.commons.dbcp;

import org.apache.commons.dbcp2.*;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

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

public class ConnectionPoolExample {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    private GenericObjectPool<PoolableConnection> connectionPool = null;

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

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM author")) {
            demo.printStatus();

            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                System.out.println("Author name: " + rs.getString("author_name"));
            }
        }

        demo.printStatus();
    }

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

        // Creates a PoolableConnectionFactory that will wrap the
        // connection object created by the ConnectionFactory to add
        // object pooling functionality.
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);
        pcf.setValidationQuery("SELECT 1");

        // Creates an instance of GenericObjectPool that holds our
        // pool of connection objects.
        GenericObjectPoolConfig<PoolableConnection> config = new GenericObjectPoolConfig<>();
        config.setTestOnBorrow(true);
        config.setMaxTotal(10);
        connectionPool = new GenericObjectPool<>(pcf, config);
        pcf.setPool(connectionPool);

        return new PoolingDataSource<>(connectionPool);
    }

    private GenericObjectPool<PoolableConnection> getConnectionPool() {
        return connectionPool;
    }

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

The code shows the following status as output example:

Max   : 0; Active: 0; Idle  : 0
Max   : 1; Active: 1; Idle  : 0
Author name: Raoul-Gabriel Urma
Author name: Mario Fusco
Author name: Alan Mycroft
Max   : 0; Active: 0; Idle  : 1

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.10.0</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I capitalize each word in a string?

This example show you how to capitalize a string. We use methods from WordUtils class provided by the Apache commons-text;. We can use the WordUtils.capitalize(str) or WordUtils.capitalizeFully(str).

Let’s see an example below:

package org.kodejava.commons.text;

import org.apache.commons.text.WordUtils;

public class WordCapitalize {
    public static void main(String[] args) {
        // Capitalizes all the whitespace separated words in a string,
        // only the first letter of each word is capitalized.
        String str = WordUtils.capitalize(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);

        // Capitalizes all the whitespace separated words in a string
        // and the rest string to lowercase.
        str = WordUtils.capitalizeFully(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);
    }
}

And here are the result of the program:

str = The Quick Brown Fox JUMPS OVER The Lazy Dog.
str = The Quick Brown Fox Jumps Over The Lazy Dog.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.10.0</version>
</dependency>

Maven Central