Thursday Nov 19, 2009

My Last Day@Sun

[Read More]

Thursday Nov 12, 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, 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= -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 HTTP 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.

Tuesday Nov 03, 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

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 hudson changes the password for user hudson
  • Login as hudson user
  • Create folder $HOME/jdks and install there jdk1.6.0
  • ssh-keygen -t rsa generate 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
  • 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.war to 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):
               # 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 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 file from the hidden folder ".ssh".
    • Close the FTP connection.
    • Copy this 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
  • Write a small shell script which sets the various paths and starts the slave agent. Name it A typical script file would be like:
    • cat /space/hudson/
    • 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.

  • 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 -  which is a pretty active mailing list.

Tuesday Aug 25, 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”. 
  • 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")
                .contextParam("contextConfigLocation", "classpath:applicationContext.xml")

           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:

The following Web-based test container factories are provided:

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>


           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:

    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  in case you have any issues. Wish you a happy testing of your RESTful Web Services :)       

Sunday May 17, 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:

  1. Download Google App Engine.
  2. 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.
  3. Download the Jersey helloworld-webapp sample, if you do not already have it.
  4. 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.
  5. Copy the following content to the created appengine-web.xml file:
    <?xml version="1.0" encoding="utf-8"?>
    <appengine-web-app xmlns="">
  6. Package the application using: mvn clean package -Dmaven.test.skip=true
  7. Deploy the application on Google App Engine using the command: target/helloworld-webapp
  8. You will see the message which says server is running at http://localhost:8080/.
  9. 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 :)

Thursday Apr 16, 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:

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:

  1. Add the following dependency to your pom.xml:
    • <dependency>
  2. Create a class which extends com.sun.jersey.test.framework.JerseyTest.
  3. 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.
  4. Annotate your test methods with the org.junit.Test annotation.
  5. 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.
  6. 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.
  7. 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
  8. 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:

  1. Support for external containers - GlassFish v2 and GlassFish v3
  2. 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 -

Friday Mar 13, 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

        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.

