Java Jersey

From HaFrWiki
Jump to: navigation, search

Developing RESTful Web services that seamlessly support exposing your data in a variety of representation media types and abstract away the low-level details of the client-server communication is not an easy task without a good toolkit.
In order to simplify development of RESTful Web services and their clients in Java, a standard and portable JAX-RS API [1] [2] has been designed. Jersey RESTful Web Services framework is open source, production quality, framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation.

Jersey framework [3] is more than the JAX-RS Reference Implementation. Jersey provides it’s own API that extend the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development. Jersey also exposes numerous extension SPIs so that developers may extend Jersey to best suit their needs.

Jersey is documented [4] so please read the documentation! (KISS and RTFM).

JAX-RS

Java defines REST support via the Java Specification Request (JSR) 311 and is named JAX-RS (The Java API for RESTful Web Services). JAX-RS uses annotations to define the REST relevance of Java classes.

Jersey is the reference implementation for the JSR 311 specification. The Jersey implementation provides a library to implement Restful webservices in a Java servlet container.

On the server side Jersey provides a servlet implementation which scans predefined classes to identify RESTful resources. In your web.xml configuration file your register this servlet for your web application.
The Jersey implementation also provides a client library to communicate with a RESTful webservice.

The base URL of the servlet is:

http://your_domain:port/display-name/url-pattern/path_from_rest_class 

.

This servlet analyzes the incoming HTTP request and selects the correct class and method to respond to this request. This selection is based on annotations in the class and methods.

JAX-RS supports the creation of XML and JSON via the Java Architecture for XML Binding (JAXB).

JAX-RS Annotations

Annotation Description
@PATH(your_path) Sets the path to base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the web.xml configuration file.
@POST Indicates that the following method will answer to an HTTP POST request.
@GET Indicates that the following method will answer to an HTTP GET request.
@PUT Indicates that the following method will answer to an HTTP PUT request.
@DELETE Indicates that the following method will answer to an HTTP DELETE request.
@Produces(MediaType.TEXT_PLAIN[, more-types]) @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/plain") is produced. Other examples would be "application/xml" or "application/json".
@Consumes(type[, more-types]) @Consumes defines which MIME type is consumed by this method.
@PathParam Used to inject values from the URL into a method parameter. This way you inject, for example, the ID of a resource into the method to get the correct object.

Maven

Jersey is complete maven build. The following is tested for OS/X and should work on Linux/Unix. Assumed is that you have installed maven successful and also have the right location for the m2 libraries.

Creating a New Project from Maven Archetype

  1. Open Terminal
  2. Goto the directory where you wanna build the Jersey Simple Service (i.e. /Sources/Java/Jersey/Refmaven)
  3. Type:

