November 26, 2008

TOTD #57: Jersey Client API – simple and easy to use

TOTD #56 explains how to create a RESTful Web service endpoint using Jersey and publish the resource using JSON representation. The blog entry showed how the endpoint can be accessed from a Web browser. This Tip Of The Day explains how to use Jersey Client APIs to invoke the published endpoint.

Lets get started!

  1. Create a new directory “./src/test/java/org/glassfish/samples”
  2. Add a test
    1. Add a template test file “AppTest.java” as shown below:

      package org.glassfish.samples;

      import junit.framework.Test;
      import junit.framework.TestCase;
      import junit.framework.TestSuite;

      /**
       * Unit test for simple App.
       */
      public class AppTest
          extends TestCase
      {
          /**
           * Create the test case
           *
           * @param testName name of the test case
           */
          public AppTest( String testName )
          {
              super( testName );
          }

          /**
           * @return the suite of tests being tested
           */
          public static Test suite()
          {
              return new TestSuite( AppTest.class );
          }

          /**
           * Rigourous Test :-)
           */
          public void testApp()
          {
              assertTrue(true);
          }
      }

    2. Add a new method “createResource()” as:
          private WebResource createResource() {
              Client client = Client.create();
              WebResource resource = client.resource(”http://localhost:8080/helloworld-webapp/webresources/myresource”);
              return resource;
          }

      This code creates a default instance of Jersey Client and creates a Web resource from that client for the URI passed as an argument.

    3. Change the implementation of “testApp()” method as:
              Greeting result = createResource().get(Greeting.class);
              assertTrue(result.greeting.equals(”Hi there!”));

      This invokes the GET method on the resource by passing specific type and compares the returned and expected value.

    4. Add the following “imports”:
      import com.sun.jersey.api.client.Client;
      import com.sun.jersey.api.client.WebResource;
    5. Copy “Greeting.java” from TOTD #56 to ”./src/test/java/org/glassfish/samples” directory.
  3. Run the test
    1. Deploy the endpoint as “mvn glassfish:run”.
    2. Run the test as “mvn test”. The following output is shown:
      ~/samples/jersey/helloworld-webapp >mvn test
      [INFO] Scanning for projects…
      [INFO] ————————————————————————
      [INFO] Building helloworld-webapp Jersey Webapp
      [INFO]    task-segment: [test]
      [INFO] ————————————————————————
      [INFO] [resources:resources]
      [INFO] Using default encoding to copy filtered resources.
      [INFO] [compiler:compile]
      [INFO] Nothing to compile – all classes are up to date
      [INFO] [resources:testResources]
      [INFO] Using default encoding to copy filtered resources.
      [INFO] [compiler:testCompile]
      [INFO] Compiling 1 source file to /Users/arungupta/samples/jersey/helloworld-webapp/target/test-classes
      [INFO] [surefire:test]
      [INFO] Surefire report directory: /Users/arungupta/samples/jersey/helloworld-webapp/target/surefire-reports

      ——————————————————-
       T E S T S
      ——————————————————-
      Running org.glassfish.samples.AppTest
      Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.587 sec

      Results :

      Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

      [INFO] ————————————————————————
      [INFO] BUILD SUCCESSFUL
      [INFO] ————————————————————————
      [INFO] Total time: 4 seconds
      [INFO] Finished at: Mon Nov 24 16:50:17 PST 2008
      [INFO] Final Memory: 18M/43M
      [INFO] ————————————————————————

  4. View request and response messages
    1. Change the implementation of “createResource()” method as (changes highlighted in bold):

              Client client = Client.create();
              WebResource resource = client.resource(”http://localhost:8080/helloworld-webapp/webresources/myresource”);
              resource.addFilter(new LoggingFilter());
              return resource;
    2. Running the tests as “mvn test” now shows the output, with request and response messages, as shown below:
      Running org.glassfish.samples.AppTest
      1 * Out-bound request
      1 > GET http://localhost:8080/helloworld-webapp/webresources/myresource
      1 >
      1 < 200
      1 < X-Powered-By: Servlet/2.5
      1 < Transfer-Encoding: chunked
      1 < Content-Type: application/json
      1 < Server: GlassFish/v3
      1 < Date: Tue, 25 Nov 2008 07:07:51 GMT
      1 <
      {”greeting”:”Hi there!”}
      1 * In-bound response
      Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.074 sec

Really easy!

Even though the APIs are used to invoke a RESTful endpoint deployed using Jersey but are very generic and can be used to invoke any RESTful endpoint. Paul’s blog explain in detail on the usage. You can also see how these APIs can be used to consume a service hosted using Apache Abdera.

com.sun.jersey.api.client, com.sun.jersey.api.client.config, and com.sun.jersey.api.client.filter packages documents all the classes that provide support for client-side communication with HTTP-based RESTful Web services.

Technorati: totd glassfish v3 embeddable jersey jsr311 rest json webservices

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot
Related posts:
  1. TOTD #56: Simple RESTful Web service using Jersey and Embeddable GlassFish – Text and JSON output
  2. TOTD #58: Jersey and GlassFish – how to process POST requests ?
  3. TOTD #10: Consuming JSON and XML representations generated by a Jersey endpoint in a jMaki Table widget
  4. TOTD #100: Getting Started with Scala Lift on GlassFish v3
  5. TOTD #8: Generating JSON using JAXB annotations in Jersey

9 Comments »

  1. [Trackback] Lets extend the Jersey endpoint (TOTD# 56) and client (TOTD# 57) such that it can accept a POST request and then invoke it. Add a new method to "MyResource.java" from TOTD# 56 as: &nbsp;&nbsp;&nbsp; @POST &nbsp;&nbsp;&nbsp; @Consumes("application/json…

    Comment by Arun Gupta's Blog — December 1, 2008 @ 6:31 am

  2. [Trackback] Today Sun announces the availability of Java FX 1.0. JavaFX 1.0 is a rich client platform for creating and delivering Rich Internet Applications across all screens (desktop, browser, and mobile) of your life. It consists of the following key…

    Comment by Arun Gupta's Blog — December 4, 2008 @ 7:12 am

  3. saOL

    Comment by dizi izle — February 21, 2009 @ 9:27 am

  4. paylaşım için çok teşekkürler başarılar diliyorum

    Comment by çiçekçi — February 23, 2009 @ 7:39 am

  5. thax u arun gupta

    Comment by sinema izle — March 7, 2009 @ 3:34 pm

  6. Thank u for this important article an code’s here. We wanna stab this :) .

    http://www.can-bil.com
    http://www.online-shopp.net

    Comment by Ankara Bilgisayar Satış Teknoloji Mağazası Elektronik Alışveriş — March 15, 2009 @ 2:32 am

  7. thanks

    Comment by nikah şekeri — April 5, 2009 @ 12:06 pm

  8. thanks..

    Comment by kelebek — April 26, 2009 @ 2:22 am

  9. [Trackback] GlassFish Monitoring allows you to monitor the state of various runtime components of the application server. This information is used to identify performance bottlenecks and tuning the system for optimal performance, to aid capacity planning, to pred…

    Comment by Arun Gupta's Blog — August 20, 2009 @ 5:41 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress
115664 visits from Sep 11, 2009