Tuesday, 18 June 2013

Less known features of Java

Every time I start (or think of starting) a blog post, a question arises in my mind, ‘How to start? What to write in the first paragraph?’Almost every time, an idea gets popped up in my mind, but today, my mind blanked out. I didn’t get any idea despite of thinking for more than 15 minutes. I even fell asleep a couple of times during that thought process. Then I thought of googling it. I opened google and typed ‘How to start a blog post’, I opened first 2-3 links, went through first link (patience: 100%), found nothing related to this, then went through the second one (patience: 50%), still, same result, then went through the third one hoping that this will really help me, but alas, nothing useful again(patience: 0%). Then I thought, ‘screw this’ and clicked on red button on upper right corner. And here we are, done with the first paragraph! Bingo!

Coming to the main aspect of this blog, this blog discusses about the features which are less known in java but are really useful. They help us a lot in our day to day programming. Even I was not aware of these. But when I came across such requirements, instead of implementing them with the traditional approach, I thought, ‘there must be some other way of doing it.’ Then I googled it and found the alternate solutions which are described in this blog. I have covered very small number of features in this blog. If I come across more of such features, I will definitely add them in my subsequent blog posts. We will look into these features one by one.

Double brace initialization:

Have you ever come across a requirement where you need to create a collection (say List) and fill it with the values available to you? May be you have to invoke the method which takes a collection filled with some predefined values as an argument, in this case, what will you do? You will probably go by the following traditional approach:


List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
//pass this list to the method

Or if your list is static then, you will probably initialize it like this

public static final List<String> list = new ArrayList<String>();
      static{
            list.add("A");
            list.add("B");
            list.add("C");
      }

Java provides a way to do this in a single go, by double brace initialization. All we need to do is to pass all the calls to add method while creating the collection itself, as described in the code below:

List<String> list = new ArrayList<String>(){{
     add("A");
     add("B");
     add("C");
}};
//pass this list to the method

Voila! Your list is created in a single go. Isn’t this wonderful? You can do the same for static list as well. Here are some technical details of this double brace initialization.

The first brace creates a new anonymous inner class, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an "instance initializer", because it is declared within the instance scope of the class.

This is just an excerpt; you can find the full article here.

Add shutdown hook:

Shutdown hook contains the code which is executed when an application goes down. Suppose if you want to do some activities before the application gets shut down (just like destroy() method of servlet) i.e. cleaning up resources, closing connections and streams, notify the administrator/user about the shutdown then you can use this shutdown hook to do the same. Following code shows how to do it.

public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
                 @Override
                 public void run() {
                     System.out.println("Inside Add Shutdown Hook...");
                 }
        });
        System.out.println("Last instruction of Program....");
        System.exit(0);
}

Output of this program will be:

Last instruction of Program....
Inside Add Shutdown Hook...

We can attach any number of shutdown hooks to the application. But but but, all shutdown hooks will run in parallel as they run in separate threads. Hence, in case of multiple shutdown hooks, we need to consider all the aspects of concurrency, deadlock, thread interaction etc.

We can also remove the shutdown hook by calling Runtime.removeShutdownHook(Thread hook)method.

The case when these shutdown hooks will not be executed is when JVM crashes unexpectedly or is killed by the user. Because, after all, it’s JVM which executes all these instructions. Hence, no JVM means no execution. More on shutdown hooks is described here and here.

Atomic classes (part of Java.util.concurrent.atomic package):

Atomic classes (e.g. Atomic Integer, Atomic Long etc) can be very useful when you want to share the variables across multiple threads. They provide “lock free thread safe programming on single variables” i.e. you can leave aside the concurrency problems if you use this classes. They have incrementAndGet() method which will provide you the next value.

Say, if you have requirement like how many threads have used a particular method or if you want to have some kind of counter which needs to be shared across the threads and these classes fit the bill. More on Atomic package is described here. A practical example of Atomic Integer is also shown here.

I am done with the features here. Hope you have liked it and will use it in future if required. Now starts the problem of what to write in the ending paragraph. My mind has again blanked out about this and I am not in a mood to google again. Hence, I am leaving it here.

A special thanks to my colleague Harshal Choksi who inspired me to write the blogs. Thanks for the inspiration mate. Keep inspiring people like this.

Happy coding!

Wednesday, 5 June 2013

Direct Web Remoting: Fire an Ajax call by converting javascript objects into java objects

Hello there! I am writing the blog after longer time than expected. Actually, a thought of writing another blog post struck into my mind many times in past 15 days or so. But, when I had the thought, I did not have the time to implement and write. When I had the time, the thought was not there into my mind and bringing that thought into my mind ate up all the available time. Thankfully, today I have both thought and time available and as a result, you are reading this!

Let’s not start this blog by traditional providing the statistics way. Instead, let’s start this directly with the main contents. And I know that no one likes to read the statistics anyways because they are nothing but bull crap.

