Tuesday, April 6, 2010

GWT Http request handling using Spring

Hi,
In a GWT based project we had a "login" mechanism which needed https protocol to be used. As GWT provides convienient ways of doing the same by using RequestBuilder class. We were using Spring framework at our server side. For handling GWT - RPC requests we were using the GWTHandler as mentioned in one of my previous posts GWT with Spring.
But now the issue was how to integrate https based requests into the project and into Spring. This was required because all the dependencies were being injected through spring. We figured out a simple solution; all the servlets that were extending from HttpServlet now were now extending from an abstract custom servlet class. This class was implementing the Spring mvc's Controller interface and also had one abstract method containing HttpRequest and HttpResponse objects as arguements. All the processing was done in this method. The handle request method returned a null and all the response was written in the response header. Since we had 2 different ways of hitting the server. The following mapping was added into the myapp-servlet.xml file.
  < !-- Handler mappings for GWT - RPC calls -- >
     < bean class="org.gwtwidgets.server.spring.GWTHandler" >
          < property name="mappings" >
              < map >
                  < entry key="/myApp/myAppService.rpc"  
                              value-ref="myAppRpcService" / >
              < / map >
          < / property >
     < / bean >
  
    < !-- Handler mappings for GWT - Http calls -- >
    < bean  class="org.springframework.
                      web.servlet.handler.SimpleUrlHandlerMapping" >
        < property name="mappings" >
            < props >
                < prop key="/myApp/login.rpc">myAppLogin < / prop >
            < / props >
        < / property >
    < / bean >

Needless to say that myAppRpcService and myAppLogin are the bean id's of beans defined in the spring context file.

I hope this post will be helpful to those who are trying to integrate gwt with spring.

Thursday, February 18, 2010

How to use struts tags in java script files?

Struts tags sometimes need to be used in java scripts. For example if we have certain validation in javascripts and we need to display a custom error message which is defined in application resources.properties file then we use the tag < bean:message key='error' >. But if this java script is in a .js file instead of the jsp page itself then this tag cannot be interpreted correctly and there is an error during runtime.
The solution to this problem is you first need to import the struts tag library using:
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%> in the .js file.
This line will be shown in error, ignore the same that is the feature of the IDE like netbeans or eclipse.
The path where the java script files are stored is given to the servlet engine so that at runtime the jsp tags will be interpreted properly. This can be done by adding the following servlet mapping and servlet elements in the web.xml file. Here the javascript files are stored at  /scripts/dynamic/ location in the root folder
< servlet >
    < servlet-name >JspServlet< /servlet-name >
    < servlet-class >org.apache.jasper.servlet.JspServlet<  /servlet-class >

   

