November 30, 2009
The Nov’09 Changes in My Life
This November, I saw some major changes in my professional life. This is the month, I served my last working day at Sun Microsystems. I had to undergo a lot of mental struggle in deciding whether or not to leave this great organization. But considering my personal commitments and career ambitions I had to take this tough decision.
I have joined a cloud computing startup, Sonoa Systems. There’s a sudden understandable change in the work environment – from a company with 30000+ people to a company with less that 100 employees. It might be a small organization, but is one with a great vision.
I’m happy that the new job would let me put in practice all that I have learned throughout the past five years of my career, specially, the SOAP and REST web services that I got a chance to work on when at Sun.
One great coincidence is that I have joined Sonoa on the 27th of Nov, the same day on which I joined my Engineering College nine years back. I hope the coming days would be as lovely and fruitful as my college days
.
November 11, 2009
JTF: Running tests against an app deployed on a staging server
Few days back I saw somebody asking whether the Jersey Test Framework allows you to run your tests on an application which is deployed on a staging server. The answer was NO at that point of time. Then I realized that this is a common use case and that it would be good to add this support.
With this release of Jersey 1.1.4, the Jersey Test Framework now lets you run your tests against your application deployed on a staging server. All that you have to do is just set this property JERSEY_HOST_NAME to the IP Address or the domain name of the machine, i.e., the staging server, on which your application is pre-deployed.
Lets say you have your application deployed on a machine with IP 129.132.212.54, tests could be run using the following command on your local machine:
mvn clean test -Dtest.containerFactory=com.sun.jersey.test.framework.spi.container.external.ExternalTestContainerFactory -DJERSEY_HOST_NAME=129.132.212.54 -DJERSEY_HTTP_PORT=<http_port>
- The support for specifying the JERSEY_HOST_NAME is limited only to the external container types.
- Apart from the JERSEY_HOST_NAME you would also need to set the JERSEY_HTTP_PORT to the port on which your server is listening.
- For more information on the various container types supported by the framework, please refer the previous blog entry on the framework.
November 4, 2009
Hudson: A Continous Integration Tool
Continuous Integration Tools
A continuous integration tool is an automated build system that
checks out the most current code from the source code repository,
builds it, and makes the resulting artifacts available for download. Such tools come handy when your application has multiple modules and there are multiple engineers working on them. These tools could be used to integrate these various modules, build the system and also maybe run some tests to ensure that everything is fine.
Hudson: What is it?
Hudson is an open-source continous integration tool, which has become very popular for some time now. It provides various features like options for checking out the source code from various version controlling systems like CVS, SVN, etc., setting the version of Java to be used, the machine(s) on which to run the integrations/builds, notifying an user or a group of users about a build failure, scheduling the job execution, etc. More information can be obtained from the Hudson project site at http://hudson-ci.org/.
Master-Slave Configuration
One interesting feature of Hudson is its provision to run a job in a master-slave configuration, i.e., there would be a Hudson master machine which would take up all the requests like defining a job, configuring it, triggering it, etc., while there will be a set of slave machines on which the executions would actually happen.
Lets say you want to define a job which has to be run on more than one platform. You define it in the Hudson master, the interface for all your configurations, and then tie it to all the machines that you would want to run the job on. The underlying mechanism of Hudson takes care of all the communication between the Hudson master and each of the slaves which are registered with it.
Now, we will see how to setup Hudson – the master and slave(s).
Setting up the Hudson Master
The master could be setup on any OS, for convenience lets assume we are setting it up on Linux.
- If you are using Ubuntu, be sure to upgrade to 8.04 to avoid
problems with RSA keys (keys generated by keygenerator in 7.10 are
blacklisted!) - Login as someone with root role (e.g. uadmin)
-
sudo useradd -d /space/hudson -m hudson– this creates user hudson with home in /space/hudson (Folder hudson does not need to exist) -
sudo passwd hudsonchanges the password for user hudson - Login as hudson user
- Create folder $HOME/jdks and install there jdk1.6.0
-
ssh-keygen -t rsagenerate public / private RSA key, public key is used for ssh login to slaves without passwords - =touch /space/hudsonserver/master = – creates foo file master as a workaround for hudson issue #936- parent project occuppies executor on slave
- Download hudson.war bits the Hudson site at http://hudson-ci.org/
- Install webserver (e.g. tomcat) and deploy Hudson
- If you do not want to run Hudson in Tomcat, use built-in server Winstone:
- run
java -jar hudson.warto start Hudson master on port 8080 - NOTE: best idea is to use something like this script (we use in
this script non-default port 18080 because this is second instance of
Hudson on the same machine):
- run
#!/bin/bash
# kill running hudson
kill `ps aux|awk '$13 == "./hudson.war" {print $2}'` 2> /dev/null
# nohup new hudson
nohup /space/jdks/jdk1.6.0_05/bin/java -jar ./hudson.war --httpPort=18080 --ajp13Port=18009 &
- Once you have the war file deployed, you could launch the application.
- Various settings like different JDKs, MAVEN_HOME could be made at the "Manage Hudson" page by clicking on the "Manage Hudson" link in the side pane.
Setting up the Hudson Slave
The following steps could be used to create a slave on a linux/solaris machine:
- Create an user "hudson" with home in /space/hudson.
- sudo useradd -d /space/hudson -m hudson
- Set a password for this user
- sudo passwd hudson
- Login as user "hudson".
- Create folders "ant" and "jdks" in /space/hudson.
- Download and unzip ant into folder "ant".
- Download and unzip various versions of jdk into jdks.
- Copy the id_rsa.pub of the Hudson master to file
/space/hudson/.ssh/authorized_keys. This enables the Hudson master to
establish a remote connection to the slave without having to enter the
login credentials. To do this:- Setup a FTP connection to the Hudson master.
- Get the id_rsa.pub file from the hidden folder ".ssh".
- Close the FTP connection.
- Copy this id_rsa.pub file to /space/hudson/.ssh/authorized_keys. Create the directory .ssh if it doesn’t exist already.
- To verify that the Hudson master’s key is successfully added to
this slave’s "ssh" keys, try setting up a ssh connection from the
Hudson master to this slave node, as "ssh hudson@your_hudson_slave".
This should setup a connection without prompting for a password.
- Copy the slave agent "slave.jar" to /space/hudson. The jar file
can be obtained from the archive "hudson.war" which has been downloaded
to setup the Hudson master. The hudson.war file may be downloaded from
the site http://hudson.dev.java.net. - Write a small shell script which sets the various paths and starts
the slave agent. Name it runSlave.sh. A typical script file would be
like:- cat /space/hudson/runSlave.sh
- echo "Starting the slave agent on the node XYZ…"
- export JAVA_HOME=/space/hudson/jdks/jdk1.6.0_06
- export ANT_HOME=/space/hudson/ant/apache-ant-1.7.1
- export PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
- java -jar slave.jar
- echo "Slave agent started…"
- This shell script would be called by the Hudson master. Running
the script directly would not start the slave agent, this gets started
only when run from the Hudson master.
- This shell script would be called by the Hudson master. Running
- Register this slave machine with the Hudson master in the "Manage Hudson" page.
You have your Hudson Master/Slave configuration ready. Now, you could just go ahead and define, configure and schedule your jobs to run according to your choice.
In case you have any queries you could consider sending a mail to the Hudson user’s mailing list – users@hudson.dev.java.net which is a pretty active mailing list.
August 26, 2009
Jersey Test Framework re-visited!
One of the previous entries introduced the Jersey Test Framework, which has since been adopted and used by a good number of developers. However, there has been some feedback suggesting ways for making the framework a better one.
Based on all this feedback, we have worked on making some changes in the framework. With the release of Jersey 1.1.2-ea, we have this new version of the framework which is better than the previous version in the following ways:
- Introduced the concept of test container factories
- Various test container types, defined by the different test container factory implementations
- Support for the new In-Memory or In-Process test container
- Loosely-coupled with the test container factory implementations
- Loose coupling allows the definition and pluggability of custom test container factory implementations
- Support for running tests on an application pre-deployed on an external container
But, there have been some major changes in the API, which seemed obvious for the cause.
This entry will describe what are the API changes, and how an user test can be defined, etc.
Breaking changes from 1.1.1-ea to
1.1.2-ea
- The maven project groupId has changed from
“com.sun.jersey.test.framework” to “com.sun.jersey”.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-test-framework</artifactId>
<version>1.1.2-ea</version>
<dependency>
- The extending of Jersey unit test and configuration has changed.
The test class has to just pass an instance of AppDescriptor. For instance, the constructor of the spring-annotations sample test, passes this information as follows:
public SpringAnnotationsWebAppTest() throws Exception {
super(new WebAppDescriptor.Builder("com.sun.jersey.samples.springannotations.resources.jerseymanaged")
.contextPath("spring")
.contextParam("contextConfigLocation", "classpath:applicationContext.xml")
.servletClass(SpringServlet.class)
.contextListenerClass(ContextLoaderListener.class)
.build());
}
Note the use of the Builder design pattern, which makes it really easy to define an instance of the AppDescriptor while defining all the application attributes.
- The test container type with which to run the tests has to be specified using the System Property test.containerFactory. Note that it used to be container.type till the previous version.
- Unlike the previous implementation, the test container type value is not a string which maps to the container type, but the fully qualified class name of the test container factory is passed as value for the property test.containerFactory.
mvn test -Dtest.containerFactory=com.sun.jersey.test.framework.spi.container.grizzly.web.GrizzlyWebTestContainerFactory
About the AppDescriptor
AppDescriptor is an abstract class which is extended by two classes – the LowLevelAppDescriptor and the WebAppDescriptor. These classes allow the definition of the various attributes of the application – like its
context-path, url-pattern, root resource classes or packages, etc. While the LowLevelAppDescriptor can be used is cases were tests are to be run on light-weight containers like Grizzly or HTTPServer, the WebAppDescriptor is used in cases where tests could be run on the web-based containers like EmbeddedGlassFish, Grizzly Web Container, and the light-weight containers as well*.
Test Container Factories
The test framework comes with a set of test container factory implementations which are responsible for creating the test container(s).
The following low-level test container factories are provided:
GrizzlyTestContainerFactoryfor testing with the low-level
Grizzly HTTP container.HTTPContainerFactoryfor testing with the Light Weight HTTP
server distributed with Java SE 6.InMemoryTestContainerFactoryfor testing in memory without
using underlying HTTP client and server side functionality
to send requests and receive responses.
The following Web-based test container factories are provided:
GrizzlyWebTestContainerFactoryfor testing with the Grizzly
Web container and Servlet support.EmbeddedGlassFishTestContainerFactoryfor testing with
embedded GlassFish.ExternalTestContainerFactoryfor testing when the Web
application is independently deployed in a separate JVM to that of the
tests. For example, the application may be deployed to the
Glassfish v2 or v3 application server.
Running Tests using Maven
As previously said, the container on which the tests have to be run is specified using the system property test.containerFactory which holds the fully-qualified classname of the test container factory which creates an instance of the test container, i.e.,
mvn clean test -Dtest.containerFactory=<container-factory fully-qualified class name>
Note:
1. If tests are to be run on external container like GlassFish, the application has to be explicity deployed on the container before running the tests.
a. Package the application:
mvn clean package -Dmaven.test.skip=true
b. Deploy the generated application war file
c. Run the tests:
mvn test -Dtest.containerFactory=com.sun.jersey.test.framework.spi.container.external.ExternalTestContainerFactory
2. If the tests are to be run on EmbeddedGlassFish, one additional property container.type has to be set along with test.containerFactory:
mvn clean test -Dtest.containerFactory=com.sun.jersey.test.framework.spi.container.embedded.glassfish.EmbeddedGlassFishTestContainerFactory -Dcontainer.type=EmbeddedGF
3. If the property test.containerFactory is not set, the tests would be run on the Grizzly Web container by default.
Enable Logging
The framework allows the logging of the HTTP requests and responses being sent over the wire during the test process. All that is needed to enable this logging is set the flag enableLogging.
mvn clean test -Dtest.containerFactory=<test container factory class> -DenableLogging
Programmatically setting the test container factory
The framework also allows setting the test container factory programmatically. This could be done by overriding the JerseyTest class’s getTestContainerFactory method and returning the appropriate test container factory’s instance. For example if Grizzly Web container has to be set as the default test container factory, it could be done as follows:
@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
That’s a brief description of the new version of the Jersey Test Framework. Please send an email to the Jersey user’s mailing list users@jersey.dev.java.net in case you have any issues. Wish you a happy testing of your RESTful Web Services
May 18, 2009
Running the Jersey Webapp on Google App Engine
This entry describes how easy it is to get your Jersey web application running on Google App Engine.
For the illustration purpose lets see how we can deploy the simple Helloworld-Webapp Jersey sample on the Google App Engine.
Simple Steps:
- Download Google App Engine.
- Follow the installation instructions for installing the app engine on your machine. It isn’t really too much work, just unzip the bundle, and add its bin directory to your path.
- Download the Jersey helloworld-webapp sample, if you do not already have it.
- Create an XML file named appengine-web.xml, under WEB-INF parallel to the deployment descriptor web.xml. Google App Engine requires this file in the webapp’s WEB-INF directory, for it to be able to run the application.
- Copy the following content to the created appengine-web.xml file:
<?xml version="1.0" encoding="utf-8"?> <appengine-web-app xmlns="http://appengine.google.com/ns/1.0"> <application></application> <version>1</version> </appengine-web-app>
- Package the application using: mvn clean package -Dmaven.test.skip=true
- Deploy the application on Google App Engine using the command: dev_appserver.sh target/helloworld-webapp
- You will see the message which says server is running at http://localhost:8080/.
- In a web browser enter http://localhost:8080/helloworld. You see the application running.
That’s it. You got the Jersey application running on Google App Engine
April 17, 2009
Jersey Test Framework makes it easy!
Does your application have RESTful Web Services? Do you want to ensure that these services are working properly on a wide range of containers – both light weight and heavy weight ones?
Have you ever felt the need of an infrastructure setup, which you can use to test your services against all these containers without having to worry about things like deployment descriptors, etc? If so, you have a news. Jersey 1.0.3 got released day before yesterday, and it comes with a testing framework called the Jersey Test Framework.
The Jersey Test Framework currently allows you to run your tests on any of the following three light weight containers:
- Embedded GlassFish
- Grizzly Web Server
- Lightweight HTTP Server
The framework is built over JUnit 4.x using Maven.
How do I use the Jersey Test Framework?
Using the framework is simple. All that you will need is do this:
- Add the following dependency to your pom.xml:
- <dependency>
<groupId>com.sun.jersey.test.framework</groupId>
<artifactId>jersey-test-framework</artifactId>
<version>1.0.3</version>
<scope>test</scope>
</dependency> - Create a class which extends com.sun.jersey.test.framework.JerseyTest.
- Some minimal number of parameters need to be passed by the test class to the JerseyTest class. This can be done in one of the following ways:
- super(String rootResourcePackage): Pass the root resource package name to the super constructor. This constructor will then take care of initialising, starting and/or stopping the test container.
- super(String contextPath, String servletPath, String resourcePackageName): Pass the application context path, servlet path and root resource package name to the super constructor if you are working on a web application. Again this constructor will take care of initializing, starting and/or stopping the test container.
- super(): When you call the default no parameter super constructor, you still can pass the information to the JerseyTest class by creating an instance of the com.sun.jersey.test.framework.util.ApplicationDescriptor class, setting the parameters using the setter methods defined in that class. This has to be done in your test class’s constructor. Also, a call needs to be made to the JerseyTest class’s setupTestEnvironment(ApplicationDescriptor applicationDescriptor) method. This call would take care of the init, start and/stop of the test container.
- Annotate your test methods with the org.junit.Test annotation.
- The handles to com.sun.jersey.api.client.Client and com.sun.jersey.api.client.WebResource instances – client and webResource get inherited from the JerseyTest class. You can use them in your test methods for building URIs and sending HTTP requests.
- Run the tests using the maven command – mvn clean test. This will by default run the tests against the Grizzly Web Server. If you want to run the tests on the container of your choice, set the system property container.type with one of the following values:
- EmbeddedGF : Makes the tests run against Embedded GlassFish.
- GrizzlyWeb : Makes the tests run against the Grizzly Web container.
- HTTPServer : Makes the tests run against the Simple HTTP Server.
- The framework also provides an option of seeing the HTTP requests and responses sent over the wire. It could be done by just setting the system property enableLogging, i.e., if you want to see the request and response sent over the wire, while running tests against Embedded GlassFish, execute the following command:
- mvn clean test -Dcontainer.type=EmbeddedGF -DenableLogging
- And that’s it. You have got the framework working.
Are there any samples which are using this framework?
Some of the samples that come with the Jersey distribution have been modified to use this framework. These are:
You should try running tests of these samples and see how the test framework works. I’m sure you will like it
If you see some of these samples do not have a deployment descriptor, but still you are able to run the tests against Embedded GlassFish. This is because the framework generates a deployment descriptor on the fly in such cases.
Future Enhancements
It is being planned to support the following features in the coming versions:
- Support for external containers – GlassFish v2 and GlassFish v3
- Giving the user an option to specify the containers which his test doesn’t support.
If you have any queries or see any issues with the current implementation or feel there should be something more, please send an email to the Jersey user mailing list – users@jersey.dev.java.net
March 14, 2009
Cool Firefox AddOn: Poster
Here’s a cool utility for non-unix users, who have been looking for a curl like solution for sending HTTP requests with the various HTTP methods – GET, POST, PUT, DELETE, etc. It is the Firefox add-on Poster.
Poster is a developer tool for interacting with web services and other web
resources that lets you make HTTP requests, set the entity body, and
content type. This allows you to interact with web services and inspect
the results.
The add-on can be installed from https://addons.mozilla.org/en-US/firefox/addon/2691.
Once the add-on is installed, you will be able to see an icon P in the Firefox browser status bar.
![]()
Clicking this, would popup a Poster window, where you can enter the URL to which you want to send the HTTP request, set the HTTP method, set the request headers, any query parameters, etc.

