Tag Archives: HTTP

Asynchronous Rest Services With Jersey


Asynchronous Rest Services With Jersey

 

There are two major versions of Jersey : Jersey 1 (com.sun.jersey.*) and Jersey 2 (org.glassfish.jersey.*). Currently Jersey 2 is being used but internet has information on both of them and lot has changed between the two.

Jersey can be used with a servlet container such as Jetty Servlet Container, Grizzly Servlet Container and any Generic Servlet 3.x and 2.x containers (tomcat) OR HTTP container such as Grizzly, JDK HTTP Container, Simple HTTP Container, Jetty HTTP Container

2015-03-28 20_33_33-Clipboard

 

In Jersey, you can return domain objects such as Book or Collection of Books (see below image). This works fine when you don’t want to specify any response details such as HTTP headers or status codes.

Capture

You can write tests by extending the JerseyTest testing framework, In the below image, a test to get a book by passing path id and getting Collection of Books is used. Note that you cannot directly pass Collection<Book> because the de-serialization from JSON to Java Object/Data structure will not work. To make this work Jersey provides a GenericType which can be written as (new GenericType<Collection<Book>>(){});

Capture

Example of a POST Request: A post request requires entity to be instantiated.

Capture

 

Jackson

Jackson is a suite of data processing tools for java that support JSON, XML and other formats. Jersey by default comes with Moxy and we can switch to jackson by removing the dependency for moxy  (org.glassfish.jersey.media) and adding the Jackson Provider (Group ID: com.fasterxml.jackson.jaxrs).  Artifact Id can be jackson-jaxrs-json-provider and jackson-jaxrs-xml-provider. You can configure the Jackson Provider:

JacksonJsonProvider json = new JacksonJsonProvider();

json.configure(SerializationFeature.INDENT_OUTPUT,true);
register(json);

Capture

Jackson Annotations

Capture

 

Advertisements