Search This Blog

Friday, October 5, 2012

JAX-RS 2.0 - Jersey 2.0 Preview - An Example


JAX-RS 2.0 spec has reached public review status. Implementors of the API have been hard at work. One among them is Jersey. I have a vested interest in Jersey as I use it at work and therefore wanted to keep up to date on the changes in JAX-RS 2.0 and Jersey 2.0 and thus this BLOG. Jersey 2.0 is not backward compatible with Jersey 1.0 per their site and is instead a major re-write to correctly handle the new specification. When working with a previous REST provider, I found that when they created a 2.0 version of their product, they did not care to be backward "sensitive". I did not say compatible but sensitive :-). Backward sensitivity IMHO is a way to provide new functionality and refactor of an existing API in a way that provides a gradual migration path of consumers of the API and not requiring an all or nothing upgrade.

When backward incompatible changes are made to API's without changing package names, then binary incompatibilities surface when both versions of the API are required within the same class loader system. These incompatibilities can be easily absorbed by small scale adopters who can easily ensure all dependencies are upgraded simultaneously and only the latest version of the API is present. This requirement of simultaneous upgrade is however an arduous challenge for larger and more complex deployments whose development and deployment windows are very separated. Sure that one can look at OSGI or write their own class loaders if they should choose to but I am too dull headed for such extravagance.

In short what I want to ensure with Jersey 2.0 is the following use case:

There are three Services (REST services running within a Servlet container) written in Jersey 1.X. Each of the Services have multiple consumers but we are currently interested in the following where Service A calls Service B and Service C using their respective clients. A Service client is nothing more than a friendly API/library wrapping Jersey Client calls that can be distributed to different consumers of the service.

For the sake of discussion, let us consider that Service B is upgraded to Jersey 2.0 but Service C is not. As part of the upgrade, the maintainers of Service B provide a client to consume the service which is written in Jersey 2.0 as well. Will the Service clients of Service B and Service C be able to co-exist and function in Service A? Does the fact that Service A has not been upgraded to Jersey 2.0 cause problems for the clients of Service B and Service C to function in the container? In addition, let us say that Service A also gets upgraded to Jersey 2.0, then will the Service client for C that is using Jersey 1.X be able to function within Service A? Clearly, one option is to provide multiple clients of the service, one for Jersey 1.X and a second for Jersey 2.0. The same is achievable but does involve additional work of development and maintainence. So the question remains, whether the compatibility discussed will hold true or not? The BLOG and example provided herewith will evaluate the same.

JAX-RS 2.0 and what to expect

Client API

With earlier versions of the JAX-RS, the specification only accounted for a Server Side API for RESTful calls. The same led to different implementors of the Server API such as Jersey and RESTEasy independently developing a client side API (See my BLOG post on REST Clients). JAX-RS 2.0 will contain a Client API to support the server side specification. The JAX-RS 2.0 Client API is a major incorporation of the Jersey 1.X client API.

Asynchronous Support on Client and Server side

Client Side asynchronous support will allow a request to be dispatched in a non-blocking manner with results made available asynchronously. On the server side, long running requests that are I/O bound can be dispatched away, thus releasing the Application server thread to service other requests.


The lack of validation of data received from Headers, Body etc is something that I whined about in a previous BLOG. JAX-RS 2.0 will provide support for validation of request data.

Filters and Handlers

JAX-RS 2.0 specification accounts for Client and Server Filters. As in the case of the Client API, where implementer's provided their own versions of these filters for the Client and Server. The JAX-RS 2.0 specification absorbs the same into its API. For a more detailed understanding of changes in JAX-RS 2.0, a read of Arun Gupta's blog is recommended. This BLOG will be leaning on the Notes Web Service example that I had previously utilized where Notes can be created, updated and deleted via a client.

Jersey 2.0 and HK2

