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
Comments:

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

Posted by Arun Gupta's Blog on November 30, 2008 at 10:31 PM PST #

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

Posted by Arun Gupta's Blog on December 03, 2008 at 11:12 PM PST #

saOL

Posted by dizi izle on February 21, 2009 at 01:27 AM PST #

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

Posted by çiçekçi on February 22, 2009 at 11:39 PM PST #

thax u arun gupta

Posted by sinema izle on March 07, 2009 at 07:34 AM PST #

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

www.can-bil.com
www.online-shopp.net

Posted by Ankara Bilgisayar Satış Teknoloji Mağazası Elektronik Alışveriş on March 14, 2009 at 07:32 PM PDT #

thanks

Posted by nikah şekeri on April 05, 2009 at 05:06 AM PDT #

thanks..

Posted by kelebek on April 25, 2009 at 07:22 PM PDT #

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

Posted by Arun Gupta's Blog on August 19, 2009 at 10:41 PM PDT #

Thanks a lot for this amazing blog.
I need HTTP authenication information to pass with this.How it will be implemented?

Posted by vijay sharma on April 27, 2010 at 04:24 PM PDT #

Vijay,

HTTP authentication with Jersey is explained at:

http://weblogs.java.net/blog/mhadley/archive/2008/03/authentication.html

Posted by Arun Gupta on May 06, 2010 at 01:50 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today