< servlet-mapping>
     < servlet-name>JspServlet< /servlet-name>
     < url-pattern>/scripts/dynamic/*< /url-pattern>
< /servlet-mapping> 


Hence all the javascript part will be rendered to the client using the servlet engine which is able to interpret the struts jsp tags.

Tuesday, February 16, 2010

Java RMI step by step


I got an opportunity to analyse different distributed java computing technologies like EJB3, CORBA, Web Services etc. One of them was the Java RMI. I got a chance to develop a sample application in Java RMI and RMI-SSL and I would like to share my implementation experience and the problems faced.

Step 1
Create an interface which extends the java.rmi.Remote interface. This interface is used by the client to access the RMI stub class generated in the later steps.
Following is the interface which extends Remote

        import java.rmi.Remote;
        import java.rmi.RemoteException;

        public interface GreetingProvider extends Remote {
                String getGreeting() throws RemoteException;
        }



Step 2

Create a policy file which will define rights and permissions for the server as well as the client to access the remote objects. The file given below is an example file and AllPermission is not suitable for the production kind of environment. It is solely for learning and understanding RMI
create a file with the name java.security.policy as follows:
        grant
        {
              permission java.security.AllPermission;
        };

 



Step3
Create a server class which will implement the GreetingProvider interface. This class will reside in the server and will have the actual implementation of the method. This method will then be invoked remotely by the client using the common GreetingProvider interface defined in step 1.
Following is the implementing server class


        import java.net.MalformedURLException;
        import java.rmi.AlreadyBoundException;
        import java.rmi.Naming;
        import java.rmi.RMISecurityManager;
        import java.rmi.RemoteException;
        import java.rmi.server.UnicastRemoteObject;
        import com.rmi.test.remote.interfaces.GreetingProvider;

        public class GreetingServer implements GreetingProvider{

        protected GreetingServer() {
             super();
        }
        public static void main(String[] args) {
        System.setProperty("java.security.policy", "E:/Research_WS/RMITEST2   /java.security.policy"); // set property java.security.policy and give the path of the //java.security.policy file created in step 2
              
        if (System.getSecurityManager() == null)
            System.setSecurityManager ( new RMISecurityManager() );
       
        try {
            GreetingProvider server = new GreetingServer();
            GreetingProvider stub = (GreetingProvider)
                UnicastRemoteObject.exportObject(server); // returns the stub class
           
            Naming.bind("GreetingServer", stub);
            System.out.println("service bound");
        } catch (RemoteException e) {
             e.printStackTrace();
        } catch (MalformedURLException e) {
             e.printStackTrace();
        } catch (AlreadyBoundException e) {
             e.printStackTrace();
        }
    }

    @Override
    public String getGreeting() {
        return "Hello World";
    }
}



Step 4
Create the client class. This class will obtain the remote server object through a stub class which will be generated in the steps below. This client is residing on the same JVM as the server machine. In case it should reside in a separate JVM, then the GreetingProvider interface,java.security.policy and stub class needs to be exported to the client through a jar file.
Client class code is as follows:

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import com.rmi.test.remote.interfaces.GreetingProvider;

public class GreetingClient {

    public static void main(String args[])
    {
        System.setProperty("java.security.policy", "E:/Research_WS/RMITEST2               /java.security.policy");
        System.out.println(System.getProperty("java.security.policy"));
        if (System.getSecurityManager() == null)
        {
            System.setSecurityManager
            (new RMISecurityManager());
        }
   
        try {
            GreetingProvider service = (GreetingProvider) Naming.lookup
                ("rmi://localhost:1099/GreetingServer");
            System.out.println(service.getGreeting());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (NotBoundException e) {
            e.printStackTrace();
        }
    }
}






Step 5
Compile the interface,server, client classes prepared in the above steps. If you are not using an IDE you can compile using the javac command from the command prompt.



Step 6
Start the rmi registry using the start rmiregistry command
using the rmic command compile the server class (not the .java file but the .class file generated after javac compilation of the server class) . A stub will be generated after this command. This stub is the client stub that will be actually referencing our remote server object. 


Step 7
Now run the server (rmi registry is still on) i.e let the main method execute. But there is a codebase Virtual machine arguement that is to be added while running. It can be done as follows:
-Djava.rmi.server.codebase=file:/e:/Research_WS/RMITEST2/bin/
give the path where you will be able to find the stub class (.class)


Step 8
Run the client.


Output
Hello World

The policy file and the codebase virtual machine property are quite important and are prone to be forgotten. Also the rmiregistry should be started when you run the server and the client. You can also start the registry at a particular port by default the port is 1099.

Monday, February 1, 2010

GWT + JSON

Hi all,

I had an opportunity to use JSON with GWT and I would like to share the implementation idea.

I take username from the username field in the GWT client page and create a JSON object to be passed to the server. Following is the client side code to create the JSON object

private String createJSONPojo(String userName)
    {
        JSONObject ob = new JSONObject();
        JSONString uname = new JSONString(userName);
        ob.put("userName", uname);
        return ob.toString();
    }

The JSON object being used in the above case is from the com.google.gwt.json.client package of gwt-user.jar i.e there is JSON support in GWT.

Now the question comes how do I decode the JSON Object string at the server side. I used an external json support library at the server side. Of course we can use the client side library itself at the server side too but I wanted to avoid getting any client side code/jars to server side. The external library used was json-lib-2.2.2-jdk15.jar. Following is the code to interpret the JSON string at the server side.

public String createUserJSON(String json)
    {
        JSONObject ob = JSONObject.fromObject(json);
        UserPojo pojo = new UserPojo ();
        pojo.setUserName(ob.getString("userName"));
        userservice.createUser(pojo);
        return "success";
    }

The library provides methods to create JSON Objects on server side and send them to the client. Similarly the GWT library has a JSONParser class to parse the JSON string at the client side.



Thursday, January 28, 2010

Injecting request and response objects of GWT client in Spring.

Hi,


In my last post I had explained how I integrated Spring with GWT by using the external library. Now I had another issue, in which I wanted the HttpSession object in the service class. I had to retrieve some variables from the session object. Since I wasn't extending my service layer class from RemoteServiceServlet I couldn't use the methods to get access to the request and response objects and hence I couldn't get the session object. I discovered that I there were some helper classes in the same external library which could be used and injected using Spring AOP. There is a RequestInjection class which was used  by us as an interceptor to the request.
It was mapped in the spring-servlet file in the following manner.


< bean id="requestSetter" class="org.gwtwidgets.server.spring.RequestInjection" >
        < property name="requestSetterName" value="setRequest"/ >
        < property name="responseSetterName" value="setResponse" / >
    < / bean >
< bean id="testServiceProxy"
          class="org.springframework.aop.framework.ProxyFactoryBean" >
          < property name="target" ref="testService" / >
          < property name="autodetectInterfaces" value="true" / >
          < property name="interceptorNames" >
              < list >
                  < value >requestSetter< / value >
              < / list >
          < / property >
    < / bean >

Wednesday, January 27, 2010

Using Spring with GWT (Google Web Toolkit)

Hi All,
I have been working on the Google web toolkit (GWT) technology version 1.6 lately. We had a task at hand to integrate server side spring technology and use GWT at the client side. GWT is an AJAX based framework developed by google and all the server side calls are processed through AJAX. The catch here is since GWT dispatches only RPC calls to the server. To integrate spring framework, an external library gwt-sl-0.1.5b.jar  was used in which we have a support package for spring integration. This discovery helped us to solve most of out problems. A GWTHandler class was used to handle the RPC requests from the GWT client.
This class is mapped in the spring-servlet file on the server side as follows:


     < bean class="org.gwtwidgets.server.spring.GWTHandler" >
          < property name="mappings" >
              < map >
                      < entry key="/module/myTestModule/test.rpc" 

                                   value-ref="test" / >
              < / map >
          < / property >
       < / bean > 


Prior to using this method, the service classes on the server side used to extend from the RemoteServiceServlet class. But using this mapping I could avoid extending from any classes and hence keeping the class free to extend from any other application specific classes.

Monday, October 12, 2009

How to write to a .properties file dynamically from java code?

We all must have used the properties file for using our desktop\web application in different locales. But once in one of the projects I encountered a situation where we had to write the configuration settings to a properties file which were a one time activity from the end user's side.

We followed the following approach to write to a .properties file from java code

File propFile = new File(System.getProperty("user.dir")+"src\\uts\\config\\envConfig.properties");
Properties prop = new Properties();

try
{
   FileInputStream fis = new FileInputStream(propFile);
   prop.load(fis);
   prop.setProperty("env_"+environmentName, environmentName);
   prop.setProperty("uid_"+userId, userId);
   prop.setProperty("pass_"+password, password);
   prop.store(new FileOutputStream(propFile), null);
}
catch(Exception e)
{
  e.printStackTrace();
}

Tuesday, September 29, 2009

Serialization

Serialization is a technique to write object's state to a data file. In order to be able to write the object to a file the class whose instance (object) we need to write has to implement the marker interface Serializable. This interface does not contain any methods.There are two methods that we use to serialize and deserialize an object, they are writeObject(Object) , readObject(). The writeObject method is in the ObjectOutputStream class while the readObject() method is in the ObjectInputStream class. All the instance variables of the object are saved and retrieved successfully as they were saved provided no instance variable is marked with the keyword transient. This keyword if used specifies that the state of that instance variable is not to be saved. 

Following code demonstrates how to do serialization

Monday, September 28, 2009

What can be done with enums?

This post shows the various things that enums can do. Enum data type was introduced since Java 5 and is a very powerful type. It is a special type of class which contains constant objects, instance variables,constructors,overloaded constructors, methods and overloaded methods as well. Enums can be declared outside or inside the class.Another important feature of enums is semicolon is optional.


Sunday, September 20, 2009

Calling new on an object

When can we call a new on an object? We normally use a new keyword in java to create a new object as follows:
Integer i = new Integer();
But can we use the new keyword on an object itself as follows:
TestClass.MyClass c = new TestClass().new MyClass();

Wednesday, September 16, 2009

Generics with non - generics

When we use generics we use the syntax as List< Integer > newList= new ArrayList< Integer >(), Can there be a way by which I can put a string into it. How can I cheat....????
Of course there is a way. This is by mixing generic code with non-generic code.
This is how it can be done.
public class TestGeneric{
   public static void main(String args[])
  {
       List newList = new ArrayList();
       newList.add(7); // autoboxing feature
       newList.add(new Integer(10)); // normal adding objects
       insert(newList);
  }
  public void insert(List nonGenericList)
 {
     nonGenericList.add("42"); // valid compiles fine and surprisingly runs fine too.....check the reason y below
 }
}

Monday, September 14, 2009

Does finally block always execute?

I had always thought that the finally block in a try-catch-finally statement always executes. But this is not true. I found one exceptional case where the finally block does not execute.

Please see the below code example.

public class TestException
{

    static int choice = 5;
   
    public static void main(String[] args)
   {
      try{
             if (choice != 5)
            {
                System.out.println("hello");
             }
             else
            {
               System.out.println("In else");
               System.exit(1);
             }
           }
      finally
      {
          System.out.println("in finally");
       }
   }
}

Hashtable and HashMap

In the java's collections framework we have two classes HashMap and Hashtable which implement the map interface.Both of them perform the same function of storing data in key - value pair, but Hashtable was older version of HashMap. Hashtable is synchronized means all the methods in the Hashtable class are synchronized i.e they are thread safe. Also if there is a difference in the naming convention, notice that the 't' is in lower case but the 'M' in HashMap is upper case following the camel case convention. HashMap is faster for iteration as compared to Hashtable as it is not synchronised. It is recommended to use HashMap unless you have a very good reason to use Hashtable.

Another point of difference is that HashMap can have multiple null values but the keys of those values should be different. Also there can exist one null key in the HashMap but there cannot be any null keys or even values for that matter in a Hashtable.