Also, you will be able to view the response that is sent back.
This tool will be very useful at the time of development of RESTful Web Services.
Supported versions of Firefox: 1.5 – 3.0.*
In my opinion, this tool is even better that curl, thanks to the GUI. Moreover, it is pretty easy to learn and use, pretty much self-explanatory.
March 2, 2009
Jersey Client API in Action
In one of the previous entries we saw that Jersey provides a Client API for consuming RESTful Web Services. In this entry, we shall see how to use this API and consume the HelloWorld service.
Before we go ahead and create the client, lets overwrite the HelloResource class with the following code:
@Path("hello")
public class HelloResource {
/** Creates a new instance of HelloResource */
public HelloResource() {
}
/**
* Retrieves representation of an instance of
* mycompany.resources.HelloResource
* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
public String sayHello(@QueryParam ("name") String name) {
if ( name != null ) {
return "Hello " + name + "!";
}
return "Hello World!";
}
@GET
@Path("{name}")
@Produces("text/plain")
public String sayHello2(@PathParam ("name") String name) {
return "Hello " + name + "!";
}
}
Deploy the application, once this is done. As you see, what we have tried to do is to define two GET methods, one which reads the query parameter “name” and greets the user accordingly, while the other one reads “name” from the URI path segment and greets the user.
Create the Client Application
For the illustration purpose, let us create a simple console application, which uses the Jersey Client API to consume the service. Also, we will download the Jersey jar files and use them.
1. In the NetBeans IDE, create a new Java Application, by doing File > New Project > Java > Java Application.
2. Name the Java Application as HelloWorldClient and click the Finish button.
3. Download the required jar files – jersey-client.jar, jersey-core.jar and jsr311-api.jar, from the links mentioned in the Jersey dependencies page.
4. Add these jar files to the Project library, through Project Properties > Libraries > Add JAR/Folder.

5. Overwrite the main() method with the following code:
public static void main(String[] args) {
// Create Client and Handle to web resources
String BASE_URI = "http://localhost:8080/HelloWorldWebapp/resources";
Client client = Client.create();
WebResource webResource = client.resource(BASE_URI);
// send a GET request with Accept header set to "text/plain"
String response = webResource.path("hello").accept(MediaType.TEXT_PLAIN).get(String.class);
System.out.println(response);
// send GET request with a query parameter value for 'name'
response = webResource.path("hello").queryParam("name", "Pranabh").get(String.class);
System.out.println(response);
// send GET request to /hello without any query param
response = webResource.path("hello").get(String.class);
System.out.println(response);
// send GET request to /hello/{name}
response = webResource.path("hello").path("Ranjita").accept(MediaType.TEXT_PLAIN).get(String.class);
System.out.println(response);
// send a GET request and get the response encapsulate in ClientResponse
ClientResponse clientResponse = webResource.path("hello").get(ClientResponse.class);
System.out.println(clientResponse.getEntity(String.class));
}
6. The following import statements need to be added too:
import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import javax.ws.rs.core.MediaType;
7. Run the application and the following output is seen:
Hello World! Hello Pranabh! Hello World! Hello Ranjita! Hello World!
Lets Dig through the Code
We created an instance of WebResource using the methods in Client class. Then GET requests were sent to the resources by appending the resource identifier to the web resource handle. Also, in some cases the HTTP Accept header was set using the accept() method. However, in some cases we did not use the accept header, since “text/plain” is the default type.
Observe the way query parameter name is set in the second GET request. It is set with the value Pranabh, and the response for this request is the string Hello Pranabh!. Similarly, in the fourth GET request, we have passed the value Ranjita for the path segment variable name .
In the last GET request, we have tried to encapsulate the response in an instance of ClientResponse class instead of String.class as in the previous requests. From this ClientResponse instance we got the response as a String entity.
All we saw was sending the GET requests, similarly we could send POST, PUT and DELETE methods using the methods post( ), put( ) and delete( ) respectively.
February 19, 2009
Talk on REST at Sun Tech Days, Hyderabad, 2009
18th Feb 2009 will be one of the most memorable days in my life. It was the Day for which we have been eagerly waiting. It was the first day of Sun Tech Days@Hyderabad – 2009.
We had a session on REST scheduled late in the evening. Sudhir and myself reached the venue, Hyderabad International Convention Centre, better known as Novotel or Hitex, by 9:00 in the morning. The day began with keynote from James Gosling on hot technologies including RESTful Web Services. Then there were a couple of interesting sessions by Arun Gupta on Metro and GlassFish. And then at 6:00 in the evening, the session on REST, titled Connecting the World with REST, began.
Since this was the last session of the day, I was little bit worried, that not many delegates might turn around for the session, but there were a good number of them (somewhere around 600), who were there in the hall waiting for the session. This indeed showed REST is getting popular and that lot of people want to know about it.
Everything was setup and we got started. The session began with an introduction to REST, RESTful web services and how JAX-RS / Jersey are related to them, followed by a small demo illustrating how to create simple RESTful web services using Jersey and NetBeans. In the demo, we showed how to read path parameters and query paramters using the JAX-RS annotations @PathParam and @QueryParam. Also, we showed how to represent data in multiple representations like XML, JSON, plain-text, etc. We wanted to show how to use the Jersey Client API too, but could not show that because of time constraint.
Then it was the Q&A time. There were a lot of people who have worked / are working on SOAP web services, and hence there were a lot of questions. Few of them that I can recall of are:
- I have a SOAP web service. I want to convert it to a REST service. Is there a tool which does that? There were many questions related to this.
- How do I pass JSON data to my service?
- How is a REST service different from CORBA?
- How does Jersey produce data in XML / JSON representations from a JAXB annotated object?
- When should I go for REST and when should I go for SOAP?
- Is there a support for Security, Reliable-Messaging, etc?
- About the WADL file?
- If any tool were required for generating clients, as in SOAP?
- Would it be possible to consume a SOAP web service using Jersey Client API?
Also, there were many people who wanted to get started with Jersey, and wanted to know if there were some good references. I have pointed them to blogs, the Jersey project page and the main wiki page.