This blog talks about Ajax, the technology which is used in many web applications these days. The main advantage of this technology is to submit only required information instead of submitting the whole page to the server. A prime example of Ajax is the form which needs to be filled for signing up for an email account. Everybody remembers that desired id text box right? The one in which we write our favorite id and it says “Sorry! This id is already in use.” Then you say, “Crap! Some gobshite has already taken it.” Then you fill your second favorite id and it still says, “Haha! This is also in use...” Then again, you try another one and the cycle gets repeated. It stops by you yelling “Screw this! I am not going to sign up for this id. Their email service is shite anyways.”

We are deviating from the main topic here I guess, so let’s get back to it. People use Ajax in many web applications; there are many ways to implement it (e.g. XmlHttpRequest, Prototype js, jQuery etc...). All have different methods of passing the parameters. How about creating an object in javascript, passing it to a java method and watching it magically get converted into java object? Isn't it awesome? This is exactly what we will ponder into in this blog.

Direct Web Remoting (will be referred to DWR henceforth) provides us the way to pass the objects (multiple parameters from page) into java class and they get converted into respective instances of DTOs. Without going much into theoretical aspects of DWR, let’s start with the implementation steps. And I guess this is what everyone will be interested into.

STEP 1: Add dwr.jar and commons-logging-1.1.1.jar into lib directory of your web application. They can be downloaded from their sites dwr and apache respectively (DWR internally uses commons logging that is the only reason why we need commons-logging.jar). I have added them into my sample project. You can use those too.

STEP 2: Add the following lines into your deployment descriptor (web.xml) to make your web application aware of the DWR servlet.

 <!-- DWR Servlet start-->
    <servlet>
        <servlet-name>dwr</servlet-name>
        <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>dwr</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
    <!-- DWR Servlet end-->

STEP 3: Create the dwr.xml file and put it into your WEB-INF directory. This file is master key to all the DWR communication/mapping. It defines the DTO which needs to be recognized as well as the class and method which needs to be called. Sample is provided below.

<dwr>
      <allow>
            <convert converter="bean" match="com.dwrtest.dto.TestDTO"></convert>
            <create creator="new" javascript="Filter">
                  <param name="class" value="com.dwrtest.action.TestAction"> </param>
                  <include method="testDWR" />
            </create>
      </allow>
</dwr>

Here, <dwr> and <allow> are the traditional opening and closing tags. Hence, we will focus on <convert>, <create>, <param> and <include> tags.

<convert>:  This tag provides the information to DWR about which javascript object needs to be converted into which java object. Here, the attribute converter=”bean” means the object passed from javascript will be converted into the object of the bean specified in “match” attribute. In this scenario, the bean specified in the “match” attribute must follow java bean specifications. We can even give * in the path. If it fails to find the class then the ajax call returns an error. Apart from bean, there are many other types of converters. They are specified here.

<create>: This tag, along with the sub tags, provides the information about which class and method needs to be called. Here, the attribute creator=”new” means the class will be instantiated using new keyword. If you are using spring IOC for instantiating the classes then, creator=”spring” needs to be used. The second attribute javascript=”Filter” means this method will be called from jsp page using Filter javascript. More on this in a shortwhile.

<param>: This tag gives information about the class whose method will be called.

<include>: This tag provides the names of the methods which  will be called using Ajax. If you have more than one method then you can specify their names in different include tags.

STEP: 4 Include the following javascripts into the page from which you are going to fire an Ajax call. These javascripts are generated dynamically and we are not supposed to give two hoots about these.

<script src='dwr/engine.js'></script>
<script src='dwr/util.js'></script>
<script src='dwr/interface/Filter.js'></script>

STEP: 5 create the methods in jsp to fire an Ajax call. The sample code is shown below:

function fireAjaxDWR(){
      var p = {
            firstName : document.getElementById("firstName").value,
            lastName : document.getElementById("lastName").value
      };
      Filter.testDWR(p,returnFromTest);
}

function returnFromTest(data){
alert(data.success);
}

Here, variable p will be converted into the instance of the bean specified in <convert> tag of dwr.xml file. First name and last name are two attributes of that bean.

The method ‘testDWR’ actually resides in the Action class (specified in the include tag in dwr.xml). The method accepts only one argument (that of type TestDTO). If you look at the call here, you will see that we have supplied two arguments. The other argument specifies the callback method (i.e. the method which will get called once the output is received). This method will be called by DWR engine once the method of action class completes its execution. The argument of this method will be the return type of that Action class’ method (in our case, it is of type TestDTO). We can access the reference variable using the dot operator as shown in the example.

Apart from specifying the call back method as an argument, we can specify the other arguments (such as timeout, the method to be called if timeout occurs etc) also. More information on this can be found on DWR website.

Voila! We are done with the sample implementation of DWR. I have created the web project and uploaded it. You can download it from here.

Finally, a special thanks to my former colleague Gaurav Saini, who taught me this awesome feature.

Happy Ajaxing!