Sunday Mar 01, 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:

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
    public String sayHello(@QueryParam ("name") String name) {
        if ( name != null ) {
            return "Hello " + name + "!";
        return "Hello World!";
    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);

        // send GET request with a query parameter value for 'name'
        response = webResource.path("hello").queryParam("name", "Pranabh").get(String.class);

        // send GET request to /hello without any query param
        response = webResource.path("hello").get(String.class);

        // send GET request to /hello/{name}
        response = webResource.path("hello").path("Ranjita").accept(MediaType.TEXT_PLAIN).get(String.class);

        // send a GET request and get the response encapsulate in ClientResponse
        ClientResponse clientResponse = webResource.path("hello").get(ClientResponse.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;

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.

Thursday Feb 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:

  1. 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.
  2. How do I pass JSON data to my service?
  3. How is a REST service different from CORBA?
  4. How does Jersey produce data in XML / JSON representations from a JAXB annotated object?
  5. When should I go for REST and when should I go for SOAP?
  6. Is there a support for Security, Reliable-Messaging, etc?
  7. About the WADL file?
  8. If any tool were required for generating clients, as in SOAP?
  9. 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.

Sunday Feb 15, 2009

The Jersey Client API

                One of the distinguishing features of Jersey is its client API. The Jersey client API makes it really easy to consume the RESTful Web Services - send requests and get back response along with all the required entities. There are two variants of the API - one based on HttpUrlConnection and the other based on the Apache HTTP Client. The API docs (for Jersey version 1.0.2, latest as of the day) are available at:

Steps for consuming a service using the client API:

  • Get an instance of Client by either:
    1. Client client = Client.create(); for the HttpURLConnection based client, or
    2. ApacheHttpClient client = ApacheHttpClient.create(); for the ApacheHttpClient.
  • Get a handle to the resources using the resource(..) method as - WebResource webResource = client.resource(base_url_of_the_service); The base_url could be given either as a String or as
  • Set the relative path to the required resource using the path() method of the WebResource class
    • Something like webResource.path(path1).path(path2) - "path1" and "path2" are the path elements. Say, I have my web service running at the base URI http://myserver/base, and the resource is identified by http://myserver/base/resources/resource1, then we could set the path to resource using the above as - webResource.path("resources").path("resource1")
    • WebResource follows the builder design pattern for appending path elements to the request URI.
  • Methods mapping each of the four HTTP methods GET, POST, PUT and DELETE are provided. These are:
    • GET ==> get()
    • POST ==> post()
    • PUT ==> put()
    • DELETE ==> delete()
  • If you want to send a GET request to a resource, that can be done using this statement:
    • webResource.path(path1).path(path2).get(Class), where Class is the type of the variable in which the response is to be set to. For example, if the response is to be set to a String variable, it could be done by using  -                                                                                                  String reponse = webResource.path(path1).path(path2).get(String.class);
    • In general, the class is set to Response.class and the response is returned as an object of type com.sun.jersey.api.client.ClientResponse.
  • If you want to send a request with the Accept Header set to some mime-type, that can be done using the accept() method of the WebResource class as shown in the following statement:
    • webResource.path(path1).path(path2).accept(mime-type).get(Class)
  • On the other hand if you want to send some data of some mime-type, it could be achieved using the type() method of the WebResource class as shown in the following statement:
    • webResource.path(path1).path(path2).type(mime-type).post(Object);

     This gives a brief introduction to the Client API. In the next entry, we will use this API to send requests to the service(s) created in the previous entries which used PathParam and QueryParam.

Friday Feb 13, 2009

Making the URI dynamic

            "I have a resource which does something. I want the same thing to be done for another use case. The only thing that differs is some part of the identifier. Do I have to create one more resource for this requirement? Just wondering if there were a way where I could make the identifier dynamic and use the same resource for all such use cases?" - these are some of the common questions that most of the people working on REST get into, at one or the other time.

        Is there really a way, where the URI could be made dynamic??? And the answer is YES.

JAX-RS provides a way of making the URI of the resource dynamic. I know, the next question is HOW???

Lets see how this could be done by modifying the same HelloWorldWebApp developed in one of the previous entries:

  • Modify the @Path annotation given above the HelloResource class as follows:

          public class HelloResource {

  • Overwrite the sayHello method with the following:

            public String sayHello(@PathParam ("name") String name) {
                  return "Hello " + name + "!";        

  • Redeploy the application. Enter the URL http://localhost:8080/HelloWorldWebapp/resources/hello/Rama in a web browser, and you will see the response Hello Rama! . Change the Rama in the URL to Raja and you will see Hello Raja! .

So how is it happening?

   We see two new things here:

  • A different way of passing path information to the @Path annotation 
           The @Path annotation allows the inclusion of path elements which could be dynamically mapped at the time of invocation. Such elements are encoded in {}. The page from the JSR-311 spec describes how path matching is done when such path elements are used in a resource's path definition.
  • Another new annotation - @PathParam

             The @PathParam is another annotation from JAX-RS. This takes care of mapping a path identifier to a method parameter.

Accessing query parameters using @QueryParam

In this entry, we will use the HelloWorldWebApp created in the previous entry. We will modify the resource, so that it takes name of a person as a query parameter and greets him/her. If no name is provided, it will give the general Hello World! message.

   And here are the steps:  

  • Overwrite the previously implemented sayHello method with the following:

    public String sayHello(@QueryParam("name") String name) {
        if (name != null) {
            // if the query parameter "name" is there
            return "Hello " + name + "!";
        return "Hello World!";

  • Import the class
  • Redeploy the application and enter http://localhost:8080/HelloWorldWebapp/resources/hello?name=Rama in a browser. You will see that response Hello Rama!. If the query parameter name is not specified the response would be Hello World!.

So how does this work?

          Here we are using a new annotation @QueryParam. It is an annotation provided by the JAX-RS API. This annotation takes care of mapping a query parameter in a request to a method parameter.

           In this example, we have used this annotation to map the query parameter name to the method parameter name. When a request is sent for the resource with some query parameter value for name, it gets set to the method parameter. For this to happen, the query parameter needs to be mapped to the method parameter. This is done by prefixing the method parameter declaration with @QueryParam and specifying the query parameter name as a string parameter for the annotation. In our example, it is achieved by doing this:

public String sayHello(@QueryParam("name") String name) {

Creating Hello World Service using Jersey

   This blog entry shows how easy it is to build a Hello World RESTful Web Service using Jersey

Required Setup:

  1. Download latest version of NetBeans, if you do not already have it. NetBeans provides wizards for creating RESTful Web Service using Jersey.
  2. If you do not have GlassFish installed in your machine, install one which comes with NetBeans setup. We will use GlassFish for deployments (but, it can be deployed on other containers too).

We will create the simple HelloWorldService in the following steps:

  1. In the NetBeans IDE, create a new project by selecting the "Java Web > Web Application" wizard.
  2. Name the project as HelloWorldWebapp.
  3. Set the server to GlassFish v2 as shown in the snapshot, and say Finish:  Select GlassFish v2 from the servers
  4. Right click on the project in the left pane, and select "New" > "Other". Select New > Other from the menu
  5. In the "Choose File Type" dialog, select "Web Services" and "RESTful Web Services from Patterns". Select Web Serv ices > RESTful Web Service from Patterns
  6. Set the pattern to Singleton in the next screen.
  7. In the next screen, set the package name to mycompany.resources. Set path to hello, class name to HelloResource and MIME-type to text/plain. Click the Finish button.
  8. The wizard creates the HelloResource class which has methods annotated with @GET and @PUT.
  9. Modify the @GET annotated method name to sayHello() and add the statement return "Hello World! Jersey welcome you";
  10. Have a look at the generated web.xml: it has a mapping of the Jersey SPI defined servlet com.sun.jersey.spi.container.servlet.ServletContainer to the url-patterns /resources/\* .
  11. Deploy the application.
  12. In a browser, enter the URL http://localhost:8080/HelloWorldWebapp/resources/hello. It gives a response with the string Hello World! Jersey welcome you.
  13. These are the steps for creating a resource using NetBeans and Jersey. 

Overview of the generated resource class

           It can be seen that the generated class has some annotations over the method implementations and the class definition. Lets see what these annotations are and what they mean:

  • @Path("hello") : This annotation describes the path to the resource, i.e., any request with the path "hello" would be routed to this resource.
  • @GET: This annotation maps the method sayHello to the HTTP GET request sent to the HelloResource.
  • @Produces("text/plain"): This annotation describes the mime type of data, which can be produced by the resource. If a resource supports multiple representations of data, all the supported mime-types could be declared as an array of strings in the Produces annotation. For ex: @Produces({"text/plain", "application/xml"}) means that the resource is capable of serving requests which have the Accept header set to either text/plain or application/xml.
  • @Consumes("text/plain"): This annotation describes the mime type of data which a resource can consume. Similar to the Produces annotation if the resource is capable of consuming multiple representations of data, all these representations could be declared as an array of strings in the Consumes annotation.
  • @PUT: This annotation maps the annotated method to the HTTP PUT request sent to the resource.

In the next entries we will see how to use the other features provided by JAX-RS/Jersey to access Uri Parameters, Query Parameters, Client API, etc. Also we will see how to deploy the applications to light weight HTTPServer, GrizzlyWebContainer and EmbeddedGlassFish.

Thursday Dec 04, 2008

Introducing Jersey

Jersey is the open source production quality reference implementation of JAX-RS for building RESTful web services. Jersey provides an API for building and consuming RESTful web services.

Jersey is built, assembled and installed using Maven.

Jersey's runtime dependencies are categorized into the following:

  • Core server. The minimum set of dependences that Jersey requires for the server.

  • Core client. The minimum set of dependences that Jersey requires for the client.

  • Container. The set of container dependences. Each container provider has it's own set of dependences.

  • Entity. The set of entity dependencies. Each entity provider has it's own set of dependences.

  • Tools. The set of dependencies required for runtime tooling.

  • Spring. The set of dependencies required for Spring.

    More information on these dependencies is available at the Jersey dependencies page.

Tuesday Dec 02, 2008

One Year@Sun

Never did I imagine that I would join this company called Sun Microsystems, the place where Java was born. One fine day, a friend informed me of an open requirement with the Metro QA team, and then I applied for the same. Things went fine and I was offered the job. Sky was the limit of joy and excitement when I was told about my selection.

I joined the company on this same day of the last year, on the 3rd of Dec 2007...

I came with a lot of mixed feelings, happy at one end that I am joining the company which is a dream company for anyone in the Java world, and little bit worried about the new environment and new colleagues... Soon things went fine, I realized how helpful the team is.

One year at Sun has been a great learning experience....

I got an opportunity to learn and work on some hot technologies like Metro, Jersey. Not to mention the one-week trip to Prague, which was the first time I went abroad.

No doubt it is a great company to work at, a place where everyone is encouraged to come up with new ideas and implement them.


Naresh worked at Sun Microsystems for two years. During these two years he had worked on the Project Metro and Project Jersey.


« April 2014