JavaScript

How to send an AJAX HTTP GET request to server

We send an AJAX HTTP request to server using XMLHttpRequest object. The XMLHttpRequest object can be used to send data to a server in scenarios where we want to update parts of a web page, without reloading the whole page.

All modern browsers like Firefox, Chrome, Safari, etc have built-in XMLHttpRequest object. However, some old versions of IE doesn’t support XMLHttpRequest object. If the browser doesn’t support XMLHttpRequest object, we use ActiveXObject to send request to the server.

The following code snippet sends HTTP GET request to server:

    var xmlhttp;
    if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari support XMLHttpRequest object
        xmlhttp = new XMLHttpRequest();
    } else {
        // IE6, IE5 doesn't support XMLHttpRequest object
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","/servlet/Welcome.do?firstName=Devesh&lastName=Sharma",true);
    xmlhttp.send();

We use open() and send() methods of the XMLHttpRequest object to send a request to a server.

The above example send GET request to a server. GET is always simpler and faster than POST. However, there may be instances where you may want to use POST request:

1. Use POST request when you are sending a large amount of data because POST doesn’t have any size limitations.
2. Use POST request when you are sending sensitive information like username and password because POST is more secure and robust than GET.

Please refer this post to learn how to send POST request to server using AJAX.

Grails, SQL Server

Error in Grails – Cannot load JDBC driver class ‘com.microsoft.sqlserver.jdbc.SQLServerDriver’

If you are configuring a Grails application to connect to SQL Server database, there are chances that you might run into this issue. You can get this error because of many reasons. Here are few things you can try to get rid of the error:

1. As it is clear from the error message, the root cause of the error is SQLServerDriver class is not loaded. That’s because the driver is missing in the class path. In order to add SQLServerDriver to your class path, you need to download sqljdbc4.jar file and place it in your application’s /lib directory.

2. Make sure that you have updated DataSource.groovy file located at grails-app/conf to include the data source information. Please refer to this post to learn how you can include the data source information in your DataSource.groovy file.

3. If you think your driver and data source is properly configured, but you are still getting this error; the following steps might be useful:

    Stop the server using grails stop-app
    Run the grails clean command
    Close the command prompt or terminal window
    Open a new terminal window and start the Grails using grails -Dserver.port=8090 run-app
    Issue should now be resolved, hopefully!
Grails, SQL Server

Configuring Grails application to use SQL Server database

1. Create a new Grails application by typing in the following command in terminal window:

grails create-app grailsDbConn

2. Change to the application directory by typing the following command in terminal window:

cd grailsDbConn

3. Create a new Domain Class by typing in the following command in terminal window:

grails create-domain-class db.Employee

4. Open Employee.groovy file in your favorite IDE and edit it to the following:

package db

class Employee {
    
    String employeeID
    String firstName
    String lastName
    String dateOfBirth

    static constraints = {
    }
}

5. Create a new Controller by typing in the following command in terminal window:

grails create-controller db.Employee

6. Open EmployeeController.groovy in your favorite IDE and edit it to the following:

package db

class EmployeeController {

    def scaffold = Employee
}

7. Open DataSource.groovy file located at grails-app/conf in your favorite IDE to include the data source information

        dataSource {
            dbCreate = "create-drop"
            driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
            url="jdbc:sqlserver://localhost:1433;DatabaseName=[YOUR_DB_NAME]"
            username = "sa"
            password = "[YOUR_PASSWORD]"
        }

The updated DataSource.groovy file will look like the following:

dataSource {
    pooled = true
    driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
    url="jdbc:sqlserver://localhost:1433;DatabaseName=[YOUR_DATABASE]"
    username = "sa"
    password = "[YOUR_PASSWORD]"
    dbCreate = "create-drop"
    loggingSql = true
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
//    cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
}
 
// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop"
            driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
            url="jdbc:sqlserver://localhost:1433;DatabaseName=[YOUR_DATABASE]"
            username = "sa"
            password = "[YOUR_PASSWORD]"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
            properties {
               maxActive = -1
               minEvictableIdleTimeMillis=1800000
               timeBetweenEvictionRunsMillis=1800000
               numTestsPerEvictionRun=3
               testOnBorrow=true
               testWhileIdle=true
               testOnReturn=false
               validationQuery="SELECT 1 from dual"
               jdbcInterceptors="ConnectionState"
            }
        }
    }
}

8. Download sqljdbc4.jar and place that in your application’s /lib directory.

9. Start Grails by typing in grails run-app in terminal window.

Please note that a Grails application will be run with the built in Tomcat server on port 8080 by default. If you may have Tomcat running on port 8080, you may want to specify a different port by using the server.port argument. In this case, run Grails by typing in grails -Dserver.port=8090 run-app in the terminal window.

10. Once the application is loaded successfully, you should have an Employee table in the database. Creating a new Employee using the app should create a new record in the table.

Grails

How to install Grails on Windows?

1. Download the latest Grails release from the Grails Download page.

2. Extract the downloaded zip file into an appropriate location; like C:\grails-2.3.1

3. Create an environment variable GRAILS_HOME that points to the path where you extracted the zip file, like GRAILS_HOME=C:\grails-2.3.1

4. If your JAVA_HOME environment variable is not set, create an environment variable JAVA_HOME that points to your Java installation directory, like JAVA_HOME=C:\Program Files\Java\jdk1.7.0_51

5. Modify PATH environment variable to append a reference to the ‘bin’ directory within the Grails directory, like %GRAILS_HOME%\bin;

6. Verify that the Grails is installed correctly by typing grails -version in the command prompt. You should see the version we just installed as the output.

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);
    }