<syntaxhighlight lang="bash"> mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false -DgroupId=com.example -DartifactId=simple-service -Dpackage=com.example -DarchetypeVersion=2.18 </syntaxhighlight> which should end-up with <syntaxhighlight lang="bash"> [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 15.289s [INFO] Finished at: Fri Jun 19 20:01:09 CEST 2015 [INFO] Final Memory: 13M/126M [INFO] ------------------------------------------------------------------------ $ </syntaxhighlight>

The results are:

  • A new simple-service project directory created in your current location.
  • Project build and management configuration is described in the pom.xml located in the project root directory.
  • Project sources are located under src/main/java.
  • Project test sources are located under src/test/java.
  • There are 2 classes in the project source directory in the com.example package:
    • The Main class is responsible for bootstrapping the Grizzly container as well as configuring and deploying the project's JAX-RS application to the container.
    • The MyResource class contains implementation of a simple JAX-RS resource.
    • The MyResourceTest class contains the Unit Test.

MyResource class

<syntaxhighlight lang="java" line start=1> package com.example;

import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType;

/**

* Root resource (exposed at "myresource" path)
*/

@Path("myresource") public class MyResource {

   /**
    * Method handling HTTP GET requests. The returned object will be sent
    * to the client as "text/plain" media type.
    *
    * @return String that will be returned as a text/plain response.
    */
   @GET
   @Produces(MediaType.TEXT_PLAIN)
   public String getIt() {
       return "Got it!";
   }

} </syntaxhighlight> A JAX-RS resource is an annotated POJO that provides so-called resource methods that are able to handle HTTP requests for URI paths that the resource is bound to [5].

MyResourceTest

<syntaxhighlight lang="java" line start=1> package com.example;

import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType;

/**

* Root resource (exposed at "myresource" path)
*/

@Path("myresource") public class MyResource {

   /**
    * Method handling HTTP GET requests. The returned object will be sent
    * to the client as "text/plain" media type.
    *
    * @return String that will be returned as a text/plain response.
    */
   @GET
   @Produces(MediaType.TEXT_PLAIN)
   public String getIt() {
       return "Got it!";
   }

} </syntaxhighlight>

Running the project

Run the project by issuing the following command interminal <syntaxhighlight lang="bash" line start="1"> $ mvn clean test </syntaxhighlight> Which results in <syntaxhighlight lang="bash" > Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS ... [INFO] ------------------------------------------------------------------------ </syntaxhighlight>

So the project has been verified to:

  • Compile without errors
  • Unit tests have been passed

Now execute in standalone mode: <syntaxhighlight lang="bash" line start="1"> $ mvn exec:java </syntaxhighlight> This results in a WADL [6] <syntaxhighlight lang="bash"> INFO: Started listener bound to [localhost:8080] Jun 20, 2015 7:42:59 PM org.glassfish.grizzly.http.server.HttpServer start INFO: [HttpServer] Started. Jersey app started with WADL available at http://localhost:8080/myapp/application.wadl Hit enter to stop it... </syntaxhighlight>

This informs you that the application has been started and it's WADL descriptor is available at http://localhost:8080/myapp/application.wadl URL.
You can retrieve the WADL content by executing a curl http://localhost:8080/myapp/application.wadl command in your console or by typing the WADL URL into your favorite browser.
You should get back an XML document in describing your deployed RESTful application in a WADL format. To learn more about working with WADL, check the Chapter 17, WADL Support chapter. <syntaxhighlight lang="xml" line> <application xmlns="http://wadl.dev.java.net/2009/02">

  <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.18 2015-06-05 02:28:21"/> 
  <doc xmlns:jersey="http://jersey.java.net/" jersey:hint="This is simplified WADL with user and core resources only. To get full WADL with extended resources use the query parameter detail. Link: http://localhost:8080/myapp/application.wadl?detail=true"/>
  <grammars/>
  <resources base="http://localhost:8080/myapp/">
  <resource path="myresource">
  <method id="getIt" name="GET">
      <response>
          <representation mediaType="text/plain"/>
      </response>
   </method>

</resource> </resources> </application> </syntaxhighlight> The last thing we should try before concluding this section is to see if we can communicate with our resource deployed at /myresource path.
We can again either type the resource URL in the browser or we can use curl: <syntaxhighlight lang="bash" line start="1"> $ curl http://localhost:8080/myapp/myresource Got it! </syntaxhighlight>

or for more information: <syntaxhighlight lang="bash" line start="1"> $ curl -i http://localhost:8080/myapp/myresource HTTP/1.1 200 OK Content-Type: text/plain Date: Sat, 20 Jun 2015 17:55:11 GMT Content-Length: 7

Got it! </syntaxhighlight>

Maven latest snapshot

Jersey project is built using Apache Maven software project build and management tool. All modules produced as part of Jersey project build are pushed to the Central Maven Repository.

Therefore it is very convenient to work with Jersey for any Maven-based project as all the released (non-SNAPSHOT) Jersey dependencies are readily available without a need to configure a special maven repository to consume the Jersey modules.

In case you want to depend on the latest SNAPSHOT versions of Jersey modules, the following repository configuration needs to be added to your Maven project pom: (HJMF: Does not work with my mvn version 3.1.1). <syntaxhighlight lang="xml" line start="1"> <repository>

   <id>snapshot-repository.java.net</id>
   <name>Java.net Snapshot Repository for Maven</name>
   <url>https://maven.java.net/content/repositories/snapshots/</url>
   <layout>default</layout>

</repository> </syntaxhighlight>

Tomcat

Before continuing you need to satisfy the requirements:

  • Download Jersey distribution as zip-file from the Jersey Download site.
  • Eclipse Web Tool Platform (WTP).
  • Web-container Tomcat

See for more details on Java web development with Eclipse WTP [7].

See also

top Implementations of JAX-RS include:[8]

HaFr-Wiki

HaFrWiki-REST-Links

Java projects

  • Glassfish, Java EE 7 Application Server
  • Grizzly, New I/O API (NIO) Framework helps to build scalable robust servers.

Reference

top

  1. Wikipedia JAX API WS, Java API for XML Webservices.
  2. Wikipedai JAX RS, Java API for RESTful WebServices
  3. Jersey Homepage, Jersey
  4. Jersey, Last documentation.
  5. JAX-RS Resources, Chapter 3, JAX-RS Application, Resources and Sub-Resources for a complete guide to JAX-RS resources.
  6. WADL: Web Application Description Language. Jersey contains support for WADL. WADL is a XML description of a deployed RESTful web application. It contains model of the deployed resources, their structure, supported media types, HTTP methods and so on. In a sense, WADL is a similar to the WSDL (Web Service Description Language) which describes SOAP web services. WADL is however specifically designed to describe RESTful Web resources. See Chapter 17. WADL Support.
  7. Vogella, Java Web developemnt with Eclise WTP
  8. Mark Little, A Comparison of JAX-RS Implementations