April 3, 2014

Securing Tibco EMS

Posted in JMS tagged , , at 7:16 AM by bsnaresh

One can follow these steps to secure a queue in Tibco EMS 5.0:

  • Get into the TIBCO EMS admin cli:
    •       tibemsadmin -server “tcp://HOSTNAME:7222”
  • To enable security, authorization has to be enabled. This can be done as follows:
    •   set server authorization=enabled
  • Restart the Tibco EMS server.
  • Create a connection factory using the following command
    • create factory <Connection Factory Name>  generic
  • To make the ConnectionFactory accessible from remote hosts, add the following property:
    • addprop factory <Connection Factory Name> url=tcp://HOSTNAME:7222
  • Create queue using the following command:
    • create queue <QUEUE NAME>
  • Create a group of users who would be able to access the above queue:
    • create group <groupname>
  • Create a user who can be added to the above group:
    • create user <username>
  • Set a password to the above user:
    •  set password <username> <new password>
  •  Add this user to the created group
    •  add member <group name> <user to be added>
  • Grant permissions on the queue to the created group
    • grant queue <queuename> group=<groupname>  all
  • Enable authorization on this queue
    • addprop queue <queuename> secure


If working on Tibco EMS 8.0, thr url property needs to be set while creating the factory itself:

  • create factory <Connection Factory Name>  generic  url=tcp://HOSTNAME:7222

August 1, 2012

Dear Maven, please give correct error messages!!!

Posted in maven, misc tagged at 10:01 PM by bsnaresh

No doubt Maven is a great piece of work, but yes it comes with its own pain points.

Few of the common problems that most Maven users face, are the misleading error messages in case of build failures for some XYZ reason. But, please don’t go by these false error messages. The error message that you see in your console could be completely misleading in certain cases.

For instance, the following is an error message which I got while running my Maven build, and I realized that it was an erroneous message only after about a hour of investigation 😦

A required class was missing while executing org.apache.maven.plugins:maven-enforcer-plugin:1.0:display-info: org/apache/commons/lang/SystemUtils

When I go an and check out the local maven repo for the class, I do see the jar which has it. Only after googling around, and trying out various options did I realize that it is a nasty problem that one might face because of a corrupt local maven repository, or an upgrade from Maven 2.x to Maven 3.x. The solution like most issues that we see when we upgrade from Maven 2.x to Maven 3.x, is to clear off the local maven repo, and rerun the build. That is it!

BTW, here’s the log of my build failure, in case you come across this problem, you might just want to clear off the local maven repo and rerun your build.

mvn compile -e

[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects…
[INFO] ————————————————————————
[INFO] Building Jenkins TestLink Plugin 3.1.3-SNAPSHOT
[INFO] ————————————————————————
[INFO] — maven-enforcer-plugin:1.0:display-info (default) @ testlink —
[INFO] Maven Version: 3.0.4
[INFO] ————————————————————————
[INFO] ————————————————————————
[INFO] Total time: 2.724s
[INFO] Finished at: Wed Aug 01 21:19:02 IST 2012
[INFO] Final Memory: 16M/214M
[INFO] ————————————————————————
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.0:display-info (default) on project testlink: Execution default of goal org.apache.maven.plugins:maven-enforcer-plugin:1.0:display-info failed: A required class was missing while executing org.apache.maven.plugins:maven-enforcer-plugin:1.0:display-info: org/apache/commons/lang/SystemUtils
[ERROR] —————————————————–
[ERROR] realm = plugin>org.apache.maven.plugins:maven-enforcer-plugin:1.0
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/C:/Users/sbhimise/.m2/repository/org/apache/maven/plugins/maven-enforcer-plugin/1.0/maven-enforcer-plugin-1.0.jar
[ERROR] urls[1] = file:/C:/Users/sbhimise/.m2/repository/org/apache/maven/reporting/maven-reporting-api/2.0.9/maven-reporting-api-2.0.9.jar
[ERROR] urls[2] = file:/C:/Users/sbhimise/.m2/repository/org/apache/maven/doxia/doxia-sink-api/1.0-alpha-10/doxia-sink-api-1.0-alpha-10.jar
[ERROR] urls[3] = file:/C:/Users/sbhimise/.m2/repository/commons-cli/commons-cli/1.0/commons-cli-1.0.jar
[ERROR] urls[4] = file:/C:/Users/sbhimise/.m2/repository/org/codehaus/plexus/plexus-interactivity-api/1.0-alpha-4/plexus-interactivity-api-1.0-alpha-4.jar
[ERROR] urls[5] = file:/C:/Users/sbhimise/.m2/repository/org/codehaus/plexus/plexus-utils/1.5.8/plexus-utils-1.5.8.jar
[ERROR] urls[6] = file:/C:/Users/sbhimise/.m2/repository/commons-lang/commons-lang/2.3/commons-lang-2.3.jar
[ERROR] urls[7] = file:/C:/Users/sbhimise/.m2/repository/org/apache/maven/enforcer/enforcer-api/1.0/enforcer-api-1.0.jar
[ERROR] urls[8] = file:/C:/Users/sbhimise/.m2/repository/org/apache/maven/enforcer/enforcer-rules/1.0/enforcer-rules-1.0.jar
[ERROR] urls[9] = file:/C:/Users/sbhimise/.m2/repository/org/apache/maven/shared/maven-common-artifact-filters/1.2/maven-common-artifact-filters-1.2.jar
[ERROR] urls[10] = file:/C:/Users/sbhimise/.m2/repository/org/beanshell/bsh/2.0b4/bsh-2.0b4.jar
[ERROR] urls[11] = file:/C:/Users/sbhimise/.m2/repository/org/apache/maven/shared/maven-dependency-tree/1.2/maven-dependency-tree-1.2.jar
[ERROR] urls[12] = file:/C:/Users/sbhimise/.m2/repository/org/codehaus/plexus/plexus-i18n/1.0-beta-6/plexus-i18n-1.0-beta-6.jar
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import from realm ClassRealm[project>org.jenkins-ci.plugins:testlink:3.1.3-SNAPSHOT, parent: ClassRealm[maven.api, parent: null]]]
[ERROR] —————————————————–: org.apache.commons.lang.SystemUtils
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:1.0:display-info (default) on project testlink: Execution default of goal org.apache.maven.plugins:maven-enforcer-plugin:1.0:display-info failed: A required class was missing while executing org.apache.maven.plugins:maven-enforcer-plugin:1.0:display-info: org/apache/commons/lang/SystemUtils

November 30, 2009

The Nov’09 Changes in My Life

Posted in Uncategorized at 6:31 PM by bsnaresh

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

Posted in REST tagged , at 1:14 AM by bsnaresh

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 
  • 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

Posted in misc at 7:06 AM by bsnaresh

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
  • 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 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.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 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

    • 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.
  • 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!

Posted in REST at 6:53 AM by bsnaresh

   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

  • 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 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

Posted in misc at 2:37 AM by bsnaresh

       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="http://appengine.google.com/ns/1.0">
  6. Package the application using: mvn clean package -Dmaven.test.skip=true
  7. Deploy the application on Google App Engine using the command: dev_appserver.sh 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 🙂

April 17, 2009

Jersey Test Framework makes it easy!

Posted in REST at 6:11 AM by bsnaresh

   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 – users@jersey.dev.java.net

March 14, 2009

Cool Firefox AddOn: Poster

Posted in misc at 1:31 AM by bsnaresh

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

Posted in REST at 7:54 AM by bsnaresh

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;
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.

Next page