Thursday, May 6, 2010

Spring http remoting with java6 in-built http server

Java 6 runtime have Http Server inbuilt in it. So for spring remoting with http, we don't have to run our applications on web containers like tomcat or jetty.

Below code shows how we can do.

For the example sake we will create the server and client makes a call to the server in the same application.

Interface class

package com.ravi.blog.sunhttp;

public interface Service {

public String getName();

public int getId();

}

Implementation class

package com.ravi.blog.sunhttp;

public class ServiceImpl implements Service {

@Override
public int getId() {
System.out.println("In ServiceImpl getId");
return 1000;
}

@Override
public String getName() {
System.out.println("In ServiceImpl getName");
return "Ravi Service";
}

}

Main class, which will load the spring beans and make a call to the server.

package com.ravi.blog.sunhttp;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ServerNClient {

public static void main(String args[]){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext-sunhttpServer.xml"});
Service service = context.getBean("httpProxyBean",com.ravi.blog.sunhttp.Service.class);
System.out.println("In client Side Service Id " + service.getId());
System.out.println("In client Side Service Name " + service.getName());
}
}

Spring applicationContext file
applicationContext-sunhttpServer.xml



xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">



































On the server side, we first created a SimpleHttpInvokerServiceExporter for myService. Then we bind the exporter with the SimpleHttpServerFactoryBean with context as /raviService

On the client side, we created a HttpProxyBean for the serviceUrl(http://localhost:1080/raviService).

In the main function, we first created the beans which will start the server and then we invoked the methods.
This is the output of the program

In ServiceImpl getId
In client Side Service Id 1000
In ServiceImpl getName
In client Side Service Name Ravi Service

HttpInvokerProxyFactoryBean has getObject method which will return the HttpServer instance. With this we can add handlers at the runtime (even after the server started).