Java, JBoss

How to extract/unzip a WAR file in Java?

WAR stands for ‘Web application ARchive’. A WAR file nothing but a JAR file used to distribute a collection of JSPs, Servlets, Classes, XML files, tag libraries, static web pages (HTML and related files) and other resources that together constitute a web application.

In order to extract/unzip a WAR file, use the following JAR command:

jar -xvf yourWARfileName.war
Java

How to generate a random number within a range in Java

Here is a standard way to generate a random number within a specific range in Java.

Please note that in the below code, the top value (max) is exclusive and the min value is inclusive.

    public static int generateRandomNumber(int max, int min) {

        Random rand = new Random();
        int randomNum = rand.nextInt(max - min) + min;
        return randomNum;
    }

Here is the code to generate a random number with max and min value inclusive.

    public static int generateRandomNumber(int max, int min) {

        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }
Java

How to add or subtract time from Date in Java

Sample code to add 30 seconds to Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.SECOND, 30);
        Date addThirtySeconds = cal.getTime();
        System.out.println("New Date and Time: " + addThirtySeconds);

Sample code to subtract 30 seconds from Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.SECOND, -30);
        Date thirtySecondsBack = cal.getTime();
        System.out.println("New Date and Time: " + thirtySecondsBack);

Sample code to add 2 minutes to Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.MINUTE, 2);
        Date addTwoMinutes = cal.getTime();
        System.out.println("New Date and Time: " + addTwoMinutes);

Sample code to subtract 2 minutes from Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.MINUTE, -2);
        Date twoMinutesBack = cal.getTime();
        System.out.println("New Date and Time: " + twoMinutesBack);

Sample code to add an hour to Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.HOUR, 1);
        Date addAnHour = cal.getTime();
        System.out.println("New Date and Time: " + addAnHour);

Sample code to subtract an hour from Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.HOUR, -1);
        Date anHourBack = cal.getTime();
        System.out.println("New Date and Time: " + anHourBack);

Sample code to add 3 days to Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.DATE, 3);
        Date addThreeDays = cal.getTime();
        System.out.println("New Date and Time: " + addThreeDays);

Sample code to subtract 3 days from Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.DATE, -3);
        Date threeDaysBack = cal.getTime();
        System.out.println("New Date and Time: " + threeDaysBack);

Sample code to add 2 months to Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.MONTH, 2);
        Date addTwoMonths = cal.getTime();
        System.out.println("New Date and Time: " + addTwoMonths);

Sample code to subtract 2 months from Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.MONTH, -2);
        Date twoMonthsBack = cal.getTime();
        System.out.println("New Date and Time: " + twoMonthsBack);

Sample code to add 3 years to Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.YEAR, 3);
        Date addThreeYears = cal.getTime();
        System.out.println("New Date and Time: " + addThreeYears);

Sample code to subtract 3 years from Date in Java

        Date now = new Date();
        System.out.println("Current Date and Time: " + now);
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.YEAR, -3);
        Date threeYearsBack = cal.getTime();
        System.out.println("New Date and Time: " + threeYearsBack);
Java

Determine if a String is numeric in Java

There are many ways to determine if a String is numeric in Java. The most simplest one is as follows:

    private static boolean isNumeric(String string) {

        try {
            Double.parseDouble(string);
            return true;
        } catch(Exception ex) {
            return false;
        }
    }

However, if you plan to use this function a lot, you may run into performance issues because exception handling is expensive in Java. Moreover, it’s not a good idea to rely on exception being thrown to determine the validity of something.

Use Regular Expression:

A more elegant solution is to use a regular expression to check for validity of being a number.

    public static boolean isNumeric(String string) {
        return string.matches("[-+]?\\d+(\\.\\d+)?");
    }

Use positional parser:

An alternative and a more robust approach is to use positional parser to check for the validity of being a number.

    public static boolean isNumeric(String string) {

        NumberFormat formatter = NumberFormat.getInstance();
        ParsePosition position = new ParsePosition(0);
        formatter.parse(string, position);
        return string.length() == position.getIndex();
    }

In this approach we use positional parser and after parsing, if the parse position is at the end of the string, we can deduce that the entire string is a valid number.

Hibernate, Java

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected

Got this error today while working with Hibernate. I am not sure what all scenarios can cause this error. In my case, it was the value of the ‘id’ property in Hibernate mapping file that was causing this problem. Basically, in the Hibernate mapping file for the id property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.

<hibernate-mapping>

    <class name="com.devesh.database.model.Student" table="Student" >
        <id name="studentId" type="java.lang.Long">
            <column name="StudentID"/>
            <generator class="native"/>
        </id>
        <property name="studentName" type="java.lang.String">
            <column name="StudentName"/>
        </property>
        ---
        ---
    </class>

</hibernate-mapping>

That is, for the above Hibernate mapping file, I should not set the value of ‘studentId’ field explicitly by using setter method and try to save it to the database. It will be generated automatically in the database.

Java, JUnit

Testing exceptions in JUnit

In this post, we will look into testing expected exceptions using JUnit.

Let’s consider the following Employee class:

public class Employee {

    private String firstName;
    private String lastName;
    private int age;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {

        if(age > 0) {
            this.age = age;
        } else {
            throw new IllegalArgumentException("Invalid Employee Age.");
        }
    }
}

The setAge() method throws an exception when an age less than or equal to zero is passed. There are a couple of approaches to test this method:

Approach 1:

The most straight forward approach is to specify the exception in the @Test annotation. The test will pass only if the expected exception is thrown.

    @Test(expected = IllegalArgumentException.class)
    public void employeeAgeTest() {

        Employee emp = new Employee();
        emp.setAge(0);
    }

Approach 2:

The above approach is useful and straight forward. However, it has its own limitations. For example, you can’t test the value of the message in the exception.

JUnit 4.7 introduced ‘ExpectedException’ rule that addresses the shortcomings of the first approach. The ‘ExpectedException’ rule lets you indicate not only what exception you are expecting, but also the exception message you are expecting.


    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void employeeAgeTest() {
        exception.expect(IllegalArgumentException.class);
        exception.expectMessage("Invalid Employee Age");
        Employee emp = new Employee();
        emp.setAge(0);
    }
Ant, Java

How to install Ant on Windows?

1. Install Java Development Kit (JDK)

The most recent version of JDK can be downloaded from Oracle’s website.

Once you have downloaded and installed JDK on your machine, set the ‘JAVA_HOME’ environment variable.

JAVA_HOME

Modify the ‘Path’ environment variable to include ‘JAVA_HOME’

Path

Verify that the Java was installed correctly, by opening the command prompt and running ‘java -version’. This should print the version of Java you have just installed on your machine.

2. Download Apache Ant

Download the most recent version of Ant from the Apache’s Ant site.

Extract the downloaded zip file in the appropriate folder.
Example: C:\Program Files\Apache Software Foundation\apache-ant-1.9.3

3. Set Ant Environment Variables

Set ‘ANT_HOME’ environment variable.

ANT_HOME

Modify the ‘Path’ environment variable to include ‘ANT_HOME’

ANT_PATH

4. Verify

Verify that the Ant is installed correctly, by opening the command prompt and running ‘ant -version’. This should print the version of Ant you have just installed on your machine.