In previous version of my examples, I have used either Spring or Guice for injecting dependencies into Resources. At the time of this BLOG, I could not find the Spring or Guice support and have therefore used what Jersey 2.0 natively uses for its dependency injection and service location needs, i.e., HK2. HK2 is based on JSR 330 standard annotations. In the following example, a service binder utilizes HK2 and binds interface contracts to implementors as shown below. This binder which is defined in a "service" maven module is then used in the web maven module to enable injection of the NotesService:
public class ServiceBinder implements Binder {
  public void bind(DynamicConfiguration config) {

 * Application class
public class NotesApplication extends ResourceConfig {
  public NotesApplication() {
    // Register different Binders
    addBinders(new ServiceBinder(), new JacksonBinder());

 * A Resource class injected with the Notes Service
public class NotesResource {
  private NotesService service; // Notes Service injection


As previously mentioned, JAX-RS 2.0 supports a client API and Jersey provides an implementation of the same. At the time of writing this BLOG, I could not find hookins for Apache HTTP Client and therefore will be using the standard HttpClient for HTTP calls.

Client Creation

The process of configuring a client and creating the same is very similar to Jersey 1.X.
// Configuration for the Client
ClientConfig config = new ClientConfig();

// Add Providers
config.register(new JacksonJaxbJsonProvider());
config.register(new LoggingFilter());

// Instantiate the Client using the Client Factory
Client  webServiceClient = ClientFactory.newClient(config);

Executing REST Request

With Jersey 1.X, a typical POST to create a Note would have looked like-
NoteResult result = client.resource(UriBuilder.fromUri(baseUri).path("/notes").build())
        .accept(MediaType.APPLICATION_XML).entity(note,  MediaType.APPLICATION_XML).post(NoteResult.class);
The same request using the JAX-RS 2.0 client looks like:
NotesResult result ="/notes").build())
        .request(MediaType.APPLICATION_XML) // Request instead of accept
        .post(Entity.entity(note, MediaType.APPLICATION_XML_TYPE), NoteResult.class);
The primary difference seems to be where the Resource is identified as "target" rather than "resource". There is no "accepts" method but is replaced with "request" for media type. The Entity is built from a Entity Builder method which returns an instance of Overall the API seems quite flowing and does not seem to conflict with the Jersey 1.X client API.

Server Changes

One of the changes I wanted to work with is the Validation but I do not believe the same has been fully implemented as yet. Apart from the Async support mentioned earlier, one area of interest for me  is the Filters and Name Binding feature of JAX-RS.

Name binding and Filter

For those who have used Jersey's ContainerRequest and ContainerResponse Filters, the JAX-RS 2.0 equivalents should be quite familiar. An example of a simple ContainerRequestFilter that logs header attributes is shown below:
public class LoggingFilter implements ContainerRequestFilter {
  private static final Logger LOG = Logger.getLogger(LoggingFilter.class);

  public void filter(ContainerRequestContext requestContext) throws IOException {
    MultivaluedMap<String, String> map = requestContext.getHeaders();;
The annotation @Loggable shown above is a custom one that I created to demonstrate the Name Binding features of JAX-RS 2.0 where a Filter or Handler can be associated with a Resource class, method or an invocation on the client. In short this means one has finer grained control over which methods/resources the filter or handler is made available to. The annotation @Loggable is shown below:
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Loggable {
With the above, if we wish to apply the LoggingFilter only to a specific method of a Resource, one simply has to annotate the method with @Loggable:
public class NotesResource {
  @Loggable // Will be logged
  public Response create(Note note) {

  @GET // No annotation @Loggable added
  public Note get(Long noteId) {
If one wanted to apply the filter on a global level, then Global Binding is used where annotating the filter or handler with @GlobalBinding makes it applicable to all resources of an application.

Asynchronous HTTP

This is where its time for fun, at least for me :-). With Servlet 3.0, one can utilize NIO features and thus free service threads from blocking IO Tasks. Jersey supports suspending the incoming connection and resuming it at a later time. On the client side, the ability to dispatch requests asynchronously is a convenience.

Fictitious Requirements of the Notes Service
  • Notes Client should be able to submit a large number of Notes for creation. The Service should not block the JVM Server thread while it waits to submit but instead should background the same. Client should be notified of a Task ID asynchronously when it becomes available.
  • Notes Client should be able to obtain the status of Note creation asynchronously. The Service should not block the JVM Server thread while waiting for task completion. Upon obtaining the task result, the client should be notified of the same.
  • Notes Client should be able to register a listener that is notified of Note Creation events from the server

Posting a list of Notes for Creation

A list of Notes are submitted to the resource to asynchronously create them. The call itself is asynchronous with a Task ID being delivered to the InvocationCallback when available. One could accomplish the same via an Executor Service etc but this feature simplifies the operation.
  public void submitAsync(List<Note> notes, InvocationCallback<Long> taskCallback) {"/notes/async").build())
        .post(Entity.entity(new NotesContainer(notes), MediaType.APPLICATION_XML), taskCallback);
On the server side, the AsyncNotesResource handles the POST as shown below:
  public void createAsync(@Suspended final AsyncResponse response, final NotesContainer notes) {

    QUEUE_EXECUTOR.submit(new Runnable() {
      public void run() {
        try {
          // This task of submitting notes can take some time
          Long taskId = notesService.asyncCreate(notes.getNotes());
"Submitted Notes for Creation successfully, resuming client connection with TaskId:"
            + taskId);
          // Resume the connection
        catch (InterruptedException e) {
          LOG.error("Waiting to submit notes creation interrupted", e);
One can also obtain a java.util.concurrent.Future using the API if desired.

Obtaining Result of Task Processing Asynchronously

The InvocationCallback of the POST request will be provided a Task ID. Using this Task ID, an asynchronous GET request can be dispatched to obtain the results of the task. As the task might not be completed at the time of the request, the client issues the request in an asynchronous manner and is provided the results of the task when available through the InvocationCallback.
 public void getAsyncNoteCreationResult(Long taskId,
    InvocationCallback<NotesResultContainer> resultCallback) {"/notes/async/" + taskId).build())
The Server resource as shown below will not block the JVM server thread but will background the process of obtaining the Task results and the backgrounded process will resume the client connection with the task result when available. Also a time out is set on the request, if the server is not able to respond within the alloted period of time, then a 503 response code is sent back with a "Retry-After" header set to 60 sec.
public void getTaskResult(@Suspended final AsyncResponse ar, @PathParam("taskId") final Long taskId) {"Received Request to Obtain Task Result for Task:" + taskId);
    ar.setTimeout(10000L, TimeUnit.MILLISECONDS);
    ar.setTimeoutHandler(new TimeoutHandler() {
      public void handleTimeout(AsyncResponse asyncResponse) {   
        // Respond with 503 with Retry-After header set to 60 seconds
        // when the service could become available.     
    QUEUE_EXECUTOR.submit(new Runnable() {

      @Override public void run() {
        try {
          // This call will block until results are available.
          List<Long> noteIds = notesService.getAysyncNoteCreationResult(taskId);

          NotesResultContainer resultContainer = new NotesResultContainer();
"Received Note Creation Result, resuming client connection");
        catch (InterruptedException ex) {
"Interrupted Cancelling Request", ex);
Server Sent Events

A Feature of Jersey, though I believe not to be really a feature of JAX-RS is the ability to listen to Server sent events. The same is accomplished by the client obtaining an instance of from the Service which then receives events published by the server. The channel is kept alive until disconnected. The Client code to obtain the EventProcessor is shown below:
   WebTarget target =
   // Register a reader for the Event Processor

   // Obtain an event Processor from the Service
   EventProcessor processor = target.request().get(EventProcessor.class);

   processor.process(new EventListener() {
     public void onEvent(InboundEvent inboundEvent) {
       Note inboundNote = inboundEvent.getData(Note.class);

       for (NoteListener listener : serverEventListeners) {
On the service end, a thread is started that will dispatch Note creation events to the channel.
  public EventChannel serverEvents() {
    final EventChannel channel = new EventChannel();
    new EventChannelThread(channel, notesService).start();

    return seq;
  public class EventChannelThread extends Thread {
     public void run() {
        // While loop jargon ommited for lack of real estate
        channel.write(new OutboundEvent.Builder().name("domain-progress")
                  .mediaType(MediaType.APPLICATION_XML_TYPE).data(Note.class, noteToDispatch).build());


Example Project

An example project can be downloaded from HERE.

As mentioned previously, the example uses the concept of CRUD as related to a Note. A multi-module maven project is provided herewith that demonstrates the Notes application as written with Jersey 1.X and Jersey 2.X. The Jersey 2.X version has some additional features such as ASYNC, Name Binding and Filter that are demonstrated. In addition, there is a compatibility-test project that evaluates the compatibility concerns that I had mentioned at the beginning of my BLOG. Please note that 2.0-SNAPSHOT of Jersey is being used. A brief description of the maven modules you will find in the example:
  • Notes-common: Contains Data transfer objects and common code used by the Jersey 1.X and Jersey 2.X applications
  • Notes-service: Contains Java classes that are functional services for managing the Notes.
  • Notes-jersey-1.X: Contains Client, Webapp and Integration test modules that demonstrate Jersey 1.X.
  • Notes-jersey-2.X: Contains Client, Webapp and Integration test modules that demonstrate Jersey 2.X features
In order to exercise the compatibility tests two test webapps are created, one using Jersey 1.X and the second using Jersey 2.0. The Notes-client's of Jersey 1.X and Jersey 2.X are exercised within both mentioned test webapps to check for compatibility problems.
The compatibility integration test invokes a resource "/compatibility" on a test web app that is developed using jersey. When the resource is invoked, both the Notes Jersey Clients are exercised to perform CRUD operations using RESTful calls to a Notes Web service Webapp. There are two versions of the test-jersey-webapp, one written in Jersey-1.X and the second in Jersey 2.0.

You can run the full suite of Integration tests merely by executing a "mvn install" from the root level of the project. If you wish to run individual tests, you can also drill down into the Notes-jersey-1.X and Notes-jersey-2.0 modules and execute the same command.

Compatibility Test Results

So can Jersey 2.0 and Jersey 1.X co-exist in the same class loader system? The answer seems to be "Yes" but with some effort. jersey-client-1.X.jar depends on jersey-core-1.X.jar. The latter bundles JAX-RS 1.X (*) packages in it. jersey-client-2.X depends on* packages that are part of JAX-RS 2.0 and therefore requires that JAX-RS API 2.0 is available.

If an application that is running Jersey 1.X wishes to utilize a Jersey 1.X and Jersey 2.X client to call other web services, it is best to upgrade the service in question. The reasoning for the same is best established by the following use case:

Consider the from jersey-core-1.X.jar:

public abstract class UriBuilder {
 public abstract UriBuilder uri(URI uri) throws IllegalArgumentException;

An implementation by Jersey of the same is com.sun.jersey.api.uri.UriBuilderImpl which is as included part of jersey-core-1.X.jar.

Now the JAX-RS 2.0 version of UriBuilder has additional abstract methods one of which is shown below:

public abstract class UriBuilder {
 public abstract UriBuilder uri(URI uri) throws IllegalArgumentException;

 // New Method Added as part of JAX-RS 2.0
 public abstract UriBuilder uri(String uri) throws IllegalArgumentException;
An implementation of the same is org.glassfish.jersey.uri.internal.JerseyUriBuilder.

When a UriBuilder is loaded, it is important that the implementation that defines all the abstract methods of UriBuilder is loaded. If not, one would get see an exception like:
The same problem could exist for other JAX-RS 2.0 classes for which Jersey 1.X does not have concrete implementations. As the JAX-RS 2.0 API has to exist in the classpath, one needs to ensure that JAX-RS 1.X API classes are not included as well.

The jersey-core-1.X.jar includes* packages from jax-rs 1.0 API. Re-bundling the jersey-core-1.X jar without these packages and including jersey 2.0 and jax-rs 2.0 API classes will always ensure that the API's have the latest and complete implementations.

In addition, the implementation of is responsible for instantiating a version of UriBuilder. If the Jersey 1.X version of RuntimeDelegate is chosen at runtime, then it will attempt to load com.sun.jersey.apu.uri.UriBuilderImpl which will not have the abstract methods defined as part or JAX-RS 2.0's UriBuilder. For this reason, the org.glassfish.jersey.server.internal.RuntimeDelegateImpl must be chosen so that the JAX-RS 2.0 implementation of UriBuilder, i.e., org.glassfish.jersey.uri.internal.JerseyUriBuilder is always created. The same is accomplished by defining in META-INF/services a file that contains a single line, org.glassfish.jersey.uri.internal.JerseyUriBuilder.

The compatiblity-test web applications exercise the above mentioned route in addition to including a custom version of jersey-core-1.X.jar which is nothing more than a version that is stripped of* java packages.

With the above changes, I found that my compatibility tests passed. Of course I am working under the assumption that the JAX-RS 2.0 API classes did not change method signatures in an incompatible way :-).


Overall I feel that the JAX-RS 2.0 implementation with the unification of the Client API is definitely a move in the right direction. Jersey 2.0-SNAPSHOT also seemed to work well from an API and implementation perspective. It is heartening to know that co-existence can be achieved using Jersey 1.X and Jersey 2.0.The Jersey folks have also stated that they will be providing a migration path for Jersey 1.X adopters which is really professional of them. Some work has already been done to that effect on their site.

On the Async features of JAX-RS 2.0, I see potential value on the server side with NIO. On the client side, I find the API to be a convenience. It is arguable that in a clustered stateless environment client side ASYNC might provide limited value.

I have not covered all JAX-RS 2.0 features but only those that have interested me. There are many changes and I might investigate the remaining come another day. Finally, if I have got some areas wrong or my understanding if flawed, I look forward to your corrections on the same.

UPDATE - An example of the released jersey 2/jax-rs 2.0 that uses Spring DI is now available


myxjtu said...

Thanks for the post. It is very interesting.

I tried to follow the sample. However, I run into errors when I tried to call the async web service. What I did is: I implemented a simple web service by following the following in sample code:

public void getTaskResult(@Suspended final AsyncResponse ar, @PathParam("taskId") final Long taskId) {...}

Then I call this service using the following code:
Client client = ClientFactory.newClient();
Response response ="http://localhost:9998").path("/taxonomy").build())

But I got the following error:

WARNING: The following warnings have been detected with resource and/or provider classes:
WARNING: A HTTP GET method, public void getXXXX(, MUST return a non-void type.

Oct 12, 2012 11:51:12 AM com.sun.jersey.spi.container.ContainerRequest getEntity
SEVERE: A message body reader for Java class, and Java type interface, and MIME media type application/octet-stream was not found.

I googled but still no clue. Do you have any hints? Thanks

Sanjay Acharya said...

If this is happening on the service end, make sure that you have glassfish jersey 2.0 dependencies available in the classpath. In addition, you do not want any of the jersey 1.X server side dependencies on the classpath.

myxjtu said...

Thanks Sanjay. I am following your sample code and have a few questions:

1. For the following code which starts Grizzly web server:
URI BASE_URI = URI.create("http://localhost:9998");
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI,
How can I setup configurations for the server, like time out, max-thread?

2. I did some testing on the async server code. it seems to me that: even with async web service, the number of threads created is also large. E.g., if I keep 500 concurrent connections for 90 seconds, the number of threads created is almost 10K. I am not sure if something is wrong. Here is the code that is used to count #threads:
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
int threadCount = threadBean.getThreadCount();

Sanjay Acharya said...

I don't know of the top of my head how to set up max threads etc on grizzly. You can check a support forum for the same.

On the async server code,how many of the threads are "Container" threads and how many are those spawned by your application?

Sway said...

I have the same problem. May I know how the problem was solved. the MIME error.