jersey Rest请求URI路径构造

https://jersey.java.net/nonav/documentation/latest/user-guide.html

Table of Contents

Preface 1. Getting Started
1.1. Creating a New Project from Maven Archetype 1.2. Exploring the Newly Created Project 1.3. Running the Project 1.4. Creating a JavaEE Web Application 1.5. Exploring Other Jersey Examples
2. Modules and dependencies
2.1. Java SE Compatibility 2.2. Introduction to Jersey dependencies 2.3. Common Jersey Use Cases
2.3.1. Servlet based application on Glassfish 2.3.2. Servlet based server-side application 2.3.3. Client application on JDK 2.3.4. Served side application on supported container
2.4. List of modules
3. JAX-RS Application, Resources and Sub-Resources
3.1. Root Resource Classes
3.1.1. @Path 3.1.2. @GET, @PUT, @POST, @DELETE, ... (HTTP Methods) 3.1.3. @Produces 3.1.4. @Consumes
3.2. Parameter Annotations (@*Param) 3.3. Sub-resources 3.4. Life-cycle of Root Resource Classes 3.5. Rules of Injection 3.6. Use of @Context 3.7. Programmatic resource model
4. Deploying a RESTful Web Service
4.1. Auto-Discoverable Features
4.1.1. Configuring the Feature Auto-discovery mechanism
5. Client API
5.1. Uniform Interface Constraint 5.2. Ease of use and reusing JAX-RS artifacts 5.3. Overview of the Client API
5.3.1. Getting started with the client API 5.3.2. Creating and configuring a Client instance 5.3.3. Targeting a web resource 5.3.4. Identifying resource on WebTarget 5.3.5. Invoking a HTTP request 5.3.6. Example summary
5.4. Java instances and types for representations
5.4.1. Adding support for new representations
5.5. Client Transport Connectors 5.6. Using client request and response filters 5.7. Securing a Client
5.7.1. HTTP Basic Authentication Support
6. Representations and Responses
6.1. Representations and Java Types 6.2. Building Responses 6.3. WebApplicationException and Mapping Exceptions to Responses 6.4. Conditional GETs and Returning 304 (Not Modified) Responses
7. JAX-RS Entity Providers
7.1. Introduction 7.2. How to Write Custom Entity Providers
7.2.1. MessageBodyWriter 7.2.2. MessageBodyReader
7.3. Entity Provider Selection 7.4. Jersey MessageBodyWorkers API 7.5. Default Jersey Entity Providers
8. Support for Common Media Type Representations
8.1. JSON
8.1.1. Approaches to JSON Support 8.1.2. MOXy 8.1.3. Java API for JSON Processing (JSON-P) 8.1.4. Jackson 8.1.5. Jettison 8.1.6. @JSONP - JSON with Padding Support
8.2. XML
8.2.1. Low level XML support 8.2.2. Getting started with JAXB 8.2.3. POJOs 8.2.4. Using custom JAXBContext 8.2.5. MOXy
8.3. Multipart
8.3.1. Overview 8.3.2. Client 8.3.3. Server
9. Filters and Interceptors
9.1. Introduction 9.2. Filters
9.2.1. Server filters 9.2.2. Client fillers
9.3. Interceptors 9.4. Filter and interceptor execution order 9.5. Name binding 9.6. Dynamic binding 9.7. Priorities
10. Asynchronous Services and Clients
10.1. Asynchronous Server API
10.1.1. Asynchronous Server-side Callbacks 10.1.2. Chunked Output
10.2. Client API
10.2.1. Asynchronous Client Callbacks 10.2.2. Chunked input
11. URIs and Links
11.1. Building URIs 11.2. Resolve and Relativize 11.3. Link
12. Programmatic API for Building Resources
12.1. Introduction 12.2. Programmatic Hello World example
12.2.1. Deployment of programmatic resources
12.3. Additional examples 12.4. Model processors
13. Server-Sent Events (SSE) Support
13.1. What are Server-Sent Events 13.2. When to use Server-Sent Events 13.3. Jersey Server-Sent Events API 13.4. Implementing SSE support in a JAX-RS resource
13.4.1. Simple SSE resource method 13.4.2. Broadcasting with Jersey SSE
13.5. Consuming SSE events with Jersey clients
13.5.1. Reading SSE events with EventInput 13.5.2. Asynchronous SSE processing with EventSource
14. Security
14.1. Securing server
14.1.1. SecurityContext 14.1.2. Authorization - securing resources
14.2. Client Security 14.3. OAuth
15. WADL Support
15.1. WADL introduction 15.2. Configuration 15.3. Extended WADL support
16. Bean Validation Support
16.1. Bean Validation Dependencies 16.2. Enabling Bean Validation in Jersey 16.3. Configuring Bean Validation Support 16.4. Validating JAX-RS resources and methods
16.4.1. Constraint Annotations 16.4.2. Annotation constraints and Validators 16.4.3. Entity Validation 16.4.4. Annotation Inheritance
16.5. @ValidateOnExecution 16.6. Injecting 16.7. Error Reporting
16.7.1. ValidationError
16.8. Example
17. MVC Templates
17.1. Dependencies 17.2. Registration and Configuration 17.3. Explicit vs. Implicit View Templates
17.3.1. Viewable - Explicit View Templates 17.3.2. @Template - Implicit View Templates
17.4. JSP 17.5. Custom Templating Engines 17.6. Other Examples
18. Jersey Test Framework
18.1. Basics 18.2. Supported Containers 18.3. Advanced features
18.3.1. JerseyTest Features 18.3.2. External container 18.3.3. Test Client configuration 18.3.4. Accessing the logged test records programmatically
19. Building and Testing Jersey
19.1. Checking Out the Source 19.2. Building the Source 19.3. Testing 19.4. Using NetBeans
20. Migrating from Jersey 1.x
20.1. Server API
20.1.1. Injecting custom objects 20.1.2. ResourceConfig Reload 20.1.3. MessageBodyReaders and MessageBodyWriters ordering
20.2. Migrating Jersey Client API
20.2.1. Making a simple client request 20.2.2. Registering filters 20.2.3. Setting "Accept" header 20.2.4. Attaching entity to request 20.2.5. Setting SSLContext and/or HostnameVerifier
A. Configuration Properties
A.1. Common (client/server) configuration properties A.2. Server configuration properties A.3. Client configuration properties

List of Examples

3.1.  Simple hello world root resource class 3.2.  Specifying URI path parameter 3.3.  PUT method 3.4.  Specifying output MIME type 3.5.  Using multiple output MIME types 3.6.  Server-side content negotiation 3.7.  Specifying input MIME type 3.8.  Query parameters 3.9.  Custom Java type for consuming request parameters 3.10.  Processing POSTed HTML form 3.11.  Obtaining general map of URI path and/or query parameters 3.12.  Obtaining general map of header parameters 3.13.  Obtaining general map of form parameters 3.14.  Example of the bean which will be used as @BeanParam 3.15.  Injection of MyBeanParam as a method parameter: 3.16.  Injection of more beans into one resource methods: 3.17.  Sub-resource methods 3.18.  Sub-resource locators 3.19.  Sub-resource locators with empty path 3.20.  Sub-resource locators returning sub-type 3.21.  Sub-resource locators created from classes 3.22.  Sub-resource locators returning resource model 3.23.  Injection 3.24.  Wrong injection into a singleton scope 3.25.  Injection of proxies into singleton 3.26.  Example of possible injections 4.1.  Deployment agnostic application model 4.2.  Reusing Jersey implementation in your custom application model 4.3.  Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0 4.4.  Configuration of maven-war-plugin in pom.xml with Servlet 3.0 4.5.  Deployment of a JAX-RS application using web.xml with Servlet 3.0 4.6.  Deployment of your application using Jersey specific servlet 4.7.  Using Jersey specific servlet without an application model instance 5.1.  POST request with form parameters 5.2.  Using JAX-RS Client API 5.3.  Using JAX-RS Client API fluently 6.1.  Using File with a specific media type to produce a response 6.2.  Returning 201 status code and adding Location header in response to POST request 6.3.  Adding an entity body to a custom response 6.4.  Throwing exceptions to control response 6.5.  Application specific exception implementation 6.6.  Mapping generic exceptions to responses 6.7.  Conditional GET support 7.1.  Example resource class 7.2.  MyBean entity class 7.3.  MessageBodyWriter example 7.4.  Example of assignment of annotations to a response entity 7.5.  Client code testing MyBeanMessageBodyWriter 7.6.  Result of MyBeanMessageBodyWriter test 7.7.  MessageBodyReader example 7.8.  Testing MyBeanMessageBodyReader 7.9.  Result of testing MyBeanMessageBodyReader 7.10.  MessageBodyReader registered on a JAX-RS client 7.11.  Result of client code execution 7.12.  Usage of MessageBodyWorkers interface 8.1.  Simple JAXB bean implementation 8.2.  JAXB bean used to generate JSON representation 8.3.  Tweaking JSON format using JAXB 8.4.  JAXB bean creation 8.5.  Constructing a JsonObject (JSON-Processing) 8.6.  Constructing a JSONObject (Jettison) 8.7.  MoxyJsonConfig - Setting properties. 8.8.  ContextResolver<MoxyJsonConfig> 8.9.  Setting properties for MOXy providers into Configurable 8.10.  Building client with MOXy JSON feature enabled. 8.11.  Creating JAX-RS application with MOXy JSON feature enabled. 8.12.  Building client with JSON-Processing JSON feature enabled. 8.13.  Creating JAX-RS application with JSON-Processing JSON feature enabled. 8.14.  ContextResolver<ObjectMapper> 8.15.  Building client with Jackson JSON feature enabled. 8.16.  Creating JAX-RS application with Jackson JSON feature enabled. 8.17.  JAXB beans for JSON supported notations description, simple address bean 8.18.  JAXB beans for JSON supported notations description, contact bean 8.19.  JAXB beans for JSON supported notations description, initialization 8.20.  XML namespace to JSON mapping configuration for Jettison based mapped notation 8.21.  JSON expression with XML namespaces mapped into JSON 8.22.  JSON expression produced using badgerfish notation 8.23.  ContextResolver<ObjectMapper> 8.24.  Building client with Jettison JSON feature enabled. 8.25.  Creating JAX-RS application with Jettison JSON feature enabled. 8.26.  Simplest case of using @JSONP 8.27.  JaxbBean for @JSONP example 8.28.  Example of @JSONP with configured parameters. 8.29.  Low level XML test - methods added to HelloWorldResource.java 8.30.  Planet class 8.31.  Resource class 8.32.  Method for consuming Planet 8.33.  Resource class - JAXBElement 8.34.  Client side - JAXBElement 8.35.  PlanetJAXBContextProvider 8.36.  Using Provider with JAX-RS client 8.37.  Add jersey-media-moxy dependency. 8.38.  Register the MoxyXmlFeature class. 8.39.  Configure and register an MoxyXmlFeature instance. 8.40.  Building client with MultiPart feature enabled. 8.41.  Creating JAX-RS application with MultiPart feature enabled. 8.42.  MultiPart entity 8.43.  MultiPart entity in HTTP message. 8.44.  FormDataMultiPart entity 8.45.  FormDataMultiPart entity in HTTP message. 8.46.  Multipart - sending files. 8.47.  Resource method using MultiPart as input parameter / return value. 8.48.  Use of @FormDataParam annotation 9.1.  Container response filter 9.2.  Container request filter 9.3.  Pre-matching request filter 9.4.  Client request filter 9.5.  GZIP writer interceptor 9.6.  GZIP reader interceptor 9.7.  @NameBinding example 9.8.  Dynamic binding example 9.9.  Priorities example 10.1.  Simple async resource 10.2.  Simple async method with timeout 10.3.  CompletionCallback example 10.4.  ChunkedOutput example 10.5.  Simple client async invocation 10.6.  Simple client fluent async invocation 10.7.  Client async callback 10.8.  Client async callback for specific entity 10.9.  ChunkedInput example 11.1.  URI building 11.2.  Building URIs using query parameters 12.1.  A standard resource class 12.2.  A programmatic resource 12.3.  A programmatic resource 12.4.  A programmatic resource 12.5.  A programmatic resource 12.6.  A programmatic resource 13.1.  Simple SSE resource method 13.2.  Broadcasting SSE messages 13.3.  Registering EventListener with EventSource 13.4.  Overriding EventSource.onEvent(InboundEvent) method 14.1.  Accessing SecurityContext 14.2.  Injecting SecurityContext into a singleton resource 14.3.  Injecting SecurityContext into singletons 14.4.  Registering RolesAllowedDynamicFeature using ResourceConfig 14.5.  Injecting SecurityContext into singletons 15.1.  A simple WADL example - JAX-RS resource definition 15.2.  A simple WADL example - WADL content 15.3.  OPTIONS method returning WADL 15.4.  More complex WADL example - JAX-RS resource definition 15.5.  More complex WADL example - WADL content 16.1.  Configuring Jersey specific properties for Bean Validation. 16.2.  Using ValidationConfig to configure Validator. 16.3.  Constraint annotations on input parameters 16.4.  Constraint annotations on fields 16.5.  Constraint annotations on class 16.6.  Definition of a constraint annotation 16.7.  Validator implementation. 16.8.  Entity validation 16.9.  Entity validation 2 16.10.  Response entity validation 16.11.  Validate getter on execution 16.12.  Injecting UriInfo into a ConstraintValidator 16.13.  Support for injecting Jersey's resources/providers via ConstraintValidatorFactory. 16.14.  ValidationError to text/plain 16.15.  ValidationError to text/html 16.16.  ValidationError to application/xml 16.17.  ValidationError to application/json 17.1.  Registering MvcFeature 17.2.  Registering JspMvcFeature 17.3.  Setting MvcProperties.TEMPLATE_BASE_PATH value in ResourceConfig 17.4.  Setting FreemarkerMvcProperties.TEMPLATE_BASE_PATH value in web.xml 17.5.  Using Viewable in a resource class 17.6.  Using absolute path to template in Viewable 17.7.  Using @Template on a resource class 17.8.  Custom TemplateProcessor 17.9.  Registering custom TemplateProcessor 20.1.  Jersey 1 reloader implementation 20.2.  Jersey 1 reloader registration 20.3.  Jersey 2 reloader implementation 20.4.  Jersey 2 reloader registration

Preface

This is user guide for Jersey 2.0. We are trying to keep it up to date as we add new features. When reading the user guide, please consult also our Jersey API documentation as an additional source of information about Jersey features and API.

If you would like to contribute to the guide or have questions on things not covered in our docs, please contact us atusers@jersey.java.net. Similarly, in case you spot any errors in the Jersey documentation, please report them by filing a new issue in our Jersey JIRA Issue Tracker under docs component. Please make sure to specify the version of the Jersey User Guide where the error has been spotted by selecting the proper value for the Affected Version field.

Text formatting conventions

First mention of any Jersey and JAX-RS API component in a section links to the API documentation of the referenced component. Any sub-sequent mentions of the component in the same chapter are rendered using a monospace font.

Emphasised font is used to a call attention to a newly introduce concept, when it first occurs in the text.

In some of the code listings, certain lines are too long to be displayed on one line for the available page width. In such case, the lines that exceed the available page width are broken up into multiple lines using a '\' at the end of each line to indicate that a break has been introduced to fit the line in the page. For example:

This is an overly long line that \
might not fit the available page \
width and had to be broken into \
multiple lines.

This line fits the page width.
                

Should read as:

This is an overly long line that might not fit the available page width and had to be broken into multiple lines.

This line fits the page width.
                

Chapter 1. Getting Started

This chapter provides a quick introduction on how to get started building RESTful services using Jersey. The example described here uses the lightweight Grizzly HTTP server. At the end of this chapter you will see how to implement equivalent functionality as a JavaEE web application you can deploy on any servlet container supporting Servlet 2.5 and higher.

1.1. Creating a New Project from Maven Archetype

Jersey project is build 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.

Note

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:

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

Since starting from a Maven project is the most convenient way for working with Jersey, let's now have a look at this approach. We will now create a new Jersey project that runs on top of a Grizzly container. We will use a Jersey-provided maven archetype. To create the project, execute the following Maven command in the directory where the new project should reside:

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

Feel free to adjust the groupIdpackage and/or artifactId of your new project. Alternatively, you can change it by updating the new project pom.xml once it gets generated.

1.2. Exploring the Newly Created Project

Once the project generation from a Jersey maven archetype is successfully finished, you should see the new simple-service project directory created in your current location. The directory contains a standard Maven project structure:

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. Another class in the same package is MyResource class, that contains implementation of a simple JAX-RS resource. It looks like this:

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!";
    }
}

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. SeeChapter 3, JAX-RS Application, Resources and Sub-Resources for a complete guide to JAX-RS resources. In our case, the resource exposes a single resource method that is able to handle HTTP GET requests, is bound to /myresource URI path and can produce responses with response message content represented in "text/plain"media type. In this version, the resource returns the same "Got it!" response to all client requests.

The last piece of code that has been generated in this skeleton project is a MyResourceTest unit test class that is located in the same com.example package as theMyResource class, however, this unit test class is placed into the maven project test source directory src/test/java (certain code comments and JUnit imports have been excluded for brevity):

package com.example;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;

import org.glassfish.grizzly.http.server.HttpServer;

...

public class MyResourceTest {

    private HttpServer server;
    private WebTarget target;

    @Before
    public void setUp() throws Exception {
        server = Main.startServer();

        Client c = ClientBuilder.newClient();
        target = c.target(Main.BASE_URI);
    }

    @After
    public void tearDown() throws Exception {
        server.stop();
    }

    /**
     * Test to see that the message "Got it!" is sent in the response.
     */
    @Test
    public void testGetIt() {
        String responseMsg = target.path("myresource").request().get(String.class);
        assertEquals("Got it!", responseMsg);
    }
}

In this unit test, a Grizzly container is first started and server application is deployed in the test setUp() method by a static call to Main.startServer(). Next, a JAX-RS client components are created in the same test set-up method. First a new JAX-RS client instance c is built and then a JAX-RS web target component pointing to the context root of our application deployed at http://localhost:8080/myapp/ (a value of Main.BASE_URI constant) is stored into a target field of the unit test class. This field is then used in the actual unit test method (testGetIt()).

In the testGetIt() method a fluent JAX-RS Client API is used to connect to and send a HTTP GET request to the MyResource JAX-RS resource class listening on/myresource URI. As part of the same fluent JAX-RS API method invocation chain, a response is read as a Java String type. On the second line in the test method, the response content string returned from the server is compared with the expected phrase in the test assertion. To learn more about using JAX-RS Client API, please see theChapter 5, Client API chapter.

1.3. Running the Project

Now that we have seen the content of the project, let's try to test-run it. To do this, we need to invoke following command on the command line:

mvn clean test

This will compile the project and run the project unit tests. We should see a similar output that informs about a successful build once the build is finished:

Results :

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

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 34.527s
[INFO] Finished at: Sun May 26 19:26:24 CEST 2013
[INFO] Final Memory: 17M/490M
[INFO] ------------------------------------------------------------------------

Now that we have verified that the project compiles and that the unit test passes, we can execute the application in a standalone mode. To do this, run the following maven command:

mvn clean exec:java

The application starts and you should soon see the following notification in your console:

May 26, 2013 8:08:45 PM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:8080]
May 26, 2013 8:08:45 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...

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 15, WADL Support chapter.

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:

$ curl http://localhost:8080/myapp/myresource
Got it!

As we can see, the curl command returned with the Got it! message that was sent by our resource. We can also ask curl to provide more information about the response, for example we can let it display all response headers by using the -i switch:

curl -i http://localhost:8080/myapp/myresource
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Sun, 26 May 2013 18:27:19 GMT
Content-Length: 7

Got it!

Here we see the whole content of the response message that our Jersey/JAX-RS application returned, including all the HTTP headers. Notice the Content-Type: text/plain header that was derived from the value of @Produces annotation attached to the MyResource class.

In case you want to see even more details about the communication between our curl client and our resource running on Jersey in a Grizzly I/O container, feel free to try other various options and switches that curl provides. For example, this last command will make curl output a lot of additional information about the whole communication:

$ curl -v http://localhost:8080/myapp/myresource
* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* connected
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /myapp/myresource HTTP/1.1
> User-Agent: curl/7.25.0 (x86_64-apple-darwin11.3.0) libcurl/7.25.0 OpenSSL/1.0.1e zlib/1.2.7 libidn/1.22
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Date: Sun, 26 May 2013 18:29:18 GMT
< Content-Length: 7
<
* Connection #0 to host localhost left intact
Got it!* Closing connection #0

1.4. Creating a JavaEE Web Application

To create a Web Application that can be packaged as WAR and deployed in a Servlet container follow a similar process to the one described in Section 1.1, “Creating a New Project from Maven Archetype”. In addition to the Grizzly-based archetype, Jersey provides also a Maven arcehtype for creating web application skeletons. To create the new web application skeleton project, execute the following Maven command in the directory where the new project should reside:

mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-webapp \
                -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \
                -DgroupId=com.example -DartifactId=simple-service-webapp -Dpackage=com.example \
                -DarchetypeVersion=2.0

As with the Grizzly based project, feel free to adjust the groupIdpackage and/or artifactId of your new web application project. Alternatively, you can change it by updating the new project pom.xml once it gets generated.

Once the project generation from a Jersey maven archetype is successfully finished, you should see the new simple-service-webapp project directory created in your current location. The directory contains a standard Maven project structure, similar to the simple-service project content we have seen earlier, except it is extended with an additional web application specific content:

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 resources are located under src/main/resources.
Project web application files are located under src/main/webapp.

The project contains the same MyResouce JAX-RS resource class. It does not contain any unit tests as well as it does not contain a Main class that was used to setup Grizzly container in the previous project. Instead, it contains the standard Java EE web application web.xml deployment descriptor under src/main/webapp/WEB-INF. The last component in the project is an index.jsp page that serves as a client for the MyResource resource class that is packaged and deployed with the application.

To compile and package the application into a WAR, invoke the following maven command in your console:

mvn clean package

A successfull build output will produce an output similar to the one below:

Results :

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

[INFO]
[INFO] --- maven-war-plugin:2.1.1:war (default-war) @ simple-service-webapp ---
[INFO] Packaging webapp
[INFO] Assembling webapp [simple-service-webapp] in [.../simple-service-webapp/target/simple-service-webapp]
[INFO] Processing war project
[INFO] Copying webapp resources [.../simple-service-webapp/src/main/webapp]
[INFO] Webapp assembled in [75 msecs]
[INFO] Building war: .../simple-service-webapp/target/simple-service-webapp.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.067s
[INFO] Finished at: Sun May 26 21:07:44 CEST 2013
[INFO] Final Memory: 17M/490M
[INFO] ------------------------------------------------------------------------

Now you are ready to take the packaged WAR (located under ./target/simple-service-webapp.war) and deploy it to a Servlet container of your choice.

Important

To deploy a Jersey application, you will need a Servlet container that supports Servlet 2.5 or later. For full set of advanced features (such as JAX-RS 2.0 Async Support) you will need a Servlet 3.0 or later compliant container.

1.5. Exploring Other Jersey Examples

In the sections above, we have covered an approach how to get dirty with Jersey quickly. Please consult the other sections of the Jersey User Guide to learn more about Jersey and JAX-RS. Even though we try our best to cover as much as possibly in the User Guide, there is always a chance that you would not be able to get a full answer to the problem you are solving. In that case, consider diving in our examples that provide additional tips and hints to the features you may want to use in your projects.

Jersey codebase contains a number of useful examples on how to use various JAX-RS and Jersey features. Feel free to browse through the code of individual Jersey Examples in the Jersey source repository. For off-line browsing, you can also download a bundle with all the examples from here.

Chapter 2. Modules and dependencies

2.1. Java SE Compatibility

All Jersey components are compiled with Java SE 6 target. It means, you will also need at least Java SE 6 to be able to compile and run your application.

2.2. Introduction to Jersey dependencies

Jersey is built, assembled and installed using Apache Maven. Non-snapshot Jersey releases are deployed to the Central Maven Repository. Jersey is also being deployed toJava.Net Maven repositories, which contain also Jersey SNAPSHOT versions. In case you would want to test the latest development builds check out the Java.Net Snapshots Maven repository.

An application that uses Jersey and depends on Jersey modules is in turn required to also include in the application dependencies the set of 3rd party modules that Jersey modules depend on. Jersey is designed as a pluggable component architecture and different applications can therefore require different sets of Jersey modules. This also means that the set of external Jersey dependencies required to be included in the application dependencies may vary in each application based on the Jersey modules that are being used by the application.

Developers using Maven or a Maven-aware build system in their projects are likely to find it easier to include and manage dependencies of their applications compared to developers using ant or other build systems that are not compatible with Maven. This document will explain to both maven and non-maven developers how to depend on Jersey modules in their application. Ant developers are likely to find the Ant Tasks for Maven very useful.

2.3. Common Jersey Use Cases

2.3.1. Servlet based application on Glassfish

If you are using Glassfish application server, you don't need to package anything with your application, everything is already included. You just need to declare (provided) dependency on JAX-RS API to be able to compile your application.

<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>

If you are using any Jersey specific feature, you will need to depend on Jersey directly.

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>
<!-- if you are using Jersey client specific features -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>
            

2.3.2. Servlet based server-side application

Following dependencies apply to application server (servlet containers) without any integrated JAX-RS implementation. Then application needs to include JAX-RS API and Jersey implementation in deployed application.

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core"  -->
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.0</version>
</dependency>
<!-- Required only when you are using JAX-RS Client -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.0</version>
</dependency>

2.3.3. Client application on JDK

Applications running on plain JDK using only client part of JAX-RS specification need to depend only on client. There are various additional modules which can be added, like for example grizzly or apache connector (see dependencies snipped below). Jersey client runs by default with plain JDK (using HttpUrlConnection). See Chapter 5, Client API. for more details.

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.0</version>
</dependency>
            

Currently available connectors:

<dependency>
    <groupId>org.glassfish.jersey.connectors</groupId>
    <artifactId>jersey-grizzly-connector</artifactId>
    <version>2.0</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.connectors</groupId>
    <artifactId>jersey-apache-connector</artifactId>
    <version>2.0</version>
</dependency>

2.3.4. Served side application on supported container

Jersey provides support for programmatic deployment on some containers: Grizzly 2 (http, servlet), JDK Http server and Simple Http server. This chapter presents only required maven dependencies, more information can be found in Chapter 4, Deploying a RESTful Web Service.

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-http</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-servlet</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-jdk-http</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-simple-http</artifactId>
    <version>2.0</version>
</dependency>

2.4. List of modules

The following chapters provide an overview of all Jersey modules and their dependencies with links to the respective binaries (follow a link on a module name to get complete set of downloadable dependencies).

Table 2.1. Jersey Core

Core
jersey-client Jersey core client implementation.
jersey-common Jersey core common packages.
jersey-server Jersey core server implementation.

Table 2.2. Jersey Containers

Containers
jersey-container-grizzly2-http Grizzly 2 Http Container.
jersey-container-grizzly2-servlet Grizzly 2 Servlet Container.
jersey-container-jdk-http JDK Http Container.
jersey-container-servlet Jersey core Servlet 3.x implementation.
jersey-container-servlet-core Jersey core Servlet 2.x implementation.
jersey-container-simple-http Simple Http Container.

Table 2.3. Jersey Connectors

Connectors
jersey-grizzly-connector Jersey Client Transport via Grizzly.
jersey-apache-connector Jersey Client Transport via Apache.

Table 2.4. Jersey Media

Media
jersey-media-json-jackson Jersey JSON Jackson entity providers support module.
jersey-media-json-jettison Jersey JSON Jettison entity providers support module.
jersey-media-json-processing Jersey JSON-P (JSR 353) entity providers support proxy module.
jersey-media-moxy Jersey JSON entity providers support module based on EclipseLink MOXy.
jersey-media-multipart Jersey Multipart entity providers support module.
jersey-media-sse Jersey Server Sent Events entity providers support module.

Table 2.5. Jersey Extensions

Extensions
jersey-bean-validation Jersey extension module providing support for Bean Validation (JSR-349) API.
jersey-mvc Jersey extension module providing support for MVC.
jersey-mvc-freemarker Jersey extension module providing support for Freemarker templates.
jersey-mvc-jsp Jersey extension module providing support for JSP templates.
jersey-proxy-client Jersey extension module providing support for (proxy-based) high-level client API.
jersey-servlet-portability Library that enables writing web applications that run with both Jersey 1.x and Jersey 2.x servlet containers.
jersey-wadl-doclet A doclet that generates a resourcedoc xml file: this file contains the javadoc documentation of resource classes, so that this can be used for extending generated wadl with useful documentation.

Table 2.6. Jersey Test Framework

Test Framework
jersey-test-framework-core Jersey Test Framework Core.
jersey-test-framework-provider-bundle Jersey Test Framework Providers Bundle.
jersey-test-framework-provider-default-client Jersey Test Framework Default Client Provider.
jersey-test-framework-provider-external Jersey Test Framework - External container.
jersey-test-framework-provider-grizzly2 Jersey Test Framework - Grizzly2 container.
jersey-test-framework-provider-inmemory Jersey Test Framework - InMemory container.
jersey-test-framework-provider-jdk-http Jersey Test Framework - JDK HTTP container.
jersey-test-framework-provider-simple Jersey Test Framework - Simple HTTP container.

Table 2.7. Jersey Glassfish Bundles

Glassfish Bundles
jersey-gf-cdi Jersey CDI for GlassFish integration.
jersey-gf-ejb Jersey EJB for GlassFish integration.

Table 2.8. Jersey Examples

Examples
clipboard Jersey clipboard example.
clipboard-programmatic Jersey programmatic resource API clipboard example.
exception-mapping Jersey example showing exception mappers in action.
helloworld Jersey annotated resource class "Hello world" example.
helloworld-programmatic Jersey programmatic resource API "Hello world" example.
helloworld-pure-jax-rs Example using only the standard JAX-RS API's and the lightweight HTTP server bundled in JDK.
http-trace Jersey HTTP TRACE support example
https-clientserver-grizzly Jersey HTTPS Client/Server example on Grizzly.
jaxb Jersey JAXB example.
jaxrs-types-injection Jersey JAX-RS types injection example.
json-jackson Jersey JSON with Jackson example.
json-jettison Jersey JSON with Jettison JAXB example.
json-moxy Jersey JSON with MOXy example.
json-with-padding Jersey JSON with Padding example.
managed-client Jersey managed client example.
osgi-helloworld-webapp OSGi Helloworld.
osgi-helloworld-webapp OSGi Helloworld - bundle.
osgi-helloworld-webapp OSGi Helloworld - war.
osgi-http-service OSGi Helloworld.
osgi-http-service OSGi Helloworld.
reload Jersey resource configuration reload example.
server-async Jersey JAX-RS asynchronous server-side example.
server-async-managed Jersey JAX-RS asynchronous server-side example with custom Jersey executor providers.
server-async-standalone Standalone Jersey JAX-RS asynchronous server-side processing example.
server-sent-events Jersey Server-Sent Events example.
simple-console Jersey Simple Console example.
sse-twitter-aggregator Jersey SSE Twitter Message Aggregator Example.
system-properties-example Jersey system properties example.
xml-moxy Jersey XML MOXy example.

Table 2.9. Jersey Examples - WebApps

Examples - WAR
bean-validation-webapp Jersey Bean Validation (JSR-349) example.
bookmark Jersey Bookmark example.
bookmark-em Jersey Bookmark example using EntityManager.
bookstore-webapp Jersey MVC Bookstore example.
cdi-webapp Jersey CDI example.
extended-wadl-webapp Extended WADL example.
freemarker-webapp Jersey Freemarker example.
helloworld-webapp Jersey annotated resource class "Hello world" example.
https-server-glassfish Jersey HTTPS server on GlassFish example.
jersey-ejb Jersey EJB example.
json-processing-webapp Jersey JSON-P (JSR 353) example.
managed-beans-webapp Jersey Managed Beans Web Application example.
managed-client-simple-webapp Jersey Managed Client Simple Webapp example.
managed-client-webapp Jersey managed client web application example.
multipart-webapp Jersey Multipart example.
sse-item-store-webapp Jersey SSE-based item store example.

Chapter 3. JAX-RS Application, Resources and Sub-Resources

This chapter presents an overview of the core JAX-RS concepts - resources and sub-resources.

The JAX-RS 2.0 JavaDoc can be found online here.

The JAX-RS 2.0 specification draft can be found online here.

3.1. Root Resource Classes

Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path have at least one method annotated with @Path or a resource method designator annotation such as @GET@PUT@POST@DELETE. Resource methods are methods of a resource class annotated with a resource method designator. This section shows how to use Jersey to annotate Java objects to create RESTful web services.

The following code example is a very simple example of a root resource class using JAX-RS annotations. The example code shown here is from one of the samples that ships with Jersey, the zip file of which can be found in the maven repository here.

Example 3.1. Simple hello world root resource class

package org.glassfish.jersey.examples.helloworld;

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

@Path("helloworld")
public class HelloWorldResource {
    public static final String CLICHED_MESSAGE = "Hello World!";

@GET
@Produces("text/plain")
    public String getHello() {
        return CLICHED_MESSAGE;
    }
}


Let's look at some of the JAX-RS annotations used in this example.

3.1.1. @Path

The @Path annotation's value is a relative URI path. In the example above, the Java class will be hosted at the URI path /helloworld. This is an extremely simple use of the @Path annotation. What makes JAX-RS so useful is that you can embed variables in the URIs.

URI path templates are URIs with variables embedded within the URI syntax. These variables are substituted at runtime in order for a resource to respond to a request based on the substituted URI. Variables are denoted by curly braces. For example, look at the following @Path annotation:

@Path("/users/{username}")

In this type of example, a user will be prompted to enter their name, and then a Jersey web service configured to respond to requests to this URI path template will respond. For example, if the user entered their username as "Galileo", the web service will respond to the following URL: http://example.com/users/Galileo

To obtain the value of the username variable the @PathParam may be used on method parameter of a request method, for example:

Example 3.2. Specifying URI path parameter

@Path("/users/{username}")
public class UserResource {

    @GET
    @Produces("text/xml")
    public String getUser(@PathParam("username") String userName) {
        ...
    }
}


If it is required that a user name must only consist of lower and upper case numeric characters then it is possible to declare a particular regular expression, which overrides the default regular expression, "[^/]+?", for example:

@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")

In this type of example the username variable will only match user names that begin with one upper or lower case letter and zero or more alpha numeric characters and the underscore character. If a user name does not match that a 404 (Not Found) response will occur.

@Path value may or may not begin with a '/', it makes no difference. Likewise, by default, a @Path value may or may not end in a '/', it makes no difference, and thus request URLs that end or do not end in a '/' will both be matched.

3.1.2. @GET, @PUT, @POST, @DELETE, ... (HTTP Methods)

@GET@PUT@POST@DELETE and @HEAD are resource method designator annotations defined by JAX-RS and which correspond to the similarly named HTTP methods. In the example above, the annotated Java method will process HTTP GET requests. The behavior of a resource is determined by which of the HTTP methods the resource is responding to.

The following example is an extract from the storage service sample that shows the use of the PUT method to create or update a storage container:

Example 3.3. PUT method

@PUT
public Response putContainer() {
    System.out.println("PUT CONTAINER " + container);

    URI uri = uriInfo.getAbsolutePath();
    Container c = new Container(container, uri.toString());

    Response r;
    if (!MemoryStore.MS.hasContainer(c)) {
        r = Response.created(uri).build();
    } else {
        r = Response.noContent().build();
    }

    MemoryStore.MS.createContainer(c);
    return r;
}


By default the JAX-RS runtime will automatically support the methods HEAD and OPTIONS, if not explicitly implemented. For HEAD the runtime will invoke the implemented GET method (if present) and ignore the response entity (if set). A response returned for the OPTIONS method depends on the requested media type defined in the 'Accept' header. The OPTIONS method can return a response with a set of supported resource methods in the 'Allow' header or return a WADL document. See wadl section for more information.

3.1.3. @Produces

The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client. In this example, the Java method will produce representations identified by the MIME media type "text/plain". @Produces can be applied at both the class and method levels. Here's an example:

Example 3.4. Specifying output MIME type

@Path("/myResource")
@Produces("text/plain")
public class SomeResource {
    @GET
    public String doGetAsPlainText() {
        ...
    }

    @GET
    @Produces("text/html")
    public String doGetAsHtml() {
        ...
    }
}


The doGetAsPlainText method defaults to the MIME type of the @Produces annotation at the class level. The doGetAsHtml method's @Produces annotation overrides the class-level @Produces setting, and specifies that the method can produce HTML rather than plain text.

If a resource class is capable of producing more that one MIME media type then the resource method chosen will correspond to the most acceptable media type as declared by the client. More specifically the Accept header of the HTTP request declares what is most acceptable. For example if the Accept header is "Accept: text/plain" then the doGetAsPlainText method will be invoked. Alternatively if the Accept header is " Accept: text/plain;q=0.9, text/html", which declares that the client can accept media types of "text/plain" and "text/html" but prefers the latter, then the doGetAsHtml method will be invoked.

More than one media type may be declared in the same @Produces declaration, for example:

Example 3.5. Using multiple output MIME types

@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
    ...
}


The doGetAsXmlOrJson method will get invoked if either of the media types "application/xml" and "application/json" are acceptable. If both are equally acceptable then the former will be chosen because it occurs first.

Optionally, server can also specify the quality factor for individual media types. These are considered if several are equally acceptable by the client. For example:

Example 3.6. Server-side content negotiation

@GET
@Produces({"application/xml; qs=0.9", "application/json"})
public String doGetAsXmlOrJson() {
    ...
}


In the above sample, if client accepts both "application/xml" and "application/json" (equally), then a server always sends "application/json", since "application/xml" has a lower quality factor.

The examples above refers explicitly to MIME media types for clarity. It is possible to refer to constant values, which may reduce typographical errors, see the constant field values of MediaType.

3.1.4. @Consumes

The @Consumes annotation is used to specify the MIME media types of representations that can be consumed by a resource. The above example can be modified to set the cliched message as follows:

Example 3.7. Specifying input MIME type

@POST
@Consumes("text/plain")
public void postClichedMessage(String message) {
    // Store the message
}


In this example, the Java method will consume representations identified by the MIME media type "text/plain". Notice that the resource method returns void. This means no representation is returned and response with a status code of 204 (No Content) will be returned to the client.

@Consumes can be applied at both the class and the method levels and more than one media type may be declared in the same @Consumes declaration.

3.2. Parameter Annotations (@*Param)

Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request. One of the previous examples presented the use of @PathParam to extract a path parameter from the path component of the request URL that matched the path declared in @Path.

@QueryParam is used to extract query parameters from the Query component of the request URL. The following example is an extract from the sparklines sample:

Example 3.8. Query parameters

@Path("smooth")
@GET
public Response smooth(
    @DefaultValue("2") @QueryParam("step") int step,
    @DefaultValue("true") @QueryParam("min-m") boolean hasMin,
    @DefaultValue("true") @QueryParam("max-m") boolean hasMax,
    @DefaultValue("true") @QueryParam("last-m") boolean hasLast,
    @DefaultValue("blue") @QueryParam("min-color") ColorParam minColor,
    @DefaultValue("green") @QueryParam("max-color") ColorParam maxColor,
    @DefaultValue("red") @QueryParam("last-color") ColorParam lastColor) {
    ...
}

If a query parameter "step" exists in the query component of the request URI then the "step" value will be will extracted and parsed as a 32 bit signed integer and assigned to the step method parameter. If "step" does not exist then a default value of 2, as declared in the @DefaultValue annotation, will be assigned to the step method parameter. If the "step" value cannot be parsed as a 32 bit signed integer then a HTTP 404 (Not Found) response is returned. User defined Java types such as ColorParam may be used, which as implemented as follows:

Example 3.9. Custom Java type for consuming request parameters

public class ColorParam extends Color {

    public ColorParam(String s) {
        super(getRGB(s));
    }

    private static int getRGB(String s) {
        if (s.charAt(0) == '#') {
            try {
                Color c = Color.decode("0x" + s.substring(1));
                return c.getRGB();
            } catch (NumberFormatException e) {
                throw new WebApplicationException(400);
            }
        } else {
            try {
                Field f = Color.class.getField(s);
                return ((Color)f.get(null)).getRGB();
            } catch (Exception e) {
                throw new WebApplicationException(400);
            }
        }
    }
}

In general the Java type of the method parameter may:

  1. Be a primitive type;

  2. Have a constructor that accepts a single String argument;

  3. Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) andjava.util.UUID.fromString(String));

  4. Have a registered implementation of javax.ws.rs.ext.ParamConverterProvider JAX-RS extension SPI that returns ajavax.ws.rs.ext.ParamConverter instance capable of a "from string" conversion for the type. or

  5. Be List<T>Set<T> or SortedSet<T>, where T satisfies 2 or 3 above. The resulting collection is read-only.

Sometimes parameters may contain more than one value for the same name. If this is the case then types in 5) may be used to obtain all values.

If the @DefaultValue is not used in conjunction with @QueryParam and the query parameter is not present in the request then value will be an empty collection forListSetor SortedSetnull for other object types, and the Java-defined default for primitive types.

The @PathParam and the other parameter-based annotations, @MatrixParam@HeaderParam@CookieParam@FormParam obey the same rules as @QueryParam.@MatrixParam extracts information from URL path segments. @HeaderParam extracts information from the HTTP headers. @CookieParam extracts information from the cookies declared in cookie related HTTP headers.

@FormParam is slightly special because it extracts information from a request representation that is of the MIME media type "application/x-www-form-urlencoded" and conforms to the encoding specified by HTML forms, as described here. This parameter is very useful for extracting information that is POSTed by HTML forms, for example the following extracts the form parameter named "name" from the POSTed form data:

Example 3.10. Processing POSTed HTML form

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(@FormParam("name") String name) {
    // Store the message
}


If it is necessary to obtain a general map of parameter name to values then, for query and path parameters it is possible to do the following:

Example 3.11. Obtaining general map of URI path and/or query parameters

@GET
public String get(@Context UriInfo ui) {
    MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
    MultivaluedMap<String, String> pathParams = ui.getPathParameters();
}


For header and cookie parameters the following:

Example 3.12. Obtaining general map of header parameters

@GET
public String get(@Context HttpHeaders hh) {
    MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
    Map<String, Cookie> pathParams = hh.getCookies();
}


In general @Context can be used to obtain contextual Java types related to the request or response.

Because form parameters (unlike others) are part of the message entity, it is possible to do the following:

Example 3.13. Obtaining general map of form parameters

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap<String, String> formParams) {
    // Store the message
}


I.e. you don't need to use the @Context annotation.

Another kind of injection is the @BeanParam which allows to inject the parameters described above into a single bean. A bean annotated with @BeanParam containing any fields and appropriate *param annotation(like @PathParam) will be initialized with corresponding request values in expected way as if these fields were in the resource class. Then instead of injecting request values like path param into a constructor parameters or class fields the @BeanParam can be used to inject such a bean into a resource or resource method. The @BeanParam is used this way to aggregate more request parameters into a single bean.

Example 3.14. Example of the bean which will be used as @BeanParam

public class MyBeanParam {
    @PathParam("p")
    private String pathParam;

    @MatrixParam("m")
    @Encoded
    @DefaultValue("default")
    private String matrixParam;

    @HeaderParam("header")
    private String headerParam;

    private String queryParam;

    public MyBeanParam(@QueryParam("q") String queryParam) {
        this.queryParam = queryParam;
    }

    public String getPathParam() {
        return pathParam;
    }
    ...
}

Example 3.15. Injection of MyBeanParam as a method parameter:

@POST
public void post(@BeanParam MyBeanParam beanParam, String entity) {
    final String pathParam = beanParam.getPathParam(); // contains injected path parameter "p"
    ...
}

The example shows aggregation of injections @PathParam@QueryParam @MatrixParam and @HeaderParam into one single bean. The rules for injections inside the bean are the same as described above for these injections. The @DefaultValue is used to define the default value for matrix parameter matrixParam. Also the @Encodedannotation has the same behaviour as if it were used for injection in the resource method directly. Injecting the bean parameter into @Singleton resource class fields is not allowed (injections into method parameter must be used instead).

@BeanParam can contain all parameters injections injections (@PathParam@QueryParam@MatrixParam@HeaderParam@CookieParam@FormParam). More beans can be injected into one resource or method parameters even if they inject the same request values. For example the following is possible:

Example 3.16. Injection of more beans into one resource methods:

@POST
public void post(@BeanParam MyBeanParam beanParam, @BeanParam AnotherBean anotherBean, @PathParam("p") pathParam,
String entity) {
    // beanParam.getPathParam() == pathParam
    ...
}

3.3. Sub-resources

@Path may be used on classes and such classes are referred to as root resource classes. @Path may also be used on methods of root resource classes. This enables common functionality for a number of resources to be grouped together and potentially reused.

The first way @Path may be used is on resource methods and such methods are referred to as sub-resource methods. The following example shows the method signatures for a root resource class from the jmaki-backend sample:

Example 3.17. Sub-resource methods

@Singleton
@Path("/printers")
public class PrintersResource {

    @GET
    @Produces({"application/json", "application/xml"})
    public WebResourceList getMyResources() { ... }

    @GET @Path("/list")
    @Produces({"application/json", "application/xml"})
    public WebResourceList getListOfPrinters() { ... }

    @GET @Path("/jMakiTable")
    @Produces("application/json")
    public PrinterTableModel getTable() { ... }

    @GET @Path("/jMakiTree")
    @Produces("application/json")
    public TreeModel getTree() { ... }

    @GET @Path("/ids/{printerid}")
    @Produces({"application/json", "application/xml"})
    public Printer getPrinter(@PathParam("printerid") String printerId) { ... }

    @PUT @Path("/ids/{printerid}")
    @Consumes({"application/json", "application/xml"})
    public void putPrinter(@PathParam("printerid") String printerId, Printer printer) { ... }

    @DELETE @Path("/ids/{printerid}")
    public void deletePrinter(@PathParam("printerid") String printerId) { ... }
}


If the path of the request URL is "printers" then the resource methods not annotated with @Path will be selected. If the request path of the request URL is "printers/list" then first the root resource class will be matched and then the sub-resource methods that match "list" will be selected, which in this case is the sub-resource methodgetListOfPrinters. So, in this example hierarchical matching on the path of the request URL is performed.

The second way @Path may be used is on methods not annotated with resource method designators such as @GET or @POST. Such methods are referred to as sub-resource locators. The following example shows the method signatures for a root resource class and a resource class from the optimistic-concurrency sample:

Example 3.18. Sub-resource locators

@Path("/item")
public class ItemResource {
    @Context UriInfo uriInfo;

    @Path("content")
    public ItemContentResource getItemContentResource() {
        return new ItemContentResource();
    }

    @GET
    @Produces("application/xml")
        public Item get() { ... }
    }
}

public class ItemContentResource {

    @GET
    public Response get() { ... }

    @PUT
    @Path("{version}")
    public void put(@PathParam("version") int version,
                    @Context HttpHeaders headers,
                    byte[] in) {
        ...
    }
}


The root resource class ItemResource contains the sub-resource locator method getItemContentResource that returns a new resource class. If the path of the request URL is "item/content" then first of all the root resource will be matched, then the sub-resource locator will be matched and invoked, which returns an instance of theItemContentResource resource class. Sub-resource locators enable reuse of resource classes. A method can be annotated with the @Path annotation with empty path (@Path("/") or @Path("")) which means that the sub resource locator is matched for the path of the enclosing resource (without sub-resource path).

Example 3.19. Sub-resource locators with empty path

@Path("/item")
public class ItemResource {

    @Path("/")
    public ItemContentResource getItemContentResource() {
        return new ItemContentResource();
    }
}


In the example above the sub-resource locator method getItemContentResource is matched for example for request path "/item/locator" or even for only "/item".

In addition the processing of resource classes returned by sub-resource locators is performed at runtime thus it is possible to support polymorphism. A sub-resource locator may return different sub-types depending on the request (for example a sub-resource locator could return different sub-types dependent on the role of the principle that is authenticated). So for example the following sub resource locator is valid:

Example 3.20. Sub-resource locators returning sub-type

@Path("/item")
public class ItemResource {

    @Path("/")
    public Object getItemContentResource() {
        return new AnyResource();
    }
}


Note that the runtime will not manage the life-cycle or perform any field injection onto instances returned from sub-resource locator methods. This is because the runtime does not know what the life-cycle of the instance is. If it is required that the runtime manages the sub-resources as standard resources the Class should be returned as shown in the following example:

Example 3.21. Sub-resource locators created from classes

import javax.inject.Singleton;

@Path("/item")
public class ItemResource {
    @Path("content")
    public Class<ItemContentSingletonResource> getItemContentResource() {
        return ItemContentSingletonResource.class;
    }
}

@Singleton
public class ItemContentSingletonResource {
    // this class is managed in the singleton life cycle
}


JAX-RS resources are managed in per-request scope by default which means that new resource is created for each request. In this example thejavax.inject.Singleton annotation says that the resource will be managed as singleton and not in request scope. The sub-resource locator method returns a class which means that the runtime will managed the resource instance and its life-cycle. If the method would return instance instead, the Singleton annotation would have no effect and the returned instance would be used.

The sub resource locator can also return a programmatic resource model. See resource builder section for information of how the programmatic resource model is constructed. The following example shows very simple resource returned from the sub-resource locator method.

Example 3.22. Sub-resource locators returning resource model

import org.glassfish.jersey.server.model.Resource;

@Path("/item")
public class ItemResource {

    @Path("content")
    public Resource getItemContentResource() {
        return Resource.from(ItemContentSingletonResource.class);
    }
}


The code above has exactly the same effect as previous example. Resource is a resource simple resource constructed from ItemContentSingletonResource. More complex programmatic resource can be returned as long they are valid resources.

3.4. Life-cycle of Root Resource Classes

By default the life-cycle of root resource classes is per-request which, namely that a new instance of a root resource class is created every time the request URI path matches the root resource. This makes for a very natural programming model where constructors and fields can be utilized (as in the previous section showing the constructor of the SparklinesResource class) without concern for multiple concurrent requests to the same resource.

In general this is unlikely to be a cause of performance issues. Class construction and garbage collection of JVMs has vastly improved over the years and many objects will be created and discarded to serve and process the HTTP request and return the HTTP response.

Instances of singleton root resource classes can be declared by an instance of Application.

Jersey supports two further life-cycles using Jersey specific annotations.

Table 3.1. Resource scopes

Scope Annotation Annotation full class name Description
Request scope @RequestScoped (or none) org.glassfish.jersey.process.internal.RequestScoped Default lifecycle (applied when no annotation is present). In this scope the resource instance is created for each new request and used for processing of this request. If the resource is used more than one time in the request processing, always the same instance will be used. This can happen when a resource is a sub resource is returned more times during the matching. In this situation only on instance will server the requests.
Per-lookup scope @PerLookup org.glassfish.jersey.process.internal.RequestScoped In this scope the resource instance is created every time it is needed for the processing even it handles the same request.
Singleton @Singleton javax.inject.Singleton In this scope there is only one instance per jax-rs application. Singleton resource can be either annotated with @Singleton and its class can be registered using the instance of Application. You can also create singletons by registering singleton instances into Application.

3.5. Rules of Injection

Previous sections have presented examples of annotated types, mostly annotated method parameters but also annotated fields of a class, for the injection of values onto those types.

This section presents the rules of injection of values on annotated types. Injection can be performed on fields, constructor parameters, resource/sub-resource/sub-resource locator method parameters and bean setter methods. The following presents an example of all such injection cases:

Example 3.23. Injection

@Path("id: \d+")
public class InjectedResource {
    // Injection onto field
    @DefaultValue("q") @QueryParam("p")
    private String p;

    // Injection onto constructor parameter
    public InjectedResource(@PathParam("id") int id) { ... }

    // Injection onto resource method parameter
    @GET
    public String get(@Context UriInfo ui) { ... }

    // Injection onto sub-resource resource method parameter
    @Path("sub-id")
    @GET
    public String get(@PathParam("sub-id") String id) { ... }

    // Injection onto sub-resource locator method parameter
    @Path("sub-id")
    public SubResource getSubResource(@PathParam("sub-id") String id) { ... }

    // Injection using bean setter method
    @HeaderParam("X-header")
    public void setHeader(String header) { ... }
}


There are some restrictions when injecting on to resource classes with a life-cycle of singleton scope. In such cases the class fields or constructor parameters cannot be injected with request specific parameters. So, for example the following is not allowed.

Example 3.24. Wrong injection into a singleton scope

@Path("resource")
@Singleton
public static class MySingletonResource {

    @QueryParam("query")
    String param; // WRONG: initialization of application will fail as you cannot
                  // inject request specific parameters into a singleton resource.

    @GET
    public String get() {
        return "query param: " + param;
    }
}


The example above will cause validation failure during application initialization as singleton resources cannot inject request specific parameters. The same example would fail if the query parameter would be injected into constructor parameter of such a singleton. In other words, if you wish one resource instance to server more requests (in the same time) it cannot be bound to a specific request parameter.

The exception exists for specific request objects which can injected even into constructor or class fields. For these objects the runtime will inject proxies which are able to simultaneously server more request. These request objects are HttpHeadersRequestUriInfoSecurityContext. These proxies can be injected using the@Context annotation. The following example shows injection of proxies into the singleton resource class.

Example 3.25. Injection of proxies into singleton

@Path("resource")
@Singleton
public static class MySingletonResource {
    @Context
    Request request; // this is ok: the proxy of Request will be injected into this singleton

    public MySingletonResource(@Context SecurityContext securityContext) {
        // this is ok too: the proxy of SecurityContext will be injected
    }

    @GET
    public String get() {
        return "query param: " + param;
    }
}


To summarize the injection can be done into the following constructs:

Table 3.2. Overview of injection types

Java construct Description
Class fields Inject value directly into the field of the class. The field can be private and must not be final. Cannot be used in Singleton scope except proxiable types mentioned above.
Constructor parameters The constructor will be invoked with injected values. If more constructors exists the one with the most injectable parameters will be invoked. Cannot be used in Singleton scope except proxiable types mentioned above.
Resource methods The resource methods (these annotated with @GET, @POST, ...) can contain parameters that can be injected when the resource method is executed. Can be used in any scope.
Sub resource locators The sub resource locators (methods annotated with @Path but not @GET, @POST, ...) can contain parameters that can be injected when the resource method is executed. Can be used in any scope.
Setter methods Instead of injecting values directly into field the value can be injected into the setter method which will initialize the field. This injection can be used only with @Context annotation. This means it cannot be used for example for injecting of query params but it can be used for injections of request. The setters will be called after the object creation and only once. The name of the method does not necessary have a setter pattern. Cannot be used in Singleton scope except proxiable types mentioned above.

The following example shows all possible java constructs into which the values can be injected.

Example 3.26. Example of possible injections

@Path("resource")
public static class SummaryOfInjectionsResource {
    @QueryParam("query")
    String param; // injection into a class field


    @GET
    public String get(@QueryParam("query") String methodQueryParam) {
        // injection into a resource method parameter
        return "query param: " + param;
    }

    @Path("sub-resource-locator")
    public Class<SubResource> subResourceLocator(@QueryParam("query") String subResourceQueryParam) {
        // injection into a sub resource locator parameter
        return SubResource.class;
    }

    public SummaryOfInjectionsResource(@QueryParam("query") String constructorQueryParam) {
        // injection into a constructor parameter
    }


    @Context
    public void setRequest(Request request) {
        // injection into a setter method
        System.out.println(request != null);
    }
}

public static class SubResource {
    @GET
    public String get() {
        return "sub resource";
    }
}


The @FormParam annotation is special and may only be utilized on resource and sub-resource methods. This is because it extracts information from a request entity.

3.6. Use of @Context

Previous sections have introduced the use of @Context. Chapter 5 of the JAX-RS specification presents all the standard JAX-RS Java types that may be used with@Context.

When deploying a JAX-RS application using servlet then ServletConfigServletContextHttpServletRequest and HttpServletResponse are available using @Context.

3.7. Programmatic resource model

Resources can be constructed from classes or instances but also can be constructed from a programmatic resource model. Every resource created from from resource classes can also be constructed using the programmatic resource builder api. See resource builder section for more information.

Chapter 4. Deploying a RESTful Web Service

JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and provider classes, and root resource and provider singleton instances. A Web service may extend this class to declare root resource and provider classes. For example,

Example 4.1. Deployment agnostic application model

public class MyApplication extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> s = new HashSet<Class<?>>();
        s.add(HelloWorldResource.class);
        return s;
    }
}


Alternatively it is possible to reuse one of Jersey's implementations that scans for root resource and provider classes given a classpath or a set of package names. Such classes are automatically added to the set of classes that are returned bygetClasses. For example, the following scans for root resource and provider classes in packages "org.foo.rest", "org.bar.rest" and in any sub-packages of those two:

Example 4.2. Reusing Jersey implementation in your custom application model

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("org.foo.rest;org.bar.rest");
    }
}


There are multiple deployment options for the class that implements Application interface in the Servlet 3.0 container. For simple deployments, no web.xml is needed at all. Instead, an @ApplicationPath annotation can be used to annotate the user defined application class and specify the the base resource URI of all application resources:

Example 4.3. Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0

@ApplicationPath("resources")
public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("org.foo.rest;org.bar.rest");
    }
    ...
}


Please note that there is more which can be set or called during execution of ResourceConfig descendants constructor, see ResourceConfig javadoc for more details.

You also need to set maven-war-plugin attribute failOnMissingWebXml to false in pom.xml when building .war without web.xml file using maven:

Example 4.4. Configuration of maven-war-plugin in pom.xml with Servlet 3.0

<plugins>
    ...
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
            <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
    </plugin>
    ...
</plugins>


Another deployment option is to declare JAX-RS application details in theweb.xml. This is usually suitable in case of more complex deployments, e.g. when security model needs to be properly defined or when additional initialization parameters have to be passed to Jersey runtime. JAX-RS 1.1 specifies that a fully qualified name of the class that implements Application may be declared in the <servlet-name> element of the JAX-RS application's web.xml. This is supported in a Web container implementing Servlet 3.0 as follows:

Example 4.5. Deployment of a JAX-RS application using web.xml with Servlet 3.0

<web-app>
    <servlet>
        <servlet-name>org.foo.rest.MyApplication</servlet-name>
    </servlet>
    ...
    <servlet-mapping>
        <servlet-name>org.foo.rest.MyApplication</servlet-name>
        <url-pattern>/resources</url-pattern>
    </servlet-mapping>
    ...
</web-app>


Note that the <servlet-class> element is omitted from the servlet declaration. This is a correct declaration utilizing the Servlet 3.0 extension mechanism. Also note that<servlet-mapping> is used to define the base resource URI.

When running in a Servlet 2.x then instead it is necessary to declare the Jersey specific servlet and pass the Application implementation class name as one of the servlet'sinit-param entries:

Example 4.6. Deployment of your application using Jersey specific servlet

<web-app>
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>org.foo.rest.MyApplication</param-value>
        </init-param>
        ...
    </servlet>
    ...
</web-app>


If there is no configuration to be set and deployed application consists only from resources and providers stored in particular packages, Jersey can scan them and register automatically:

Example 4.7. Using Jersey specific servlet without an application model instance

<web-app>
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>org.foo.rest;org.bar.rest</param-value>
        </init-param>
        ...
    </servlet>
    ...
</web-app>


JAX-RS also provides the ability to obtain a container specific artifact from an Application instance. For example, Jersey supports using Grizzly as follows:

HttpHandler endpoint = RuntimeDelegate.getInstance().createEndpoint(new MyApplication(), HttpHandler.class);

Jersey also provides Grizzly helper classes to deploy the HttpHandler instance at a base URL for in-process deployment.

The Jersey samples provide many examples of Servlet-based and Grizzly-in-process-based deployments.

4.1. Auto-Discoverable Features

For a few modules provided by Jersey there is no need to explicitly register their Features as these Features are discovered and registered in the Configuration (on client/server) automatically by Jersey when the modules implementing these features are present on the classpath during the an application deployment. The modules that are automatically discovered include:

  • jersey-media-moxy (JSON part)

  • jersey-media-json-processing

  • jersey-bean-validation

Besides these modules there are also few features/providers present in jersey-server module that are discovered by this mechanism and their availability is affected by Jersey auto-discovery support configuration (see Section 4.1.1, “Configuring the Feature Auto-discovery mechanism”):

Note

Auto discovery functionality is in Jersey supported by implementing an internal SPI AutoDiscoverable interface. This interface is not public at the moment, so be careful when using it.

4.1.1. Configuring the Feature Auto-discovery mechanism

The auto-discovery of features in Jersey that is enabled by default can be disabled by using special (common/server/client) properties:

Common auto discovery properties

For each of these properties there is a client/server counter-part that only disables the feature on the client or server respectively (see ClientProperties/ServerProperties). Each of these client/server specific auto-discovery related properties overrides the value of the related common property (if set).

Note

In case an auto-discoverable feature is disabled then all the featured, components and/or properties, registered with the feature by default using the auto-discovery mechanism have to be registered manually.

Chapter 5. Client API

This section introduces the JAX-RS Client API, which is a fluent Java based API for communication with RESTful Web services. This standard API that is also part of Java EE 7 is designed to make it very easy to consume a Web service exposed via HTTP protocol and enables developers to concisely and efficiently implement portable client-side solutions that leverage existing and well established client-side HTTP connector implementations.

The JAX-RS client API can be utilized to consume any Web service exposed on top of a HTTP protocol or it's extension (e.g. WebDAV), and is not restricted to services implemented using JAX-RS. Yet, developers familiar with JAX-RS should find the client API complementary to their services, especially if the client API is utilized by those services themselves, or to test those services. The JAX-RS client API finds inspiration in the proprietary Jersey 1.x Client API and developers familiar with the Jersey 1.x Client API should find it easy to understand all the concepts introduced in the new JAX-RS Client API.

The goals of the client API are threefold:

  1. Encapsulate a key constraint of the REST architectural style, namely the Uniform Interface Constraint and associated data elements, as client-side Java artifacts;

  2. Make it as easy to consume RESTful Web services exposed over HTTP, same as the JAX-RS server-side API makes it easy to develop RESTful Web services; and

  3. Share common concepts and extensibility points of the JAX-RS API between the server and the client side programming models.

As an extension to the standard JAX-RS Client API, the Jersey Client API supports a pluggable architecture to enable the use of different underlying HTTP client Connectorimplementations. Several such implementations are currently provided with Jersey. We have a default client connector using Http(s)URLConnection supplied with the JDK as well as connector implementations based on Apache HTTP Client, and Grizzly Asynchronous Client.

5.1. Uniform Interface Constraint

The uniform interface constraint bounds the architecture of RESTful Web services so that a client, such as a browser, can utilize the same interface to communicate with any service. This is a very powerful concept in software engineering that makes Web-based search engines and service mash-ups possible. It induces properties such as:

  1. simplicity, the architecture is easier to understand and maintain; and

  2. evolvability or loose coupling, clients and services can evolve over time perhaps in new and unexpected ways, while retaining backwards compatibility.

Further constraints are required:

  1. every resource is identified by a URI;

  2. a client interacts with the resource via HTTP requests and responses using a fixed set of HTTP methods;

  3. one or more representations can be returned and are identified by media types; and

  4. the contents of which can link to further resources.

The above process repeated over and again should be familiar to anyone who has used a browser to fill in HTML forms and follow links. That same process is applicable to non-browser based clients.

Many existing Java-based client APIs, such as the Apache HTTP client API or HttpUrlConnection supplied with the JDK place too much focus on the Client-Server constraint for the exchanges of request and responses rather than a resource, identified by a URI, and the use of a fixed set of HTTP methods.

A resource in the JAX-RS client API is an instance of the Java class WebTarget. and encapsulates an URI. The fixed set of HTTP methods can be invoked based on theWebTarget. The representations are Java types, instances of which, may contain links that new instances of WebTarget may be created from.

5.2. Ease of use and reusing JAX-RS artifacts

Since a JAX-RS component is represented as an annotated Java type, it makes it easy to configure, pass around and inject in ways that are not so intuitive or possible with other client-side APIs. The Jersey Client API reuses many aspects of the JAX-RS and the Jersey implementation such as:

  1. URI building using UriBuilder and UriTemplate to safely build URIs;

  2. Built-in support for Java types of representations such as byte[]StringNumberBooleanCharacterInputStreamjava.io.ReaderFile,DataSource, JAXB beans as well as additional Jersey-specific JSON and Multi Part support.

  3. Using the fluent builder-style API pattern to make it easier to construct requests.

Some APIs, like the Apache HTTP Client or HttpURLConnection can be rather hard to use and/or require too much code to do something relatively simple, especially when the client needs to understand different payload representations. This is why the Jersey implementation of JAX-RS Client API provides support for wrappingHttpUrlConnection and the Apache HTTP client. Thus it is possible to get the benefits of the established JAX-RS implementations and features while getting the ease of use benefit of the simple design of the JAX-RS client API. For example, with a low-level HTTP client library, sending a POST request with a bunch of typed HTML form parameters and receiving a response de-serialized into a JAXB bean is not straightforward at all. With the new JAX-RS Client API supported by Jersey this task is very easy:

Example 5.1. POST request with form parameters

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");

Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");

MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
    .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
        MyJAXBBean.class);


In the Example 5.1, “POST request with form parameters” a new WebTarget instance is created using a new Client instance first, next a Form instance is created with two form parameters. Once ready, the Form instance is POSTed to the target resource. First, the acceptable media type is specified in the request(...) method. Then in thepost(...) method, a call to a static method on JAX-RS Entity is made to construct the request entity instance and attach the proper content media type to the form entity that is being sent. The second parameter in the post(...) method specifies the Java type of the response entity that should be returned from the method in case of a successful response. In this case an instance of JAXB bean is requested to be returned on success. The Jersey client API takes care of selecting the properMessageBodyWriter<T> for the serialization of the Form instance, invoking the POST request and producing and de-serialization of the response message payload into an instance of a JAXB bean using a proper MessageBodyReader<T>.

If the code above had to be written using HttpUrlConnection, the developer would have to write custom code to serialize the form data that are sent within the POST request and de-serialize the response input stream into a JAXB bean. Additionally, more code would have to be written to make it easy to reuse the logic when communicating with the same resource “http://localhost:8080/resource” that is represented by the JAX-RS WebTarget instance in our example.

5.3. Overview of the Client API

5.3.1. Getting started with the client API

Refer to the dependencies for details on the dependencies when using the Jersey JAX-RS Client support.

You may also want to use a custom Connector implementation. In such case you would need to include additional dependencies on the module(s) containing the custom client connector that you want to use. See section "Configuring custom Connectors" about how to use and configure a custom Jersey client transport Connector.

5.3.2.  Creating and configuring a Client instance

JAX-RS Client API is a designed to allow fluent programming model. This means, a construction of a Client instance, from which a WebTarget is created, from which a request Invocation is built and invoked can be chained in a single "flow" of invocations. The individual steps of the flow will be shown in the following sections. To utilize the client API it is first necessary to build an instance of a Client using one of the static ClientBuilder factory methods. Here's the most simple example:

Client client = ClientBuilder.newClient();

The ClientBuilder is a JAX-RS API used to create new instances of Client. In a slightly more advanced scenarios, ClientBuilder can be used to configure additional client instance properties, such as a SSL transport settings, if needed (see ??? below).

Client instance can be configured during creation by passing a ClientConfig to the newClient(Configurable) ClientBuilder factory method. ClientConfigimplements Configurable and therefore it offers methods to register providers (e.g. features or individual entity providers, filters or interceptors) and setup properties. The following code shows a registration of custom client filters:

ClientConfig clientConfig = new ClientConfig();
clientConfig.register(MyClientResponseFilter.class);
clientConfig.register(new AnotherClientFilter());
Client client = ClientBuilder.newClient(clientConfig);

In the example, filters are registered using the ClientConfig.register(...) method. There are multiple overloaded versions of the method that support registration of feature and provider classes or instances. Once a ClientConfig instance is configured, it can be passed to the ClientBuilder to create a pre-configured Clientinstance.

Note that the Jersey ClientConfig supports the fluent API model of Configurable. With that the code that configures a new client instance can be also written using a more compact style as shown below.

Client client = ClientBuilder.newClient(new ClientConfig()
        .register(MyClientResponseFilter.class)
        .register(new AnotherClientFilter());

The ability to leverage this compact pattern is inherent to all JAX-RS and Jersey Client API components.

Since Client implements Configurable interface too, it can be configured further even after it has been created. Important is to mention that any configuration change done on a Client instance will not influence the ClientConfig instance that was used to provide the initial Client instance configuration at the instance creation time. The next piece of code shows a configuration of an existing Client instance.

client.register(ThirdClientFilter.class);

Similarly to earlier examples, since Client.register(...) method supports the fluent API style, multiple client instance configuration calls can be chained:

client.register(FilterA.class)
      .register(new FilterB())
      .property("my-property", true);

To get the current configuration of the Client instance a getConfiguration() method can be used.

ClientConfig clientConfig = new ClientConfig();
clientConfig.register(MyClientResponseFilter.class);
clientConfig.register(new AnotherClientFilter());
Client client = ClientBuilder.newClient(clientConfig);
client.register(ThirdClientFilter.class);
Configuration newConfiguration = client.getConfiguration();

In the code, an additional MyClientResponseFilter class and AnotherClientFilter instance are registered in the clientConfig. The clientConfig is then used to construct a new Client instance. The ThirdClientFilter is added separately to the constructed Client instance. This does not influence the configuration represented by the original clientConfig. In the last step a newConfiguration is retrieved from the client. This configuration contains all three registered filters while the original clientConfig instance still contains only two filters. Unlike clientConfig created separately, the newConfiguration retrieved from the clientinstance represents a live client configuration view. Any additional configuration changes made to the client instance are also reflected in the newConfiguration. So,newConfiguration is really a view of the client configuration and not a configuration state copy. These principles are important in the client API and will be used in the following sections too. For example, you can construct a common base configuration for all clients (in our case it would be clientConfig) and then reuse this common configuration instance to configure multiple client instances that can be further specialized. Similarly, you can use an existing client instance configuration to configure another client instance without having to worry about any side effects in the original client instance.

5.3.3. Targeting a web resource

Once you have a Client instance you can create a WebTarget from it.

WebTarget webTarget = client.target("http://example.com/rest");

Client contains several target(...) methods that allow for creation of WebTarget instance. In this case we're using target(String uri) version. The uripassed to the method as a String is the URI of the targeted web resource. In more complex scenarios it could be the context root URI of the whole RESTful application, from which WebTarget instances representing individual resource targets can be derived and individually configured. This is possible, because JAX-RS WebTarget also implements Configurable:

WebTarget webTarget = client.target("http://example.com/rest");
webTarget.register(FilterForExampleCom.class);

The configuration principles used in JAX-RS client API apply to WebTarget as well. Each WebTarget instance inherits a configuration from it's parent (either a client or another web target) and can be further custom-configured without affecting the configuration of the parent component. In this case, the FilterForExampleCom will be registered only in the webTarget and not in client. So, the client can still be used to create new WebTarget instances pointing at other URIs using just the common client configuration, which FilterForExampleCom filter is not part of.

5.3.4. Identifying resource on WebTarget

Let's assume we have a webTarget pointing at "http://example.com/rest" URI that represents a context root of a RESTful application and there is a resource exposed on the URI "http://example.com/rest/resource". As already mentioned, a WebTarget instance can be used to derive other web targets. Use the following code to define a path to the resource.

WebTarget resourceWebTarget = webTarget.path("resource");

The resourceWebTarget now points to the resource on URI "http://example.com/rest/resource". Again if we configure the resourceWebTarget with a filter specific to the resource, it will not influence the original webTarget instance. However, the filter FilterForExampleCom registration will still be inherited by theresourceWebTarget as it has been created from webTarget. This mechanism allows you to share the common configuration of related resources (typically hosted under the same URI root, in our case represented by the webTarget instance), while allowing for further configuration specialization based on the specific requirements of each individual resource. The same configuration principles of inheritance (to allow common config propagation) and decoupling (to allow individual config customization) applies to all components in JAX-RS Client API discussed below.

Let's say there is a sub resource on the path "http://example.com/rest/resource/helloworld". You can derive a WebTarget for this resource simply by:

WebTarget helloworldWebTarget = resourceWebTarget.path("helloworld");

Let's assume that the helloworld resource accepts a query param for GET requests which defines the greeting message. The next code snippet shows a code that creates a new WebTarget with the query param defined.

WebTarget helloworldWebTargetWithQueryParam =
        helloworldWebTarget.queryParam("greeting", "Hi World!");

Please note that apart from methods that can derive new WebTarget instance based on a URI path or query parameters, the JAX-RS WebTarget API contains also methods for working with matrix parameters too.

5.3.5. Invoking a HTTP request

Let's now focus on invoking a GET HTTP request on the created web targets. To start building a new HTTP request invocation, we need to create a new Invocation.Builder.

Invocation.Builder invocationBuilder =
        helloworldWebTargetWithQueryParam.request(MediaType.TEXT_PLAIN_TYPE);
invocationBuilder.header("some-header", "true");

A new invocation builder instance is created using one of the request(...) methods that are available on WebTarget. A couple of these methods accept parameters that let you define the media type of the representation requested to be returned from the resource. Here we are saying that we request a "text/plain" type. This tells Jersey to add a Accept: text/plain HTTP header to our request.

The invocationBuilder is used to setup request specific parameters. Here we can setup headers for the request or for example cookie parameters. In our example we set up a "some-header" header to value true.

Once finished with request customizations, it's time to invoke the request. We have two options now. We can use the Invocation.Builder to build a generic Invocationinstance that will be invoked some time later. Using Invocation we will be able to e.g. set additional request properties which are properties in a batch of several requests and use the generic JAX-RS Invocation API to invoke the batch of requests without actually knowing all the details (such as request HTTP method, configuration etc.). Any properties set on an invocation instance can be read during the request processing. For example, in a custom ClientRequestFilter you can call getProperty()method on the supplied ClientRequestContext to read a request property. Note that these request properties are different from the configuration properties set onConfigurable. As mentioned earlier, an Invocation instance provides generic invocation API to invoke the HTTP request it represents either synchronously or asynchronously. See the Chapter 10, Asynchronous Services and Clients for more information on asynchronous invocations.

In case you do not want to do any batch processing on your HTTP request invocations prior to invoking them, there is another, more convenient approach that you can use to invoke your requests directly from an Invocation.Builder instance. This approach is demonstrated in the next Java code listing.

Response response = invocationBuilder.get();

While short, the code in the example performs multiple actions. First, it will build the the request from the invocationBuilder. The URI of request will behttp://example.com/rest/resource/helloworld?greeting="Hi%20World!" and the request will contain some-header: true and Accept: text/plain headers. The request will then pass trough all configured request filters ( AnotherClientFilterThirdClientFilter and FilterForExampleCom). Once processed by the filters, the request will be sent to the remote resource. Let's say the resource then returns an HTTP 200 message with a plain text response content that contains the value sent in the request greeting query parameter. Now we can observe the returned response:

System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));

which will produce the following output to the console:

200
Hi World!

As we can see, the request was successfully processed (code 200) and returned an entity (representation) is "Hi World!". Note that since ve have configured aMyClientResponseFilter in the resource target, when response.readEntity(String.class) gets called, the response returned from the remote endpoint is passed through the response filter chain (including the MyClientResponseFilter) and entity interceptor chain and at last a proper MessageBodyReader<T> is located to read the response content bytes from the response stream into a Java String instance. Check Chapter 9, Filters and Interceptors to lear more about request and response filters and entity interceptors.

Imagine now that you would like to invoke a POST request but without any query parameters. You would just use the helloworldWebTarget instance created earlier and call the post() instead of get().

Response postResponse =
        helloworldWebTarget.request(MediaType.TEXT_PLAIN_TYPE)
                .post(Entity.entity("A string entity to be POSTed", MediaType.TEXT_PLAIN));

5.3.6. Example summary

The following code puts together the pieces used in the earlier examples.

Example 5.2. Using JAX-RS Client API

ClientConfig clientConfig = new ClientConfig();
clientConfig.register(MyClientResponseFilter.class);
clientConfig.register(new AnotherClientFilter());

Client client = ClientBuilder.newClient(clientConfig);
client.register(ThirdClientFilter.class);

WebTarget webTarget = client.target("http://example.com/rest");
webTarget.register(FilterForExampleCom.class);
WebTarget resourceWebTarget = webTarget.path("resource");
WebTarget helloworldWebTarget = resourceWebTarget.path("helloworld");
WebTarget helloworldWebTargetWithQueryParam =
        helloworldWebTarget.queryParam("greeting", "Hi World!");

Invocation.Builder invocationBuilder =
        helloworldWebTargetWithQueryParam.request(MediaType.TEXT_PLAIN_TYPE);
invocationBuilder.header("some-header", "true");

Response response = invocationBuilder.get();
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));


Now we can try to leverage the fluent API style to write this code in a more compact way.

Example 5.3. Using JAX-RS Client API fluently

Client client = ClientBuilder.newClient(new ClientConfig()
            .register(MyClientResponseFilter.class)
            .register(new AnotherClientFilter()));

String entity = client.target("http://example.com/rest")
            .register(FilterForExampleCom.class)
            .path("resource/helloworld")
            .queryParam("greeting", "Hi World!")
            .request(MediaType.TEXT_PLAIN_TYPE)
            .header("some-header", "true")
            .get(String.class);


The code above does the same thing except it skips the generic Response processing and directly requests an entity in the last get(String.class) method call. This shortcut method let's you specify that (in case the response was returned successfully with a HTTP 2xx status code) the response entity should be returned as Java Stringtype. This compact example demonstrates another advantage of the JAX-RS client API. The fluency of JAX-RS Client API is convenient especially with simple use cases. Here is another a very simple GET request returning a String representation (entity):

String responseEntity = ClientBuilder.newClient()
            .target("http://example.com").path("resource/rest")
                        .request().get(String.class);

5.4. Java instances and types for representations

All the Java types and representations supported by default on the Jersey server side for requests and responses are also supported on the client side. For example, to process a response entity (or representation) as a stream of bytes use InputStream as follows:

InputStream in = response.readEntity(InputStream.class);

... // Read from the stream

in.close();
            

Note that it is important to close the stream after processing so that resources are freed up.

To POST a file use a File instance as follows:

File f = ...

...

webTarget.request().post(Entity.entity(f, MediaType.TEXT_PLAIN_TYPE));
            

5.4.1. Adding support for new representations

The support for new application-defined representations as Java types requires the implementation of the same JAX-RS entity provider extension interfaces as for the server side JAX-RS API, namely MessageBodyReader<T> and MessageBodyWriter<T> respectively, for request and response entities (or inbound and outbound representations).

Classes or implementations of the provider-based interfaces need to be registered as providers within the JAX-RS or Jersey Client API components that implementConfigurable contract (ClientBuilderClientWebTarget or ClientConfig), as was shown in the earlier sections. Some media types are provided in the form of JAX-RS Feature a concept that allows the extension providers to group together multiple different extension providers and/or configuration properties in order to simplify the registration and configuration of the provided feature by the end users. For example, MoxyJsonFeature can be register to enable and configure JSON binding support via MOXy library.

5.5. Client Transport Connectors

By default, the transport layer in Jersey is provided by HttpUrlConnection. This transport is implemented in Jersey via HttpUrlConnector that implements Jersey-specificConnector SPI. You can implement and/or register your own Connector instance to the Jersey Client implementation, that will replace the defaultHttpUrlConnection-based transport layer. Jersey provides several alternative client transport connector implementations that are ready-to-use. You can useApacheConnector (add a maven dependency to org.glassfish.jersey.connectors:jersey-apache-connector) or GrizzlyConnector (add a maven dependency to org.glassfish.jersey.connectors:jersey-grizzly-connector) alternatively. Please, note again, that the Connector SPI is not a feature of JAX-RS but is a Jersey-specific extension API that will only work with Jersey. Following example shows how to setup the custom Connector to the Jersey client.

ClientConfig clientConfig = new ClientConfig();
Connector connector = new GrizzlyConnector(clientConfig);
clientConfig.connector(connector);
Client client = ClientBuilder.newClient(clientConfig);

Client accepts as as a constructor argument a Configurable instance. Jersey implementation of the Configurable provider for the client is ClientConfig. By using the Jersey ClientConfig you can configure the custom Connector into the ClientConfig. The GrizzlyConnector is used as a custom connector in the example above. Please note that the connector cannot be registered as a provider using Configurable.register(...) at the moment.

5.6. Using client request and response filters

Filtering requests and responses can provide useful lower-level concept focused on a certain independent aspect or domain that is decoupled from the application layer of building and sending requests, and processing responses. Filters can read/modify the request URI, headers and entity or read/modify the response status, headers and entity.

Jersey contains the following useful client-side filters that you may want to use in your applications:

CsrfProtectionFilter: Cross-site request forgery protection filter (adds X-Requested-By to each state changing request).
EncodingFeature: Feature that registers encoding filter which use registered ContentEncoders to encode and decode the communication. The encoding/decoding is performed in interceptor (you don't need to register this interceptor). Check the javadoc of the EncodingFeature in order to use it.
HttpBasicAuthFilter: HTTP Basic Authentication filter (see ??? below).

Note that these features are provided by Jersey, but since they use and implement JAX-RS API, the features should be portable and run in any JAX-RS implementation, not just Jersey. See Chapter 9, Filters and Interceptors chapter for more information on filters and interceptors.

5.7. Securing a Client

This section describes how to setup SSL configuration on Jersey client (using JAX-RS API). The SSL configuration is setup in ClientBuilder. The client builder contains methods for definition of KeyStoreTrustStore or entire SslContext. See the following example:

SSLContext ssl = ... your configured SSL context;
Client client = ClientBuilder.newBuilder().sslContext(ssl).build();
Response response = client.target("https://example.com/resource").request().get();

The example above shows how to setup a custom SslContext to the ClientBuilder. Creating a SslContext can be more difficult as you might need to init instance properly with the protocol, KeyStoreTrustStore, etc. Jersey offers a utility ClientConfig class that can be used to setup the SslContext. The SslConfiguratorcan be configured based on standardized system properties for SSL configuration, so for example you can configure the KeyStore file name using a environment variablejavax.net.ssl.keyStore and SslConfigurator will use such a variable to setup the SslContext. See javadoc of ClientConfig for more details. The following code shows how a SslConfigurator can be used to create a custom SSL context.

SslConfigurator sslConfig = SslConfigurator.newInstance()
        .trustStoreFile("./truststore_client")
        .trustStorePassword("secret-password-for-truststore")
        .keyStoreFile("./keystore_client")
        .keyPassword("secret-password-for-keystore");

SSLContext sslContext = sslConfig.createSSLContext();
Client client = ClientBuilder.newBuilder().sslContext(sslContext).build();

Note that you can also setup KeyStore and TrustStore directly on a ClientBuilder instance without wrapping them into the SslContext. However, if you setup aSslContext it will override any previously defined KeyStore and TrustStore settings. ClientBuilder also offers a method for defining a custom HostnameVerifierimplementation. HostnameVerifier implementations are invoked when default host URL verification fails.

Important

Note that to utilize HTTP with SSL it is necessary to utilize the “https” scheme.

Currently the default connector HttpUrlConnector based on HttpUrlConnection implements support for SSL defined by JAX-RS configuration discussed in this sample.

5.7.1. HTTP Basic Authentication Support

Jersey contains a filter that allows client to authenticate to servers which requires HTTP Basic Authentication. Use HttpBasicAuthFilter to add authentication header to requests initiated from from the client. See the example of how to configure and register the filter:

client.register(new HttpBasicAuthFilter("Homer", "SecretPassword"));

Chapter 6. Representations and Responses

6.1. Representations and Java Types

Previous sections on @Produces and @Consumes annotations referred to media type of an entity representation. Examples above depicted resource methods that could consume and/or produce String Java type for a number of different media types. This approach is easy to understand and relatively straightforward when applied to simple use cases.

To cover also other cases, handling non-textual data for example or handling data stored in the file system, etc., JAX-RS implementations are required to support also other kinds of media type conversions where additional, non-String, Java types are being utilized. Following is a short listing of the Java types that are supported out of the box with respect to supported media type:

  • All media types (*/*)
    • byte[]
    • java.lang.String
    • java.io.Reader (inbound only)
    • java.io.File
    • javax.activation.DataSource
    • javax.ws.rs.core.StreamingOutput (outbound only)
  • XML media types (text/xmlapplication/xml and application/...+xml)
    • javax.xml.transform.Source
    • javax.xml.bind.JAXBElement
    • Application supplied JAXB classes (types annotated with @XmlRootElement or@XmlType)
  • Form content (application/x-www-form-urlencoded)
    • MultivaluedMap<String,String>
  • Plain text (text/plain)
    • java.lang.Boolean
    • java.lang.Character
    • java.lang.Number

Unlike method parameters that are associated with the extraction of request parameters, the method parameter associated with the representation being consumed does not require annotating. In other words the representation (entity) parameter does not require a specific 'entity' annotation. A method parameter without a annotation is an entity. A maximum of one such unannotated method parameter may exist since there may only be a maximum of one such representation sent in a request.

The representation being produced corresponds to what is returned by the resource method. For example JAX-RS makes it simple to produce images that are instance ofFile as follows:

Example 6.1. Using File with a specific media type to produce a response

@GET
@Path("/images/{image}")
@Produces("image/*")
public Response getImage(@PathParam("image") String image) {
  File f = new File(image);

  if (!f.exists()) {
    throw new WebApplicationException(404);
  }

  String mt = new MimetypesFileTypeMap().getContentType(f);
  return Response.ok(f, mt).build();
}


The File type can also be used when consuming a representation (request entity). In that case a temporary file will be created from the incoming request entity and passed as a parameter to the resource method.

The Content-Type response header (if not set programmatically as described in the next section) will be automatically set based on the media types declared by@Produces annotation. Given the following method, the most acceptable media type is used when multiple output media types are allowed:

@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson() {
  ...
}

If application/xml is the most acceptable media type defined by the request (e.g. by header Accept: application/xml), then the Content-Type response header will be set to application/xml.

6.2. Building Responses

Sometimes it is necessary to return additional information in response to a HTTP request. Such information may be built and returned using Response andResponse.ResponseBuilder. For example, a common RESTful pattern for the creation of a new resource is to support a POST request that returns a 201 (Created) status code and a Location header whose value is the URI to the newly created resource. This may be achieved as follows:

Example 6.2. Returning 201 status code and adding Location header in response to POST request

@POST
@Consumes("application/xml")
public Response post(String content) {
  URI createdUri = ...
  create(content);
  return Response.created(createdUri).build();
}


In the above no representation produced is returned, this can be achieved by building an entity as part of the response as follows:

Example 6.3. Adding an entity body to a custom response

@POST
@Consumes("application/xml")
public Response post(String content) {
  URI createdUri = ...
  String createdContent = create(content);
  return Response.created(createdUri).entity(Entity.text(createdContent)).build();
}


Response building provides other functionality such as setting the entity tag and last modified date of the representation.

6.3. WebApplicationException and Mapping Exceptions to Responses

Previous section shows how to return HTTP responses, that are built up programmatically. It is possible to use the very same mechanism to return HTTP errors directly, e.g. when handling exceptions in a try-catch block. However, to better align with the Java programming model, JAX-RS allows to define direct mapping of Java exceptions to HTTP error responses.

The following example shows throwing CustomNotFoundException from a resource method in order to return an error HTTP response to the client:

Example 6.4. Throwing exceptions to control response

@Path("items/{itemid}/")
public Item getItem(@PathParam("itemid") String itemid) {
  Item i = getItems().get(itemid);
  if (i == null) {
    throw new CustomNotFoundException("Item, " + itemid + ", is not found");
  }

  return i;
}


This exception is an application specific exception that extends WebApplicationException and builds a HTTP response with the 404 status code and an optional message as the body of the response:

Example 6.5. Application specific exception implementation

public class CustomNotFoundException extends WebApplicationException {

  /**
  * Create a HTTP 404 (Not Found) exception.
  */
  public CustomNotFoundException() {
    super(Responses.notFound().build());
  }

  /**
  * Create a HTTP 404 (Not Found) exception.
  * @param message the String that is the entity of the 404 response.
  */
  public CustomNotFoundException(String message) {
    super(Response.status(Responses.NOT_FOUND).
    entity(message).type("text/plain").build());
  }
}


In other cases it may not be appropriate to throw instances of WebApplicationException, or classes that extend WebApplicationException, and instead it may be preferable to map an existing exception to a response. For such cases it is possible to use a custom exception mapping provider. The provider must implement theExceptionMapper<E extends Throwable> interface. For example, the following maps the EntityNotFoundException to a HTTP 404 (Not Found) response:

Example 6.6. Mapping generic exceptions to responses

@Provider
public class EntityNotFoundMapper implements ExceptionMapper<javax.persistence.EntityNotFoundException> {
  public Response toResponse(javax.persistence.EntityNotFoundException ex) {
    return Response.status(404).
      entity(ex.getMessage()).
      type("text/plain").
      build();
  }
}


The above class is annotated with @Provider, this declares that the class is of interest to the JAX-RS runtime. Such a class may be added to the set of classes of theApplication instance that is configured. When an application throws an EntityNotFoundException the toResponse method of the EntityNotFoundMapper instance will be invoked.

Jersey supports extension of the exception mappers. These extended mappers must implement the org.glassfish.jersey.spi.ExtendedExceptionMapperinterface. This interface additionally defines method isMappable(Throwable) which will be invoked by the Jersey runtime when exception is thrown and this provider is considered as mappable based on the exception type. Using this method the provider can reject mapping of the exception before the method toResponse is invoked. The provider can for example check the exception parameters and based on them return false and let other provider to be chosen for the exception mapping.

6.4. Conditional GETs and Returning 304 (Not Modified) Responses

Conditional GETs are a great way to reduce bandwidth, and potentially improve on the server-side performance, depending on how the information used to determine conditions is calculated. A well-designed web site may for example return 304 (Not Modified) responses for many of static images it serves.

JAX-RS provides support for conditional GETs using the contextual interface Request.

The following example shows conditional GET support:

Example 6.7. Conditional GET support

public SparklinesResource(
  @QueryParam("d") IntegerList data,
  @DefaultValue("0,100") @QueryParam("limits") Interval limits,
  @Context Request request,
  @Context UriInfo ui) {
  if (data == null) {
    throw new WebApplicationException(400);
  }

  this.data = data;
  this.limits = limits;

  if (!limits.contains(data)) {
    throw new WebApplicationException(400);
  }

  this.tag = computeEntityTag(ui.getRequestUri());

  if (request.getMethod().equals("GET")) {
    Response.ResponseBuilder rb = request.evaluatePreconditions(tag);
    if (rb != null) {
      throw new WebApplicationException(rb.build());
    }
  }
}


The constructor of the SparklinesResouce root resource class computes an entity tag from the request URI and then calls the request.evaluatePreconditions with that entity tag. If a client request contains an If-None-Match header with a value that contains the same entity tag that was calculated then the evaluatePreconditions returns a pre-filled out response, with the 304 status code and entity tag set, that may be built and returned. Otherwise, evaluatePreconditions returns null and the normal response can be returned.

Notice that in this example the constructor of a resource class is used to perform actions that may otherwise have to be duplicated to invoked for each resource method. The life cycle of resource classes is per-request which means that the resource instance is created for each request and therefore can work with request parameters and for example make changes to the request processing by throwing an exception as it is shown in this example.

Chapter 7. JAX-RS Entity Providers

7.1. Introduction

Entity payload, if present in an received HTTP message, is passed to Jersey from an I/O container as an input stream. The stream may, for example, contain data represented as a plain text, XML or JSON document. However, in many JAX-RS components that process these inbound data, such as resource methods or client responses, the JAX-RS API user can access the inbound entity as an arbitrary Java object that is created from the content of the input stream based on the representation type information. For example, an entity created from an input stream that contains data represented as a XML document, can be converted to a custom JAXB bean. Similar concept is supported for the outbound entities. An entity returned from the resource method in the form of an arbitrary Java object can be serialized by Jersey into a container output stream as a specified representation. Of course, while JAX-RS implementations do provide default support for most common combinations of Java type and it's respective on-the-wire representation formats, JAX-RS implementations do not support the conversion described above for any arbitrary Java type and any arbitrary representation format by default. Instead, a generic extension concept is exposed in JAX-RS API to allow application-level customizations of this JAX-RS runtime to support for entity conversions. The JAX-RS extension API components that provide the user-level extensibility are typically referred to by several terms with the same meaning, such as entity providersmessage body providersmessage body workers or message body readers and writers. You may find all these terms used interchangeably throughout the user guide and they all refer to the same concept.

In JAX-RS extension API (or SPI - service provider interface, if you like) the concept is captured in 2 interfaces. One for handling inbound entity representation-to-Java de-serialization - MessageBodyReader<T> and the other one for handling the outbound entity Java-to-representation serialization - MessageBodyWriter<T>. AMessageBodyReader<T>, as the name suggests, is an extension that supports reading the message body representation from an input stream and converting the data into an instance of a specific Java type. A MessageBodyWriter<T> is then responsible for converting a message payload from an instance of a specific Java type into a specific representation format that is sent over the wire to the other party as part of an HTTP message exchange. Both of these providers can be used to provide message payload serialization and de-serialization support on the server as well as the client side. A message body reader or writer is always used whenever a HTTP request or response contains an entity and the entity is either requested by the application code (e.g. injected as a parameter of JAX-RS resource method or a response entity read on the client from a Response) or has to be serialized and sent to the other party (e.g. an instance returned from a JAX-RS resource method or a request entity sent by a JAX-RS client).

7.2. How to Write Custom Entity Providers

A best way how to learn about entity providers is to walk through an example of writing one. Therefore we will describe here the process of implementing a customMessageBodyWriter<T> and MessageBodyReader<T> using a practical example. Let's first setup the stage by defining a JAX-RS resource class for the server side story of our application.

Example 7.1. Example resource class

@Path("resource")
public class MyResource {
    @GET
    @Produces("application/xml")
    public MyBean getMyBean() {
        return new MyBean("Hello World!", 42);
    }

    @POST
    @Consumes("application/xml")
    public String postMyBean(MyBean myBean) {
        return myBean.anyString;
    }
}


The resource class defines GET and POST resource methods. Both methods work with an entity that is an instance of MyBean.

The MyBean class is defined in the next example:

Example 7.2. MyBean entity class

@XmlRootElement
public class MyBean {
    @XmlElement
    public String anyString;
    @XmlElement
    public int anyNumber;

    public MyBean(String anyString, int anyNumber) {
        this.anyString = anyString;
        this.anyNumber = anyNumber;
    }

    // empty constructor needed for deserialization by JAXB
    public MyBean() {
    }

    @Override
    public String toString() {
        return "MyBean{" +
            "anyString='" + anyString + '\'' +
            ", anyNumber=" + anyNumber +
            '}';
    }
}


7.2.1. MessageBodyWriter

The MyBean is a JAXB-annotated POJO. In GET resource method we return the instance of MyBean and we would like Jersey runtime to serialize it into XML and write it as an entity body to the response output stream. We design a custom MessageBodyWriter<T> that can serialize this POJO into XML. See the following code sample:

Note

Please note, that this is only a demonstration of how to write a custom entity provider. Jersey already contains default support for entity providers that can serialize JAXB beans into XML.

Example 7.3. MessageBodyWriter example

@Produces("application/xml")
public class MyBeanMessageBodyWriter implements MessageBodyWriter<MyBean> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
                               Annotation[] annotations, MediaType mediaType) {
        return type == MyBean.class;
    }

    @Override
    public long getSize(MyBean myBean, Class<?> type, Type genericType,
                        Annotation[] annotations, MediaType mediaType) {
        // deprecated by JAX-RS 2.0 and ignored by Jersey runtime
        return 0;
    }

    @Override
    public void writeTo(MyBean myBean,
                        Class<?> type,
                        Type genericType,
                        Annotation[] annotations,
                        MediaType mediaType,
                        MultivaluedMap<String, Object> httpHeaders,
                        OutputStream entityStream)
                        throws IOException, WebApplicationException {

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(MyBean.class);

            // serialize the entity myBean to the entity output stream
            jaxbContext.createMarshaller().marshal(myBean, entityStream);
        } catch (JAXBException jaxbException) {
            throw new ProcessingException(
                "Error serializing a MyBean to the output stream", jaxbException);
        }
    }
}


The MyBeanMessageBodyWriter implements the MessageBodyWriter<T> interface that contains three methods. In the next sections we'll explore these methods more closely.

7.2.1.1.  MessageBodyWriter.isWriteable

A method isWriteable should return true if the MessageBodyWriter<T> is able to write the given type. Method does not decide only based on the Java type of the entity but also on annotations attached to the entity and the requested representation media type.

Parameters type and genericType both define the entity, where type is a raw Java type (for example, a java.util.List class> and genericType is aParameterizedType including generic information (for example List<String>).

Parameter annotations contains annotations that are either attached to the resource method and/or annotations that are attached to the entity by building response like in the following piece of code:

Example 7.4. Example of assignment of annotations to a response entity

@Path("resource")
public static class AnnotatedResource {

    @GET
    public Response get() {
        Annotation annotation = AnnotatedResource.class
                            .getAnnotation(Path.class);
        return Response.ok()
                .entity("Entity", new Annotation[] {annotation}).build();
    }
}


In the example above, the MessageBodyWriter<T> would get annotations parameter containing a JAX-RS @GET annotation as it annotates the resource method and also a @Path annotation as it is passed in the response (but not because it annotates the resource; only resource method annotations are included). In the case ofMyResource and method getMyBean the annotations would contain the @GET and the @Produces annotation.

The last parameter of the isWriteable method is the mediaType which is the media type attached to the response entity by annotating the resource method with a@Produces annotation or the request media type specified in the JAX-RS Client API. In our example, the media type passed to providers for the resource MyResource and method getMyBean would be "application/xml".

In our implementation of the isWriteable method, we just check that the type is MyBean. Please note, that this method might be executed multiple times by Jersey runtime as Jersey needs to check whether this provider can be used for a particular combination of entity Java type, media type, and attached annotations, which may be potentially a performance hog. You can limit the number of execution by properly defining the @Produces annotation on the MessageBodyWriter<T>. In our case thanks to @Produces annotation, the provider will be considered as writeable (and the method isWriteable might be executed) only if the media type of the outbound message is "application/xml". Additionally, the provider will only be considered as possible candidate and its isWriteable method will be executed, if the generic type of the provider is either a sub class or super class of type parameter.

7.2.1.2.  MessageBodyWriter.writeTo

Once a message body writer is selected as the most appropriate (see the Section 7.3, “Entity Provider Selection” for more details on entity provider selection), its writeTomethod is invoked. This method receives parameters with the same meaning as in isWriteable as well as a few additional ones.

In addition to the parameters already introduced, the writeTo method defies also httpHeaders parameter, that contains HTTP headers associated with the outbound message.

Note

When a MessageBodyWriter<T> is invoked, the headers still can be modified in this point and any modification will be reflected in the outbound HTTP message being sent. The modification of headers must however happen before a first byte is written to the supplied output stream.

Another new parameter, myBean, contains the entity instance to be serialized (the type of entity corresponds to generic type of MessageBodyWriter<T>). Related parameter entityStream contains the entity output stream to which the method should serialize the entity. In our case we use JAXB to marshall the entity into theentityStream. Note, that the entityStream is not closed at the end of method; the stream will be closed by Jersey.

Important

Do not close the entity output stream in the writeTo method of your MessageBodyWriter<T> implementation.

7.2.1.3.  MessageBodyWriter.getSize

The method is deprecated since JAX-RS 2.0 and Jersey 2 ignores the return value. In JAX-RS 1.0 the method could return the size of the entity that would be then used for "Content-Length" response header. In Jersey 2.0 the "Content-Length" parameter is computed automatically using an internal outbound entity buffering. For details about configuration options of outbound entity buffering see the javadoc of MessageProperties, property OUTBOUND_CONTENT_LENGTH_BUFFER which configures the size of the buffer.

Note

You can disable the Jersey outbound entity buffering by setting the buffer size to 0.

7.2.1.4. Testing a MessageBodyWriter<T>

Before testing the MyBeanMessageBodyWriter, the writer must be registered as a custom JAX-RS extension provider. It should either be added to your applicationResourceConfig, or returned from your custom Application sub-class, or annotated with @Provider annotation to leverage JAX-RS provider auto-discovery feature.

After registering the MyBeanMessageBodyWriter and MyResource class in our application, the request can be initiated (in this example from Client API).

Example 7.5. Client code testing MyBeanMessageBodyWriter

WebTarget webTarget = // initialize web target to the context root
            // of example application
Response response = webTarget.path("resource")
                        .request(MediaType.APPLICATION_XML).get();
System.out.println(response.getStatus());
String myBeanXml = response.readEntity(String.class);
System.out.println(myBeanXml);


The client code initiates the GET which will be matched to the resource method MyResource.getMyBean(). The response entity is de-serialized as a String.

The result of console output is:

Example 7.6. Result of MyBeanMessageBodyWriter test

200
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><myBean>
<anyString>Hello World!</anyString><anyNumber>42</anyNumber></myBean>


The returned status is 200 and the entity is stored in the response in a XML format. Next, we will look at how the Jersey de-serializes this XML document into a MyBeanconsumed by our POST resource method.

7.2.2. MessageBodyReader

In order to de-serialize the entity of MyBean on the server or the client, we need to implement a custom MessageBodyReader<T>.

Note

Please note, that this is only a demonstration of how to write a custom entity provider. Jersey already contains default support for entity providers that can serialize JAXB beans into XML.

Our MessageBodyReader<T> implementation is listed in Example 7.7, “MessageBodyReader example”.

Example 7.7. MessageBodyReader example

public static class MyBeanMessageBodyReader
        implements MessageBodyReader<MyBean> {

@Override
public boolean isReadable(Class<?> type, Type genericType,
    Annotation[] annotations, MediaType mediaType) {
    return type == MyBean.class;
}

@Override
public MyBean readFrom(Class<MyBean> type,
    Type genericType,
    Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, String> httpHeaders,
    InputStream entityStream)
        throws IOException, WebApplicationException {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(MyBean.class);
        MyBean myBean = (MyBean) jaxbContext.createUnmarshaller()
            .unmarshal(entityStream);
        return myBean;
    } catch (JAXBException jaxbException) {
        throw new ProcessingException("Error deserializing a MyBean.",
            jaxbException);
    }
}
}


It is obvious that the MessageBodyReader<T> interface is similar to MessageBodyWriter<T>. In the next couple of sections we will explore it's API methods.

7.2.2.1. MessageBodyReader.isReadable

It defines the method isReadable() which has a very simliar meaning as method isWriteable() in MessageBodyWriter<T>. The method returns true if it is able to de-serialize the given type. The annotations parameter contains annotations that are attached to the entity parameter in the resource method. In our POST resource method postMyBean the entity parameter myBean is not annotated, therefore no annotation will be passed to the isReadable. The mediaType parameter contains the entity media type. The media type, in our case, must be consumable by the POST resource method, which is specified by placing a JAX-RS @Consumes annotation to the method. The resource method postMyBean() is annotated with @Consumes("application/xml"), therefore for purpose of de-serialization of entity for thepostMyBean() method, only requests with entities represented as "application/xml" media type will match the method. However, this method might be executed for for entity types that are sub classes or super classes of the declared generic type on the MessageBodyReader<T> will be also considered. It is a responsibility of theisReadable method to decide whether it is able to de-serialize the entity and type comparison is one of the basic decision steps.

Tip

In order to reduce number of isReadable executions, always define correctly the consumable media type(s) with the @Consumes annotation on your custom MessageBodyReader<T>.

7.2.2.2. MessageBodyReader.readFrom

The readForm() method gets the parameters with the same meaning as in isReadable(). The additional entityStream parameter provides a handle to the entity input stream from which the entity bytes should be read and de-serialized into a Java entity which is then returned from the method. Our MyBeanMessageBodyReader de-serializes the incoming XML data into an instance of MyBean using JAXB.

Important

Do not close the entity input stream in your MessageBodyReader<T> implementation. The stream will be automatically closed by Jersey runtime.

7.2.2.3. Testing a MessageBodyWriter<T>

Now let's send a test request using the JAX-RS Client API.

Example 7.8. Testing MyBeanMessageBodyReader

final MyBean myBean = new MyBean("posted MyBean", 11);
Response response = webTarget.path("resource").request("application/xml")
        .post(Entity.entity(myBean, "application/xml"));

System.out.println(response.getStatus());
final String responseEntity = response.readEntity(String.class);
System.out.println(responseEntity);


The console output is:

Example 7.9. Result of testing MyBeanMessageBodyReader

200
posted MyBean


7.2.2.4. Using Entity Providers with JAX-RS Client API

Both, MessageBodyReader<T> and MessageBodyWriter<T> can be registered in a configuration of JAX-RS Client API components typically without any need to change their code. The example Example 7.10, “MessageBodyReader registered on a JAX-RS client” is a variation on the Example 7.5, “Client code testing MyBeanMessageBodyWriter” listed in one of the previous sections.

Example 7.10. MessageBodyReader registered on a JAX-RS client

Client client = ClientBuilder.newBuilder()
    .register(MyBeanMessageBodyReader.class).build();

Response response = client.target("http://example/comm/resource")
    .request(MediaType.APPLICATION_XML).get();
System.out.println(response.getStatus());
MyBean myBean = response.readEntity(MyBean.class);
System.out.println(myBean);


The code above registers MyBeanMessageBodyReader to the Client configuration using a ClientBuilder which means that the provider will be used for any WebTargetproduced by the client instance.

Note

You could also register the JAX-RS entity (and any other) providers to individual WebTarget instances produced by the client.

Then, using the fluent chain of method invocations, a resource target pointing to our MyResource is defined, a HTTP GET request is invoked. The response entity is then read as an instance of a MyBean type by invoking the response.readEntity method, that internally locates the registered MyBeanMessageBodyReader and uses it for entity de-serialization.

The console output for the example is:

Example 7.11. Result of client code execution

200
MyBean{anyString='Hello World!', anyNumber=42}


7.3. Entity Provider Selection

Usually there are many entity providers registered on the server or client side (be default there must be at least providers mandated by the JAX-RS specification, such as providers for primitive types, byte array, JAXB beans, etc.). JAX-RS defines an algorithm for selecting the most suitable provider for entity processing. This algorithm works with information such as entity Java type and on-the-wire media type representation of entity, and searches for the most suitable entity provider from the list of available providers based on the supported media type declared on each provider (defined by @Produces or @Consumes on the provider class) as well as based on the generic type declaration of the available providers. When a list of suitable candidate entity providers is selected and sorted based on the rules defined in JAX-RS specification, a JAX-RS runtime then it invokes isReadable or isWriteable method respectively on each provider in the list until a first provider is found that returns true. This provider is then used to process the entity.

The following steps describe the algorithm for selecting a MessageBodyWriter<T> (extracted from JAX-RS with little modifications). The steps refer to the previously discussed example application. The MessageBodyWriter<T> is searched for purpose of deserialization of MyBean entity returned from the method getMyBean. So, type is MyBean and media type "application/xml". Let's assume the runtime contains also registered providers, namely:

A@Produces("application/*") with generic type <Object>
B@Produces("*/*") with generic type <MyBean>
C@Produces("text/plain") with generic type <MyBean>
D@Produces("application/xml") with generic type <Object>
MyBeanMessageBodyWriter@Produces("application/xml") with generic type <MyBean>

The algorithm executed by a JAX-RS runtime to select a proper MessageBodyWriter<T> implementation is illustrated in Procedure 7.1, “MessageBodyWriter<T>Selection Algorithm”.

Procedure 7.1. MessageBodyWriter<T> Selection Algorithm

  1. Obtain the object that will be mapped to the message entity body. For a return type of Response or subclasses, the object is the value of the entity property, for other return types it is the returned object.

    So in our case, for the resource method getMyBean the type will be MyBean.

  2. Determine the media type of the response.

    In our case. for resource method getMyBean annotated with @Produces("application/xml"), the media type will be "application/xml".

  3. Select the set of MessageBodyWriter providers that support the object and media type of the message entity body.

    In our case, for entity media type "application/xml" and type MyBean, the appropriate MessageBodyWriter<T> will be the ABD andMyBeanMessageBodyWriter. The provider C does not define the appropriate media type. A and B are fine as their type is more generic and compatible with"application/xml".

  4. Sort the selected MessageBodyWriter providers with a primary key of generic type where providers whose generic type is the nearest superclass of the object class are sorted first and a secondary key of media type. Additionally, JAX-RS specification mandates that custom, user registered providers have to be sorted ahead of default providers provided by JAX-RS implementation. This is used as a tertiary comparison key. User providers are places prior to Jersey internal providers in to the final ordered list.

    The sorted providers will be: MyBeanMessageBodyWriterBDA.

  5. Iterate through the sorted MessageBodyWriter<T> providers and, utilizing the isWriteable method of each until you find a MessageBodyWriter<T> that returns true.

    The first provider in the list - our MyBeanMessageBodyWriter returns true as it compares types and the types matches. If it would return false, the next providerB would by check by invoking its isWriteable method.

  6. If step 5 locates a suitable MessageBodyWriter<T> then use its writeTo method to map the object to the entity body.

    MyBeanMessageBodyWriter.writeTo will be executed and it will serialize the entity.

    • Otherwise, the server runtime MUST generate a generate an InternalServerErrorException, a subclass of WebApplicationException with its status set to 500, and no entity and the client runtime MUST generate a ProcessingException.

      We have successfully found a provider, thus no exception is generated.

Note

JAX-RS 2.0 is incompatible with JAX-RS 1.x in one step of the entity provider selection algorithm. JAX-RS 1.x defines sorting keys priorities in the Step 4 in exactly opposite order. So, in JAX-RS 1.x the keys are defined in the order: primary media type, secondary type declaration distance where custom providers have always precedence to internal providers. If you want to force Jersey to use the algorithm compatible with JAX-RS 1.x, setup the property (toResourceConfig or return from Application from its getProperties method):

jersey.config.workers.legacyOrdering=true

Documentation of this property can be found in the javadoc of MessageProperties.

The algorithm for selection of MessageBodyReader<T> is similar, including the incompatibility between JAX-RS 2.0 and JAX-RS 1.x and the property to workaround it. The algorithm is defined as follows:

Procedure 7.2. MessageBodyReader<T> Selection Algorithm

  1. Obtain the media type of the request. If the request does not contain a Content-Type header then use application/octet-stream media type.

  2. Identify the Java type of the parameter whose value will be mapped from the entity body. The Java type on the server is the type of the entity parameter of the resource method. On the client it is the Class passed to readFrom method.

  3. Select the set of available MessageBodyReader<T> providers that support the media type of the request.

  4. Iterate through the selected MessageBodyReader<T> classes and, utilizing their isReadable method, choose the first MessageBodyReader<T> provider that supports the desired combination of Java type/media type/annotations parameters.

  5. If Step 4 locates a suitable MessageBodyReader<T>, then use its readFrom method to map the entity body to the desired Java type.

    • Otherwise, the server runtime MUST generate a NotSupportedException (HTTP 415 status code) and no entity and the client runtime MUST generate an instance of ProcessingException.

7.4. Jersey MessageBodyWorkers API

In case you need to directly work with JAX-RS entity providers, for example to serialize an entity in your resource method, filter or in a composite entity provider, you would need to perform quite a lot of steps. You would need to choose the appropriate MessageBodyWriter<T> based on the type, media type and other parameters. Then you would need to instantiate it, check it by isWriteable method and basically perform all the steps that are normally performed by Jersey (see Procedure 7.2, “MessageBodyReader<T> Selection Algorithm”).

To remove this burden from developers, Jersey exposes a proprietary public API that simplifies the manipulation of entity providers. The API is defined byMessageBodyWorkers interface and Jersey provides an implementation that can be injected using the @Context injection annotation. The interface declares methods for selection of most appropriate MessageBodyReader<T> and MessageBodyWriter<T> based on the rules defined in JAX-RS spec, methods for writing and reading entity that ensure proper and timely invocation of interceptors and other useful methods.

See the following example of usage of MessageBodyWorkers.

Example 7.12. Usage of MessageBodyWorkers interface

@Path("workers")
public static class WorkersResource {

    @Context
    private MessageBodyWorkers workers;

    @GET
    @Produces("application/xml")
    public String getMyBeanAsString() {

        final MyBean myBean = new MyBean("Hello World!", 42);

        // buffer into which myBean will be serialized
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // get most appropriate MBW
        final MessageBodyWriter<MyBean> messageBodyWriter =
                workers.getMessageBodyWriter(MyBean.class, MyBean.class,
                        new Annotation[]{}, MediaType.APPLICATION_XML_TYPE);

        try {
            // use the MBW to serialize myBean into baos
            messageBodyWriter.writeTo(myBean,
                MyBean.class, MyBean.class, new Annotation[] {},
                MediaType.APPLICATION_XML_TYPE, new MultivaluedHashMap<String, Object>(),
                baos);
        } catch (IOException e) {
            throw new RuntimeException(
                "Error while serializing MyBean.", e);
        }

        final String stringXmlOutput = baos.toString();
        // stringXmlOutput now contains XML representation:
        // "<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        // <myBean><anyString>Hello World!</anyString>
        // <anyNumber>42</anyNumber></myBean>"

        return stringXmlOutput;
    }
}


In the example a resource injects MessageBodyWorkers and uses it for selection of the most appropriate MessageBodyWriter<T>. Then the writer is utilized to serialize the entity into the buffer as XML document. The String content of the buffer is then returned. This will cause that Jersey will not useMyBeanMessageBodyWriter to serialize the entity as it is already in the String type (MyBeanMessageBodyWriter does not support String). Instead, a simpleString-based MessageBodyWriter<T> will be chosen and it will only serialize the String with XML to the output entity stream by writing out the bytes of the String.

Of course, the code in the example does not bring any benefit as the entity could have been serialized by MyBeanMessageBodyWriter by Jersey as in previous examples; the purpose of the example was to show how to use MessageBodyWorkers in a resource method.

7.5. Default Jersey Entity Providers

Jersey internally contains entity providers for these types with combination of media types (in brackets):

byte[] (*/*)
String (*/*)
InputStream (*/*)
Reader (*/*)
File (*/*)
DataSource (*/*)
Source (text/xmlapplication/xml and media types of the form application/*+xml)
JAXBElement (text/xmlapplication/xml and media types of the form application/*+xml)
MultivaluedMap<K,V> (application/x-www-form-urlencoded)
Form (application/x-www-form-urlencoded)
StreamingOutput ((*/*)) - this class can be used as an lightweight MessageBodyWriter<T> that can be returned from a resource method
BooleanCharacter and Number (text/plain) - corresponding primitive types supported via boxing/unboxing conversion

For other media type supported in jersey please see the Chapter 8, Support for Common Media Type Representations which describes additional Jersey entity provider extensions for serialization to JSON, XML, serialization of collections, Multi Part and others.

Chapter 8. Support for Common Media Type Representations

8.1. JSON

Jersey JSON support comes as a set of extension modules where each of these modules contains an implementation of a Feature that needs to be registered into yourConfigurable instance (client/server). There are multiple frameworks that provide support for JSON processing and/or JSON-to-Java binding. The modules listed bellow provide support for JSON representations by integrating the individual JSON frameworks into Jersey. At present, Jersey integrates with the following modules to provide JSON support:

8.1.1. Approaches to JSON Support

Each of the aforementioned extension modules uses one or more of the three basic approaches available when working with JSON representations:

  • POJO based JSON binding support

  • JAXB based JSON binding support

  • Low-level JSON parsing & processing support

The first method is pretty generic and allows you to map any Java Object to JSON and vice versa. The other two approaches limit you in Java types your resource methods could produce and/or consume. JAXB based approach is useful if you plan to utilize certain JAXB features and support both XML and JSON representations. The last, low-level, approach gives you the best fine-grained control over the out-coming JSON data format.

8.1.1.1. POJO support

POJO support represents the easiest way to convert your Java Objects to JSON and back.

Media modules that support this approach are MOXy and Jackson

8.1.1.2. JAXB based JSON support

Taking this approach will save you a lot of time, if you want to easily produce/consume both JSON and XML data format. With JAXB beans you will be able to use a the same Java model to generate JSON as well as XML representations. Another advantage is simplicity of working with such a model and availability of the API in Java SE Platform. JAXB leverages annotated POJOs and these could be handled as simple Java beans.

A disadvantage of JAXB based approach could be if you need to work with a very specific JSON format. Then it might be difficult to find a proper way to get such a format produced and consumed. This is a reason why a lot of configuration options are provided, so that you can control how JAXB beans get serialized and de-serialized. The extra configuration options however requires you to learn more details about the framework you are using.

Following is a very simple example of how a JAXB bean could look like.

Example 8.1. Simple JAXB bean implementation

@XmlRootElement
public class MyJaxbBean {
    public String name;
    public int age;

    public MyJaxbBean() {} // JAXB needs this

    public MyJaxbBean(String name, int age) {
        this.name = name;
        this.age = age;
    }
}


Using the above JAXB bean for producing JSON data format from you resource method, is then as simple as:

Example 8.2. JAXB bean used to generate JSON representation

@GET
@Produces("application/json")
public MyJaxbBean getMyBean() {
    return new MyJaxbBean("Agamemnon", 32);
}


Notice, that JSON specific mime type is specified in @Produces annotation, and the method returns an instance of MyJaxbBean, which JAXB is able to process. Resulting JSON in this case would look like:

{"name":"Agamemnon", "age":"32"}

A proper use of JAXB annotations itself enables you to control output JSON format to certain extent. Specifically, renaming and omitting items is easy to do directly just by using JAXB annotations. For example, the following example depicts changes in the above mentioned MyJaxbBean that will result in {"king":"Agamemnon"} JSON output.

Example 8.3. Tweaking JSON format using JAXB

@XmlRootElement
public class MyJaxbBean {

    @XmlElement(name="king")
    public String name;

    @XmlTransient
    public int age;

    // several lines removed
}


Media modules that support this approach are MOXyJacksonJettison

8.1.1.3. Low-level based JSON support

JSON Processing API is a new standard API for parsing and processing JSON structures in similar way to what SAX and StAX parsers provide for XML. The API is part of Java EE 7 and later. Another such JSON parsing/processing API is provided by Jettison framework. Both APIs provide a low-level access to producing and consuming JSON data structures. By adopting this low-level approach you would be working with JsonObject (or JSONObject respectively) and/or JsonArray (or JSONArrayrespectively) classes when processing your JSON data representations.

The biggest advantage of these low-level APIs is that you will gain full control over the JSON format produced and consumed. You will also be able to produce and consume very large JSON structures using streaming JSON parser/generator APIs. On the other hand, dealing with your data model objects will probably be a lot more complex, compared to the POJO or JAXB based binding approach. Differences are depicted at the following code snippets.

Let's start with JAXB-based approach.

Example 8.4. JAXB bean creation

MyJaxbBean myBean = new MyJaxbBean("Agamemnon", 32);


Above you construct a simple JAXB bean, which could be written in JSON as {"name":"Agamemnon", "age":32}

Now to build an equivalent JsonObject/JSONObject (in terms of resulting JSON expression), you would need several more lines of code. The following example illustrates how to construct the same JSON data using the standard Java EE 7 JSON-Processing API.

Example 8.5. Constructing a JsonObject (JSON-Processing)

JsonObject myObject = Json.createObjectBuilder()
        .add("name", "Agamemnon")
        .add("age", 32)
        .build();


And at last, here's how the same work can be done with Jettison API.

Example 8.6. Constructing a JSONObject (Jettison)

JSONObject myObject = new JSONObject();
try {
    myObject.put("name", "Agamemnon");
    myObject.put("age", 32);
} catch (JSONException ex) {
    LOGGER.log(Level.SEVERE, "Error ...", ex);
}


Media modules that support the low-level JSON parsing and generating approach are Java API for JSON Processing (JSON-P) and Jettison. Unless you have a strong reason for using the non-standard Jettison API, we recommend you to use the new standard Java API for JSON Processing (JSON-P) API instead.

8.1.2. MOXy

8.1.2.1. Dependency

To use MOXy as your JSON provider you need to add jersey-media-moxy module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.0</version>
</dependency>

If you're not using Maven make sure to have all needed dependencies (see jersey-media-moxy) on the classpath.

8.1.2.2. Configure and register

As stated in the Section 4.1, “Auto-Discoverable Features” as well as earlier in this chapter, MOXy media module is one of the modules where you don't need to explicitly register it's Features (MoxyJsonFeature) in your client/server Configurable as this feature is automatically discovered and registered when you add jersey-media-moxy module to your class-path.

The auto-discoverable jersey-media-moxy module defines a few properties that can be used to control the automatic registration of MoxyJsonFeature (besides the generic CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE an the its client/server variants):

Note

A manual registration of any other Jersey JSON provider feature (except for Java API for JSON Processing (JSON-P)) disables the automated enabling and configuration of MoxyJsonFeature.

To configure MessageBodyReader<T>s / MessageBodyWriter<T>s provided by MOXy you can simply create an instance of MoxyJsonConfig and set values of needed properties. For most common properties you can use a particular method to set the value of the property or you can use more generic methods to set the property:

Example 8.7. MoxyJsonConfig - Setting properties.

final Map<String, String> namespacePrefixMapper = new HashMap<String, String>();
namespacePrefixMapper.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");

final MoxyJsonConfig configuration = new MoxyJsonConfig()
        .setNamespacePrefixMapper(namespacePrefixMapper)
        .setNamespaceSeparator(':');
                        


In order to make MoxyJsonConfig visible for MOXy you need to create and register ContextResolver<T> in your client/server code.

Example 8.8. ContextResolver<MoxyJsonConfig>

@Provider
public class JsonMoxyConfigurationContextResolver implements ContextResolver<MoxyJsonConfig> {

    private final MoxyJsonConfig config;

    public JsonMoxyConfigurationContextResolver() {
        final Map<String, String> namespacePrefixMapper = new HashMap<String, String>();
        namespacePrefixMapper.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");

        config = MoxyJsonConfig()
            .setNamespacePrefixMapper(namespacePrefixMapper)
            .setNamespaceSeparator(':');
    }

    @Override
    public MoxyJsonConfig getContext(Class<?> objectType) {
        return config;
    }
}


Another way to pass configuration properties to the underlying MOXyJsonProvider is to set them directly into your Configurable instance (see an example below). These are overwritten by properties set into the MoxyJsonConfig.

Example 8.9. Setting properties for MOXy providers into Configurable

new ResourceConfig()
                            .property(MarshallerProperties.JSON_NAMESPACE_SEPARATOR, ".")
                            // further configuration


There are some properties for which Jersey sets the default value when MessageBodyReader<T> / MessageBodyWriter<T> from MOXy is used and they are:

Table 8.1. Default property values for MOXy MessageBodyReader<T> / MessageBodyWriter<T>

javax.xml.bind.Marshaller#JAXB_FORMATTED_OUTPUT false
org.eclipse.persistence.jaxb.JAXBContextProperties#JSON_INCLUDE_ROOT false
org.eclipse.persistence.jaxb.MarshallerProperties#JSON_MARSHAL_EMPTY_COLLECTIONS true
org.eclipse.persistence.jaxb.JAXBContextProperties#JSON_NAMESPACE_SEPARATOR org.eclipse.persistence.oxm.XMLConstants#DOT


Example 8.10. Building client with MOXy JSON feature enabled.

final Client client = ClientBuilder.newBuilder()
        // The line bellow that registers MOXy feature can be
        // omitted if FEATURE_AUTO_DISCOVERY_DISABLE is
        // not disabled.
        .register(MoxyJsonFeature.class)
        .register(JsonMoxyConfigurationContextResolver.class)
        .build();

Example 8.11. Creating JAX-RS application with MOXy JSON feature enabled.

// Create JAX-RS application.
final Application application = new ResourceConfig()
        .packages("org.glassfish.jersey.examples.jsonmoxy")
        // The line bellow that registers MOXy feature can be
        // omitted if FEATURE_AUTO_DISCOVERY_DISABLE is
        // not disabled.
        .register(MoxyJsonFeature.class)
        .register(JsonMoxyConfigurationContextResolver.class);

8.1.2.3. Examples

Jersey provides an JSON MOXy example on how to use MOXy to consume/produce JSON.

8.1.3. Java API for JSON Processing (JSON-P)

8.1.3.1. Dependency

To use JSON-P as your JSON provider you need to add jersey-media-json-processing module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-processing</artifactId>
    <version>2.0</version>
</dependency>

If you're not using Maven make sure to have all needed dependencies (see jersey-media-json-processing) on the class-path.

8.1.3.2. Configure and register

As stated in Section 4.1, “Auto-Discoverable Features” JSON-Processing media module is one of the modules where you don't need to explicitly register it's Features (JsonProcessingFeature) in your client/server Configurable as this feature is automatically discovered and registered when you add jersey-media-json-processing module to your classpath.

As for the other modules, jersey-media-json-processing has also few properties that can affect the registration of JsonProcessingFeature (besidesCommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE and the like):

To configure MessageBodyReader<T>s / MessageBodyWriter<T>s provided by JSON-P you can simply add values for supported properties into the Configuration instance (client/server). Currently supported are these properties:

  • JsonGenerator.PRETTY_PRINTING ("javax.json.stream.JsonGenerator.prettyPrinting")

Example 8.12. Building client with JSON-Processing JSON feature enabled.

ClientBuilder.newClient(new ClientConfig()
        // The line bellow that registers JSON-Processing feature can be
        // omitted if FEATURE_AUTO_DISCOVERY_DISABLE is not disabled.
        .register(JsonProcessingFeature.class)
        .property(JsonGenerator.PRETTY_PRINTING, true)
);

Example 8.13. Creating JAX-RS application with JSON-Processing JSON feature enabled.

// Create JAX-RS application.
final Application application = new ResourceConfig()
        // The line bellow that registers JSON-Processing feature can be
        // omitted if FEATURE_AUTO_DISCOVERY_DISABLE is not disabled.
        .register(JsonProcessingFeature.class)
        .packages("org.glassfish.jersey.examples.jsonp")
        .property(JsonGenerator.PRETTY_PRINTING, true);

8.1.3.3. Examples

Jersey provides an JSON Processing example on how to use JSON-Processing to consume/produce JSON.

8.1.4. Jackson

8.1.4.1. Dependency

To use Jackson as your JSON provider you need to add jersey-media-json-jackson module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.0</version>
</dependency>

If you're not using Maven make sure to have all needed dependencies (see jersey-media-json-jackson) on the classpath.

8.1.4.2. Configure and register

Jackson JSON processor could be controlled via providing a custom Jackson ObjectMapper instance. This could be handy if you need to redefine the default Jackson behaviour and to fine-tune how your JSON data structures look like. Detailed description of all Jackson features is out of scope of this guide. The example bellow gives you a hint on how to wire your ObjectMapper instance into your Jersey application.

In order to use Jackson as your JSON (JAXB/POJO) provider you need to register JacksonFeature and a ContextResolver<T> for ObjectMapper (if needed) in yourConfigurable (client/server).

Example 8.14. ContextResolver<ObjectMapper>

@Provider
public class MyObjectMapperProvider implements ContextResolver<ObjectMapper> {

    final ObjectMapper defaultObjectMapper;
    final ObjectMapper combinedObjectMapper;

    public MyObjectMapperProvider() {
        defaultObjectMapper = createDefaultMapper();
        combinedObjectMapper = createCombinedObjectMapper();
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        if (type == CombinedAnnotationBean.class) {
            return combinedObjectMapper;
        } else {
            return defaultObjectMapper;
        }
    }

    private static ObjectMapper createDefaultMapper() {
        final ObjectMapper result = new ObjectMapper();
        result.configure(Feature.INDENT_OUTPUT, true);

        return result;
    }

    // ...
}


Example 8.15. Building client with Jackson JSON feature enabled.

final Client client = ClientBuilder.newBuilder()
        .register(MyObjectMapperProvider.class)  // No need to register this provider if no special configuration is required.
        .register(JacksonFeature.class)
        .build();


Example 8.16. Creating JAX-RS application with Jackson JSON feature enabled.

// Create JAX-RS application.
final Application application = new ResourceConfig()
        .packages("org.glassfish.jersey.examples.jackson")
        .register(MyObjectMapperProvider.class)  // No need to register this provider if no special configuration is required.
        .register(JacksonFeature.class);


8.1.4.3. Examples

Jersey provides an JSON Jackson example on how to use Jackson to consume/produce JSON.

8.1.5. Jettison

JAXB approach for (de)serializing JSON in Jettison module provides, in addition to using pure JAXB, configuration options that could be set on an JettisonConfig instance. The instance could be then further used to create a JettisonJaxbContext, which serves as a main configuration point in this area. To pass your specializedJettisonJaxbContext to Jersey, you will finally need to implement a JAXBContext ContextResolver<T> (see below).

8.1.5.1. Dependency

To use Jettison as your JSON provider you need to add jersey-media-json-jettison module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jettison</artifactId>
    <version>2.0</version>
</dependency>

If you're not using Maven make sure to have all needed dependencies (see jersey-media-json-jettison) on the classpath.

8.1.5.2. JSON Notations

JettisonConfig allows you to use two JSON notations. Each of these notations serializes JSON in a different way. Following is a list of supported notations:

  • JETTISON_MAPPED (default notation)

  • BADGERFISH

You might want to use one of these notations, when working with more complex XML documents. Namely when you deal with multiple XML namespaces in your JAXB beans.

Individual notations and their further configuration options are described bellow. Rather then explaining rules for mapping XML constructs into JSON, the notations will be described using a simple example. Following are JAXB beans, which will be used.

Example 8.17. JAXB beans for JSON supported notations description, simple address bean

@XmlRootElement
public class Address {
    public String street;
    public String town;

    public Address(){}

    public Address(String street, String town) {
        this.street = street;
        this.town = town;
    }
}


Example 8.18. JAXB beans for JSON supported notations description, contact bean

@XmlRootElement
public class Contact {

    public int id;
    public String name;
    public List<Address> addresses;

    public Contact() {};

    public Contact(int id, String name, List<Address> addresses) {
        this.name = name;
        this.id = id;
        this.addresses =
            (addresses != null) ? new LinkedList<Address>(addresses) : null;
    }
}


Following text will be mainly working with a contact bean initialized with:

Example 8.19. JAXB beans for JSON supported notations description, initialization

Address[] addresses = {new Address("Long Street 1", "Short Village")};
Contact contact = new Contact(2, "Bob", Arrays.asList(addresses));


I.e. contact bean with id=2name="Bob" containing a single address (street="Long Street 1"town="Short Village").

All bellow described configuration options are documented also in api-docs at JettisonConfig.

8.1.5.2.1. Jettison mapped notation

If you need to deal with various XML namespaces, you will find Jettison mapped notation pretty useful. Lets define a particular namespace for id item:

...
@XmlElement(namespace="http://example.com")
public int id;
...

Then you simply configure a mapping from XML namespace into JSON prefix as follows:

Example 8.20.  XML namespace to JSON mapping configuration for Jettison based mapped notation

Map<String,String> ns2json = new HashMap<String, String>();
ns2json.put("http://example.com", "example");
context = new JettisonJaxbContext(
    JettisonConfig.mappedJettison().xml2JsonNs(ns2json).build(),
    types);


Resulting JSON will look like in the example bellow.

Example 8.21. JSON expression with XML namespaces mapped into JSON

{
   "contact":{
      "exampleid":2,
      "name":"Bob",
      "addresses":{
         "street":"Long Street 1",
         "town":"Short Village"
      }
   }
}


Please note, that id item became example.id based on the XML namespace mapping. If you have more XML namespaces in your XML, you will need to configure appropriate mapping for all of them.

8.1.5.2.2. Badgerfish notation

From JSON and JavaScript perspective, this notation is definitely the worst readable one. You will probably not want to use it, unless you need to make sure your JAXB beans could be flawlessly written and read back to and from JSON, without bothering with any formatting configuration, namespaces, etc.

JettisonConfig instance using badgerfish notation could be built with

JettisonConfig.badgerFish().build()

and the JSON output JSON will be as follows.

Example 8.22. JSON expression produced using badgerfish notation

{
   "contact":{
      "id":{
         "$":"2"
      },
      "name":{
         "$":"Bob"
      },
      "addresses":{
         "street":{
            "$":"Long Street 1"
         },
         "town":{
            "$":"Short Village"
         }
      }
   }
}


8.1.5.3. Configure and register

In order to use Jettison as your JSON (JAXB/POJO) provider you need to register JettisonFeature and a ContextResolver<T> for JAXBContext (if needed) in yourConfigurable (client/server).

Example 8.23. ContextResolver<ObjectMapper>

@Provider
public class JaxbContextResolver implements ContextResolver<JAXBContext> {

    private final JAXBContext context;
    private final Set<Class<?>> types;
    private final Class<?>[] cTypes = {Flights.class, FlightType.class, AircraftType.class};

    public JaxbContextResolver() throws Exception {
        this.types = new HashSet<Class<?>>(Arrays.asList(cTypes));
        this.context = new JettisonJaxbContext(JettisonConfig.DEFAULT, cTypes);
    }

    @Override
    public JAXBContext getContext(Class<?> objectType) {
        return (types.contains(objectType)) ? context : null;
    }
}


Example 8.24. Building client with Jettison JSON feature enabled.

final Client client = ClientBuilder.newBuilder()
        .register(JaxbContextResolver.class)  // No need to register this provider if no special configuration is required.
        .register(JettisonFeature.class)
        .build();


Example 8.25. Creating JAX-RS application with Jettison JSON feature enabled.

// Create JAX-RS application.
final Application application = new ResourceConfig()
        .packages("org.glassfish.jersey.examples.jettison")
        .register(JaxbContextResolver.class)  // No need to register this provider if no special configuration is required.
        .register(JettisonFeature.class);


8.1.5.4. Examples

Jersey provides an JSON Jettison example on how to use Jettison to consume/produce JSON.

8.1.6. @JSONP - JSON with Padding Support

Jersey provides out-of-the-box support for JSONP - JSON with padding. The following conditions has to be met to take advantage of this capability:

  • Resource method, which should return wrapped JSON, needs to be annotated with @JSONP annotation.

  • MessageBodyWriter<T> for application/json media type, which also accepts the return type of the resource method, needs to be registered (see JSON section of this chapter).

  • User's request has to contain Accept header with one of the JavaScript media types defined (see below).

Acceptable media types compatible with @JSONP are: application/javascriptapplication/x-javascriptapplication/ecmascript,text/javascripttext/x-javascripttext/ecmascripttext/jscript.

Example 8.26. Simplest case of using @JSONP

@GET
@JSONP
@Produces({"application/json", "application/javascript"})
public JaxbBean getSimpleJSONP() {
    return new JaxbBean("jsonp");
}


Assume that we have registered a JSON providers and that the JaxbBean looks like:

Example 8.27. JaxbBean for @JSONP example

@XmlRootElement
public class JaxbBean {

    private String value;

    public JaxbBean() {}

    public JaxbBean(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(final String value) {
        this.value = value;
    }
}


When you send a GET request with Accept header set to application/javascript you'll get a result entity that look like:

callback({
    "value" : "jsonp",
})

There are, of course, ways to configure wrapping method of the returned entity which defaults to callback as you can see in the previous example. @JSONP has two parameters that can be configured: callback and queryParamcallback stands for the name of the JavaScript callback function defined by the application. The second parameter, queryParam, defines the name of the query parameter holding the name of the callback function to be used (if present in the request). Value of queryParamdefaults to __callback so even if you do not set the name of the query parameter yourself, client can always affect the result name of the wrapping JavaScript callback method.

Note

queryParam value (if set) always takes precedence over callback value.

Lets modify our example a little bit:

Example 8.28. Example of @JSONP with configured parameters.

@GET
@Produces({"application/json", "application/javascript"})
@JSONP(callback = "eval", queryParam = "jsonpCallback")
public JaxbBean getSimpleJSONP() {
    return new JaxbBean("jsonp");
}


And make two requests:

curl -X GET http://localhost:8080/jsonp

will return

eval({
    "value" : "jsonp",
})

and the

curl -X GET http://localhost:8080/jsonp?jsonpCallback=alert

will return

alert({
    "value" : "jsonp",
})

Example.  You can take a look at a provided example available at JSON with Padding example.

8.2. XML

As you probably already know, Jersey uses MessageBodyWriter<T>s and MessageBodyReader<T>s to parse incoming requests and create outgoing responses. Every user can create its own representation but... this is not recommended way how to do things. XML is proven standard for interchanging information, especially in web services. Jerseys supports low level data types used for direct manipulation and JAXB XML entities.

8.2.1. Low level XML support

Jersey currently support several low level data types: StreamSourceSAXSourceDOMSource and Document. You can use these types as the return type or as a method (resource) parameter. Lets say we want to test this feature and we have helloworld example as a starting point. All we need to do is add methods (resources) which consumes and produces XML and types mentioned above will be used.

Example 8.29. Low level XML test - methods added to HelloWorldResource.java

@POST
@Path("StreamSource")
public StreamSource getStreamSource(StreamSource streamSource) {
    return streamSource;
}

@POST
@Path("SAXSource")
public SAXSource getSAXSource(SAXSource saxSource) {
    return saxSource;
}

@POST
@Path("DOMSource")
public DOMSource getDOMSource(DOMSource domSource) {
    return domSource;
}

@POST
@Path("Document")
public Document getDocument(Document document) {
    return document;
}

Both MessageBodyWriter<T> and MessageBodyReader<T> are used in this case, all we need is a POST request with some XML document as a request entity. To keep this as simple as possible only root element with no content will be sent: "<test />". You can create JAX-RS client to do that or use some other tool, for examplecurl:

curl -v http://localhost:8080/base/helloworld/StreamSource -d "<test/>"

You should get exactly the same XML from our service as is present in the request; in this case, XML headers are added to response but content stays. Feel free to iterate through all resources.

8.2.2. Getting started with JAXB

Good start for people which already have some experience with JAXB annotations is JAXB example. You can see various use-cases there. This text is mainly meant for those who don't have prior experience with JAXB. Don't expect that all possible annotations and their combinations will be covered in this chapter, JAXB (JSR 222 implementation) is pretty complex and comprehensive. But if you just want to know how you can interchange XML messages with your REST service, you are looking at the right chapter.

Lets start with simple example. Lets say we have class Planet and service which produces "Planets".

Example 8.30. Planet class

@XmlRootElement
public class Planet {
    public int id;
    public String name;
    public double radius;
}

Example 8.31. Resource class

@Path("planet")
public class Resource {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Planet getPlanet() {
        final Planet planet = new Planet();

        planet.id = 1;
        planet.name = "Earth";
        planet.radius = 1.0;

        return planet;
    }
}

You can see there is some extra annotation declared on Planet class, particularly @XmlRootElement. This is an JAXB annotation which maps java classes to XML elements. We don't need to specify anything else, because Planet is very simple class and all fields are public. In this case, XML element name will be derived from the class name or you can set the name property: @XmlRootElement(name="yourName").

Our resource class will respond to GET /planet with

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
    <id>1</id>
    <name>Earth</name>
    <radius>1.0</radius>
</planet>

which might be exactly what we want... or not. Or we might not really care, because we can use JAX-RS client for making requests to this resource and this is easy as:

                    Planet planet = webTarget.path("planet").request(MediaType.APPLICATION_XML_TYPE).get(Planet.class);
                

There is pre-created WebTarget object which points to our applications context root and we simply add path (in our case its planet), accept header (not mandatory, but service could provide different content based on this header; for example text/html can be served for web browsers) and at the end we specify that we are expectingPlanet class via GET request.

There may be need for not just producing XML, we might want to consume it as well.

Example 8.32. Method for consuming Planet

@POST
@Consumes(MediaType.APPLICATION_XML)
public void setPlanet(Planet planet) {
    System.out.println("setPlanet " + planet);
}


After valid request is made, service will print out string representation of Planet, which can look like Planet{id=2, name='Mars', radius=1.51}. With JAX-RS client you can do:

                    webTarget.path("planet").post(planet);
                

If there is a need for some other (non default) XML representation, other JAXB annotations would need to be used. This process is usually simplified by generating java source from XML Schema which is done by xjc which is XML to java compiler and it is part of JAXB.

8.2.3. POJOs

Sometimes you can't / don't want to add JAXB annotations to source code and you still want to have resources consuming and producing XML representation of your classes. In this case, JAXBElement class should help you. Let's redo planet resource but this time we won't have an @XmlRootElement annotation on Planet class.

Example 8.33. Resource class - JAXBElement

@Path("planet")
public class Resource {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public JAXBElement<Planet> getPlanet() {
        Planet planet = new Planet();

        planet.id = 1;
        planet.name = "Earth";
        planet.radius = 1.0;

        return new JAXBElement<Planet>(new QName("planet"), Planet.class, planet);
    }

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public void setPlanet(JAXBElement<Planet> planet) {
        System.out.println("setPlanet " + planet.getValue());
    }
}

As you can see, everything is little more complicated with JAXBElement. This is because now you need to explicitly set element name for Planet class XML representation. Client side is even more complicated than server side because you can't do JAXBElement<Planet> so JAX-RS client API provides way how to workaround it by declaring subclass of GenericType<T>.

Example 8.34. Client side - JAXBElement

// GET
GenericType<JAXBElement<Planet>> planetType = new GenericType<JAXBElement<Planet>>() {};

Planet planet = (Planet) webTarget.path("planet").request(MediaType.APPLICATION_XML_TYPE).get(planetType).getValue();
System.out.println("### " + planet);

// POST
planet = new Planet();

// ...

webTarget.path("planet").post(new JAXBElement<Planet>(new QName("planet"), Planet.class, planet));

8.2.4. Using custom JAXBContext

In some scenarios you can take advantage of using custom JAXBContext. Creating JAXBContext is an expensive operation and if you already have one created, same instance can be used by Jersey. Other possible use-case for this is when you need to set some specific things to JAXBContext, for example to set a different class loader.

Example 8.35. PlanetJAXBContextProvider

@Provider
public class PlanetJAXBContextProvider implements ContextResolver<JAXBContext> {
    private JAXBContext context = null;

    public JAXBContext getContext(Class<?> type) {
        if (type != Planet.class) {
            return null; // we don't support nothing else than Planet
        }

        if (context == null) {
            try {
                context = JAXBContext.newInstance(Planet.class);
            } catch (JAXBException e) {
                // log warning/error; null will be returned which indicates that this
                // provider won't/can't be used.
            }
        }

        return context;
    }
}

Sample above shows simple JAXBContext creation, all you need to do is put this @Provider annotated class somewhere where Jersey can find it. Users sometimes have problems with using provider classes on client side, so just to reminder - you have to declare them in the client config (client does not do anything like package scanning done by server).

Example 8.36. Using Provider with JAX-RS client

ClientConfig config = new ClientConfig();
config.register(PlanetJAXBContextProvider.class);

Client client = ClientBuilder.newClient(config);
                

8.2.5. MOXy

If you want to use MOXy as your JAXB implementation instead of JAXB RI you have two options. You can either use the standard JAXB mechanisms to define theJAXBContextFactory from which a JAXBContext instance would be obtained (for more on this topic, read JavaDoc on JAXBContext) or you can add jersey-media-moxy module to your project and register/configure MoxyXmlFeature class/instance in the Configurable.

Example 8.37. Add jersey-media-moxy dependency.

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.0</version>
</dependency>

Example 8.38. Register the MoxyXmlFeature class.

final ResourceConfig config = new ResourceConfig()
    .packages("org.glassfish.jersey.examples.xmlmoxy")
    .register(MoxyXmlFeature.class);

Example 8.39. Configure and register an MoxyXmlFeature instance.

// Configure Properties.
final Map<String, Object> properties = new HashMap<String, Object>();
// ...

// Obtain a ClassLoader you want to use.
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

final ResourceConfig config = new ResourceConfig()
    .packages("org.glassfish.jersey.examples.xmlmoxy")
    .register(new MoxyXmlFeature(
        properties,
        classLoader,
        true, // Flag to determine whether eclipselink-oxm.xml file should be used for lookup.
        CustomClassA.class, CustomClassB.class  // Classes to be bound.
    ));

8.3. Multipart

8.3.1. Overview

The classes in this module provide an integration of multipart/* request and response bodies in a JAX-RS runtime environment. The set of registered providers is leveraged, in that the content type for a body part of such a message reuses the same MessageBodyReader<T>/MessageBodyWriter<T> implementations as would be used for that content type as a standalone entity.

The following list of general MIME MultiPart features is currently supported:

  • The MIME-Version: 1.0 HTTP header is included on generated responses. It is accepted, but not required, on processed requests.

  • MessageBodyReader<T> implementation for consuming MIME MultiPart entities.

  • MessageBodyWriter<T> implementation for producing MIME MultiPart entities. The appropriate @Provider is used to serialize each body part, based on its media type.

  • Optional creation of an appropriate boundary parameter on a generated Content-Type header, if not already present.

For more information refer to Multi Part.

8.3.1.1. Dependency

To use multipart features you need to add jersey-media-multipart module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>2.0</version>
</dependency>

If you're not using Maven make sure to have all needed dependencies (see jersey-media-multipart) on the class-path.

8.3.1.2. Registration

Before you can use capabilities of the jersey-media-multipart module in your client/server code, you need to register MultiPartFeature.

Example 8.40. Building client with MultiPart feature enabled.

final Client client = ClientBuilder.newBuilder()
    .register(MultiPartFeature.class)
    .build();


Example 8.41. Creating JAX-RS application with MultiPart feature enabled.

// Create JAX-RS application.
final Application application = new ResourceConfig()
    .packages("org.glassfish.jersey.examples.multipart")
    .register(MultiPartFeature.class)


8.3.1.3. Examples

Jersey provides an multipart-webapp example on how to use multipart features.

8.3.2. Client

MultiPart class (or it's subclasses) can be used as an entry point to using jersey-media-multipart module on the client side. This class represents a MIME multipart message and is able to hold an arbitrary number of BodyParts. Default media type is multipart/mixed for MultiPart entity and text/plain for BodyPart.

Example 8.42. MultiPart entity

final MultiPart multiPartEntity = new MultiPart()
        .bodyPart(new BodyPart().entity("hello"))
        .bodyPart(new BodyPart(new JaxbBean("xml"), MediaType.APPLICATION_XML_TYPE))
        .bodyPart(new BodyPart(new JaxbBean("json"), MediaType.APPLICATION_JSON_TYPE));

final WebTarget target = // Create WebTarget.
final Response response = target
        .request()
        .post(Entity.entity(multiPartEntity, multiPartEntity.getMediaType()));


If you send a multiPartEntity to the server the entity with Content-Type header in HTTP message would look like (don't forget to register a JSON provider):

Example 8.43. MultiPart entity in HTTP message.

Content-Type: multipart/mixed; boundary=Boundary_1_829077776_1369128119878

--Boundary_1_829077776_1369128119878
Content-Type: text/plain

hello
--Boundary_1_829077776_1369128119878
Content-Type: application/xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><jaxbBean><value>xml</value></jaxbBean>
--Boundary_1_829077776_1369128119878
Content-Type: application/json

{"value":"json"}
--Boundary_1_829077776_1369128119878--


When working with forms (e.g. media type multipart/form-data) and various fields in them, there is a more convenient class to be used - FormDataMultiPart. It automatically sets the media type for the FormDataMultiPart entity to multipart/form-data and Content-Disposition header to FormDataBodyPart body parts.

Example 8.44. FormDataMultiPart entity

final FormDataMultiPart multipart = new FormDataMultiPart()
    .field("hello", "hello")
    .field("xml", new JaxbBean("xml"))
    .field("json", new JaxbBean("json"), MediaType.APPLICATION_JSON_TYPE);

final WebTarget target = // Create WebTarget.
final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType()));


To illustrate the difference when using FormDataMultiPart instead of FormDataBodyPart you can take a look at the FormDataMultiPart entity from HTML message:

Example 8.45. FormDataMultiPart entity in HTTP message.

Content-Type: multipart/form-data; boundary=Boundary_1_511262261_1369143433608

--Boundary_1_511262261_1369143433608
Content-Type: text/plain
Content-Disposition: form-data; name="hello"

hello
--Boundary_1_511262261_1369143433608
Content-Type: application/xml
Content-Disposition: form-data; name="xml"

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><jaxbBean><value>xml</value></jaxbBean>
--Boundary_1_511262261_1369143433608
Content-Type: application/json
Content-Disposition: form-data; name="json"

{"value":"json"}
--Boundary_1_511262261_1369143433608--


A common use-case for many users is sending files from client to server. For this purpose you can use classes fromorg.glassfish.jersey.jersey.media.multipart package, such as FileDataBodyPart or StreamDataBodyPart.

Example 8.46. Multipart - sending files.

// MediaType of the body part will be derived from the file.
final FileDataBodyPart filePart = new FileDataBodyPart("my_pom", new File("pom.xml"));

final FormDataMultiPart multipart = new FormDataMultiPart()
    .field("foo", "bar")
    .bodyPart(filePart);

final WebTarget target = // Create WebTarget.
final Response response = target.request()
    .post(Entity.entity(multipart, multipart.getMediaType()));


8.3.3. Server

Returning a multipart response from server to client is not much different from the parts described in the client section above. To obtain a multipart entity, sent by a client, in the application you can use two approaches:

  • Injecting the whole MultiPart entity.

  • Injecting particular parts of a form-data multipart request via @FormDataParam annotation.

8.3.3.1. Injecting and returning the MultiPart entity

Working with MultiPart types is no different from injecting/returning other entity types. Jersey provides MessageBodyReader<T> for reading the request entity and injecting this entity into a method parameter of a resource method and MessageBodyWriter<T> for writing output entities. You can expect that either MultiPart orFormDataMultiPart (multipart/form-data media type) object to be injected into a resource method.

Example 8.47. Resource method using MultiPart as input parameter / return value.

@POST
@Produces("multipart/mixed")
public MultiPart post(final FormDataMultiPart multiPart) {
    return multiPart;
}

8.3.3.2. Injecting with @FormDataParam

If you just need to bin the named body part(s) of a multipart/form-data request entity body to a resource method parameter you can use @FormDataParamannotation.

This annotation in conjunction with the media type multipart/form-data should be used for submitting and consuming forms that contain files, non-ASCII data, and binary data.

The type of the annotated parameter can be one of the following (for more detailed description see javadoc to @FormDataParam):

  • FormDataBodyPart - The value of the parameter will be the first named body part or null if such a named body part is not present.

  • List or Collection of FormDataBodyPart. The value of the parameter will one or more named body parts with the same name or null if such a named body part is not present.

  • FormDataContentDisposition - The value of the parameter will be the content disposition of the first named body part part or null if such a named body part is not present.

  • List or Collection of FormDataContentDisposition. The value of the parameter will one or more content dispositions of the named body parts with the same name or null if such a named body part is not present.

  • A type for which a message body reader is available given the media type of the first named body part. The value of the parameter will be the result of reading using the message body reader given the type T, the media type of the named part, and the bytes of the named body part as input.

    If there is no named part present and there is a default value present as declared by @DefaultValue then the media type will be set to text/plain. The value of the parameter will be the result of reading using the message body reader given the type T, the media type text/plain, and the UTF-8 encoded bytes of the default value as input.

    If there is no message body reader available and the type T conforms to a type specified by @FormParam then processing is performed as specified by@FormParam, where the values of the form parameter are String instances produced by reading the bytes of the named body parts utilizing a message body reader for the String type and the media type text/plain.

    If there is no named part present then processing is performed as specified by @FormParam.

Example 8.48. Use of @FormDataParam annotation

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA_TYPE)
public String postForm(
    @DefaultValue("true") @FormDataParam("enabled") boolean enabled,
    @FormDataParam("data") FileData bean,
    @FormDataParam("file") InputStream file,
    @FormDataParam("file") FormDataContentDisposition fileDisposition) {

    // ...
}

In the example above the server consumes a multipart/form-data request entity body that contains one optional named body part enabled and two required named body parts data and file.

The optional part enabled is processed as a boolean value, if the part is absent then the value will be true.

The part data is processed as a JAXB bean and contains some meta-data about the following part.

The part file is a file that is uploaded, this is processed as an InputStream. Additional information about the file from the Content-Disposition header can be accessed by the parameter fileDisposition.

Tip

@FormDataParam annotation can be also used on fields.

Chapter 9. Filters and Interceptors

9.1. Introduction

This chapter describes filters, interceptors and their configuration. Filters and interceptors can be used on both sides, on the client and the server side. Filters can modify inbound and outbound requests and responses including modification of headers, entity and other request/response parameters. Interceptors are used primarily for modification of entity input and output streams. You can use interceptors for example to zip and unzip output and input entity streams.

9.2. Filters

Filters can be used when you want to modify any request or response parameters like headers. For example you would like to add a response header "X-Powered-By" to each generated response. Instead of adding this header in each resource method you would use a response filter to add this header.

There are filters on the server side and the client side.

Server filters:

ContainerRequestFilter
ContainerResponseFilter

Client filters:

ClientResponseFilter
ClientResponseFilter

9.2.1. Server filters

The following example shows a simple container response filter adding a header to each response.

Example 9.1. Container response filter

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;

public class PoweredByResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

            responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
    }
}


In the example above the PoweredByResponseFilter always adds a header "X-Powered-By" to the response. The filter must inherit from the ContainerResponseFilterand must be registered as a provider. The filter will be executed for every response which is in most cases after the resource method is executed. Response filters are executed even if the resource method is not run, for example when the resource method is not found and 404 "Not found" response code is returned by the Jersey runtime. In this case the filter will be executed and will process the 404 response.

The filter() method has two arguments, the container request and container response. The ContainerRequestContext is accessible only for read only purposes as the filter is executed already in response phase. The modifications can be done in the ContainerResponseContext.

The following example shows the usage of a request filter.

Example 9.2. Container request filter

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

public class AuthorizationRequestFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext)
                    throws IOException {

        final SecurityContext securityContext =
                    requestContext.getSecurityContext();
        if (securityContext == null ||
                    !securityContext.isUserInRole("privileged")) {

                requestContext.abortWith(Response
                    .status(Response.Status.UNAUTHORIZED)
                    .entity("User cannot access the resource.")
                    .build());
        }
    }
}

The request filter is similar to the response filter but does not have access to the ContainerResponseContext as no response is accessible yet. Response filter inherits fromClientResponseFilter. Request filter is executed before the resource method is run and before the response is created. The filter has possibility to manipulate the request parameters including request headers or entity.

The AuthorizationRequestFilter in the example checks whether the authenticated user is in the privileged role. If it is not then the request is aborted by callingContainerRequestContext.abortWith(Response response) method. The method is intended to be called from the request filter in situation when the request should not be processed further in the standard processing chain. When the filter method is finished the response passed as a parameter to the abortWith method is used to respond to the request. Response filters, if any are registered, will be executed and will have possibility to process the aborted response.

9.2.1.1. Pre-matching and post-matching filters

All the request filters shown above was implemented as post-matching filters. It means that the filters would be applied only after a suitable resource method has been selected to process the actual request i.e. after request matching happens. Request matching is the process of finding a resource method that should be executed based on the request path and other request parameters. Since post-matching request filters are invoked when a particular resource method has already been selected, such filters can not influence the resoure method matching process.

To overcome the above described limitation, there is a possibility to mark a server request filter as a pre-matching filter, i.e. to annotate the filter class with the @PreMatchingannotation. Pre-matching filters are request filters that are executed before the request matching is started. Thanks to this, pre-matching request filters have the possibility to influence which method will be matched. Such a pre-matching request filter example is shown here:

Example 9.3. Pre-matching request filter

...
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
...

@PreMatching
public class PreMatchingFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext)
                        throws IOException {
        // change all PUT methods to POST
        if (requestContext.getMethod().equals("PUT")) {
            requestContext.setMethod("POST");
        }
    }
}


The PreMatchingFilter is a simple pre-matching filter which changes all PUT HTTP methods to POST. This might be useful when you want to always handle these PUT and POST HTTP methods with the same Java code. After the PreMatchingFilter has been invoked, the rest of the request processing will behave as if the POST HTTP method was originally used. You cannot do this in post-matching filters (standard filters without @PreMatching annotation) as the resource method is already matched (selected). An attempt to tweak the original HTTP method in a post-matching filter would cause an IllegalArgumentException.

As written above, pre-matching filters can fully influence the request matching process, which means you can even modify request URI in a pre-matching filter by invoking thesetRequestUri(URI) method of ContainerRequestFilter so that a different resource would be matched.

Like in post-matching filters you can abort a response in pre-matching filters too.

9.2.2. Client fillers

Client filters are similar to container filters. The response can also be aborted in the ClientRequestFilter which would cause that no request will actually be sent to the server at all. A new response is passed to the abort method. This response will be used and delivered as a result of the request invocation. Such a response goes through the client response filters. This is similar to what happens on the server side. The process is shown in the following example:

Example 9.4. Client request filter

public class CheckRequestFilter implements ClientRequestFilter {

    @Override
    public void filter(ClientRequestContext requestContext)
                        throws IOException {
        if (requestContext.getHeaders(
                        ).get("Client-Name") == null) {
            requestContext.abortWith(
                        Response.status(Response.Status.BAD_REQUEST)
                .entity("Client-Name header must be defined.")
                        .build());
         }
    }
}


The CheckRequestFilter validates the outgoing request. It is checked for presence of a Client-Name header. If the header is not present the request will be aborted with a made up response with an appropriate code and message in the entity body. This will cause that the original request will not be effectivelly sent to the server but the actual invocation will still end up with a response as if it would be generated by the server side. If there would be any client response filter it would be executed on this response.

To summarize the workflow, for any client request invoked from the client API the client request filters (ClientRequestFilter) are executed that could manipulate the request. If not aborted, the outcoming request is then physically sent over to the server side and once a response is received back from the server the client response filters (ClientResponseFilter) are executed that might again manipulate the returned response. Finally the response is passed back to the code that invoked the request. If the request was aborted in any client request filter then the client/server communication is skipped and the aborted response is used in the response filters.

9.3. Interceptors

Interceptors share a common API for the server and the client side. Whereas filters are primarily intended to manipulate request and response parameters like HTTP headers, URIs and/or HTTP methods, interceptors are intended to manipulate entities, via manipulating entity input/output streams. If you for example need to encode entity body of a client request then you could implement an interceptor to do the work for you.

There are two kinds of interceptors, ReaderInterceptor and WriterInterceptor. Reader interceptors are used to manipulate inbound entity streams. These are the streams coming from the "wire". So, using a reader interceptor you can manipulate request entity stream on the server side (where an entity is read from the client request) and response entity stream on the client side (where an entity is read from the server response). Writer interceptors are used for cases where entity is written to the "wire" which on the server means when writing out a response entity and on the client side when writing request entity for a request to be sent out to the server. Writer and reader interceptors are executed before message body readers or writers are executed and their primary intention is to wrap the entity streams that will be used in message body reader and writers.

The following example shows a writer interceptor that enables GZIP compression of the whole entity body.

Example 9.5. GZIP writer interceptor

public class GZIPWriterInterceptor implements WriterInterceptor {

    @Override
    public void aroundWriteTo(WriterInterceptorContext context)
                    throws IOException, WebApplicationException {
        final OutputStream outputStream = context.getOutputStream();
        context.setOutputStream(new GZIPOutputStream(outputStream));
        context.proceed();
    }
}


The interceptor gets a output stream from the WriterInterceptorContext and sets a new one which is a GZIP wrapper of the original output stream. After all interceptors are executed the output stream lastly set to the WriterInterceptorContext will be used for serialization of the entity. In the example above the entity bytes will be written to the GZIPOutputStream which will compress the stream data and write them to the original output stream. The original stream is always the stream which writes the data to the "wire". When the interceptor is used on the server, the original output stream is the stream into which writes data to the underlying server container stream that sends the response to the client.

The interceptors wrap the streams and they itself work as wrappers. This means that each interceptor is a wrapper of another interceptor and it is responsibility of each interceptor implementation to call the wrapped interceptor. This is achieved by calling the proceed() method on the WriterInterceptorContext. This method will call the next registered interceptor in the chain, so effectivelly this will call all remaining registered interceptors. Calling proceed() from the last interceptor in the chain will call the appropriate message body reader. Therefore every interceptor must call the proceed() method otherwise the entity would not be written. The wrapping principle is reflected also in the method name, aroundWriteTo, which says that the method is wrapping the writing of the entity.

The method aroundWriteTo() gets WriterInterceptorContext as a parameter. This context contains getters and setters for header parameters, request properties, entity, entity stream and other properties. These are the properties which will be passed to the final MessageBodyWriter<T>. Interceptors are allowed to modify all these properties. This could influence writing of an entity by MessageBodyWriter<T> and even selection of such a writer. By changing media type (WriterInterceptorContext.setMediaType()) the interceptor can cause that different message body writer will be chosen. The interceptor can also completely replace the entity if it is needed. However, for modification of headers, request properties and such, the filters are usually more preferable choice. Interceptors are executed only when there is any entity and when the entity is to be written. So, when you always want to add a new header to a response no matter what, use filters as interceptors might not be executed when no entity is present. Interceptors should modify properties only for entity serialization and deserialization purposes.

Let's now look at an example of a WriterInterceptor

Example 9.6. GZIP reader interceptor

public class GZIPReaderInterceptor implements ReaderInterceptor {

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context)
                    throws IOException, WebApplicationException {
        final InputStream originalInputStream = context.getInputStream();
        context.setInputStream(new GZIPInputStream(originalInputStream));
        return context.proceed();
    }
}


The GZIPReaderInterceptor wraps the original input stream with the GZIPInputStream. All further reads from the entity stream will cause that data will be decompressed by this stream. The interceptor method aroundReadFrom() must return an entity. The entity is returned from the proceed method of theReaderInterceptorContext. The proceed method internally calls the wrapped interceptor which must also return an entity. The proceed method invoked from the last interceptor in the chain calls message body reader which deserializes the entity end returns it. Every interceptor can change this entity if there is a need but in the most cases interceptors will just return the entity as returned from the proceed method.

As already mentioned above, interceptors should be primarily used to manipulate entity body. Similar to methods exposed by WriterInterceptorContext theReaderInterceptorContext introduces a set of methods for modification of request/response properties like HTTP headers, URIs and/or HTTP methods (excluding getters and setters for entity as entity has not been read yet). Again the same rules as for WriterInterceptor applies for changing these properties (change only properties in order to influence reading of an entity).

9.4. Filter and interceptor execution order

Let's look closer at the context of execution of filters and interceptors. The following steps describes scenario where a JAX-RS client makes a POST request to the server. The server receives an entity and sends a response back with the same entity. GZIP reader and writer interceptors are registered on the client and the server. Also filters are registered on client and server which change the headers of request and response.

  1. Client request invoked: The POST request with attached entity is built on the client and invoked.
  2. ClientRequestFilters: The ClientResponseFilters are executed on the client and they manipulate the request headers.
  3. Client WriterInterceptor: As the request contains an entity, writer interceptor registered on the client is executed before a MessageBodyWriter is executed. It wraps the entity output stream with the GZipOutputStream.
  4. Client MessageBodyWriter: message body writer is executed on the client which serializes the entity into the new GZipOutput stream. This stream zips the data and sends it to the "wire".
  5. Server: server receives a request. Data of entity is compressed which means that pure read from the entity input stream would return compressed data.
  6. Server pre-matching ContainerRequestFilters: ContainerRequestFilters are executed that can manipulate resource method matching process.
  7. Server: matching: resource method matching is done.
  8. Server: post-matching ContainerRequestFilters: ContainerRequestFilters post matching filters are executed. This include execution of all global filters (without name binding) and filters name-bound to the matched method.
  9. Server ReaderInterceptor: reader interceptors are executed on the server. The GZIPReaderInterceptor wraps the input stream (the stream from the "wire") into the GZipInputStream and set it to context.
  10. Server MessageBodyReader: server message body reader is executed and it deserializes the entity from new GZipInputStream (get from the context). This means the reader will read unzipped data and not the compressed data from the "wire".
  11. Server resource method is executed: the deserialized entity object is passed to the matched resource method as a parameter. The method returns this entity as a response entity.
  12. Server ContainerResponseFilters are executed: response filters are executed on the server and they manipulate the response headers. This include all global bound filters (without name binding) and all filters name-bound to the resource method.
  13. Server WriterInterceptor: is executed on the server. It wraps the original output stream with a new GZIPOuptutStream. The original stream is the stream that "goes to the wire" (output stream for response from the underlying server container).
  14. Server MessageBodyWriter: message body writer is executed on the server which serializes the entity into the GZIPOutputStream. This stream compresses the data and writes it to the original stream which sends this compressed data back to the client.
  15. Client receives the response: the response contains compressed entity data.
  16. Client ClientResponseFilters: client response filters are executed and they manipulate the response headers.
  17. Client response is returned: the javax.ws.rs.core.Response is returned from the request invocation.
  18. Client code calls response.readEntity(): read entity is executed on the client to extract the entity from the response.
  19. Client ReaderInterceptor: the client reader interceptor is executed when readEntity(Class) is called. The interceptor wraps the entity input stream with GZIPInputStream. This will decompress the data from the original input stream.
  20. Client MessageBodyReaders: client message body reader is invoked which reads decompressed data from GZIPInputStream and deserializes the entity.
  21. Client: The entity is returned from the readEntity().

It is worth to mention that in the scenario above the reader and writer interceptors are invoked only if the entity is present (it does not make sense to wrap entity stream when no entity will be written). The same behaviour is there for message body readers and writers. As mentioned above, interceptors are executed before the message body reader/writer as a part of their execution and they can wrap the input/output stream before the entity is read/written. There are exceptions when interceptors are not run before message body reader/writers but this is not the case of simple scenario above. This happens for example when the entity is read many times from client response using internal buffering. Then the data are intercepted only once and kept 'decoded' in the buffer.

9.5. Name binding

Filters and interceptors can be name-bound. Name binding is a concept that allows to say to a JAX-RS runtime that a specific filter or interceptor will be executed only for a specific resource method. When a filter or an interceptor is limited only to a specific resource method we say that it is name-bound. Filters and interceptors that do not have such a limitation are called global.

Filter or interceptor can be assigned to a resource method using the @NameBinding annotation. The annotation is used as meta annotation for other user implemented annotations that are applied to a providers and resource methods. See the following example:

Example 9.7. @NameBinding example

...
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.zip.GZIPInputStream;

import javax.ws.rs.GET;
import javax.ws.rs.NameBinding;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
...


// @Compress annotation is the name binding annotation
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Compress {}


@Path("helloworld")
public class HelloWorldResource {

    @GET
    @Produces("text/plain")
    public String getHello() {
        return "Hello World!";
    }

    @GET
    @Path("too-much-data")
    @Compress
    public String getVeryLongString() {
        String str = ... // very long string
        return str;
    }
}

// interceptor will be executed only when resource methods
// annotated with @Compress annotation will be executed
@Compress
public class GZIPWriterInterceptor implements WriterInterceptor {
    @Override
    public void aroundWriteTo(WriterInterceptorContext context)
                    throws IOException, WebApplicationException {
        final OutputStream outputStream = context.getOutputStream();
        context.setOutputStream(new GZIPOutputStream(outputStream));
        context.proceed();
    }
}


The example above defines a new @Compress annotation which is a name binding annotation as it is annotated with @NameBinding. The @Compress is applied on the resource method getVeryLongString() and on the interceptor GZIPWriterInterceptor. The interceptor will be executed only if any resource method with such a annotation will be executed. In our example case the interceptor will be executed only for the getVeryLongString() method. The interceptor will not be executed for method getHello(). In this example the reason is probably clear. We would like to compress only long data and we do not need to compress the short response of "Hello World!".

Name binding can be applied on a resource class. In the example HelloWorldResource would be annotated with @Compress. This would mean that all resource methods will use compression in this case.

There might be many name binding annotations defined in an application. When any provider (filter or interceptor) is annotated with more than one name binding annotation, then it will be executed for resource methods which contain ALL these annotations. So, for example if our interceptor would be annotated with another name binding annotation @GZIP then the resource method would need to have both annotations attached, @Compress and @GZIP, otherwise the interceptor would not be executed. Based on the previous paragraph we can even use the combination when the resource method getVeryLongString() would be annotated with @Compress and resource class HelloWorldResource would be annotated from with @GZIP. This would also trigger the interceptor as annotations of resource methods are aggregated from resource method and from resource class. But this is probably just an edge case which will not be used so often.

Note that global filters are executed always, so even for resource methods which have any name binding annotations.

9.6. Dynamic binding

Dynamic binding is a way how to assign filters and interceptors to the resource methods in a dynamic manner. Name binding from the previous chapter uses a static approach and changes to binding require source code change and recompilation. With dynamic binding you can implement code which defines bindings during the application initialization time. The following example shows how to implement dynamic binding.

Example 9.8. Dynamic binding example

...
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.container.DynamicFeature;
...

@Path("helloworld")
public class HelloWorldResource {

    @GET
    @Produces("text/plain")
    public String getHello() {
        return "Hello World!";
    }

    @GET
    @Path("too-much-data")
    public String getVeryLongString() {
        String str = ... // very long string
        return str;
    }
}

// This dynamic binding provider registers GZIPWriterInterceptor
// only for HelloWorldResource and methods that contain
// "VeryLongString" in their name. It will be executed during
// application initialization phase.
public class CompressionDynamicBinding implements DynamicFeature {

    @Override
    public void configure(ResourceInfo resourceInfo, FeatureContext context) {
        if (HelloWorldResource.class.equals(resourceInfo.getResourceClass())
                && resourceInfo.getResourceMethod()
                    .getName().contains("VeryLongString")) {
            context.register(GZIPWriterInterceptor.class);
        }
    }
}


The example contains one HelloWorldResource which is known from the previous name binding example. The difference is in the getVeryLongString method, which now does not define the @Compress name binding annotations. The binding is done using the provider which implements DynamicFeature interface. The interface defines one configure method with two arguments, ResourceInfo and FeatureContextResourceInfo contains information about the resource and method to which the binding can be done. The configure method will be executed once for each resource method that is defined in the application. In the example above the provider will be executed twice, once for the getHello() method and once for getVeryLongString() ( once the resourceInfo will contain information about getHello() method and once it will point to getVeryLongString()). If a dynamic binding provider wants to register any provider for the actual resource method it will do that using providedFeatureContext which extends JAX-RS Configurable API. All methods for registration of filter or interceptor classes or instances can be used. Such dynamically registered filters or interceptors will be bound only to the actual resource method. In the example above the GZIPWriterInterceptor will be bound only to the methodgetVeryLongString() which will cause that data will be compressed only for this method and not for the method getHello(). The code ofGZIPWriterInterceptor is in the examples above.

Note that filters and interceptors registered using dynamic binding are only additional filters run for the resource method. If there are any name bound providers or global providers they will still be executed.

9.7. Priorities

In case you register more filters and interceptors you might want to define an exact order in which they should be invoked. The order can be controlled by the @Priorityannotation defined by the javax.annotation.Priority class. The annotation accepts an integer parameter of priority. Providers used in request processing (ContainerRequestFilter, ClientRequestFilter, ReaderInterceptors) are sorted based on the priority in an ascending manner. So, a request filter with priority defined with@Priority(1000) will be executed before another request filter with priority defined as @Priority(2000). Providers used during response processing (ContainerResponseFilter, ClientResponseFilter, WriterIntercepors) are executed in the reverse order (using descending manner), so a provider with the priority defined with@Priority(2000) will be executed before another provider with priority defined with @Priority(1000).

It's a good practice to assign a priority to filters and interceptors. Use Priorities class which defines standardized priorities in JAX-RS for different usages, rather than inventing your own priorities. So, when you for example write an authentication filter you would assign a priority 1000 which is the value of Priorities.AUTHENTICATION. The following example shows the filter from the beginning of this chapter with a priority assigned.

Example 9.9. Priorities example

...
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
...

@Priority(Priorities.HEADER_DECORATOR)
public class ResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext,
                    ContainerResponseContext responseContext)
                    throws IOException {

        responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
    }
}


As this is a response filter and response filters are executed in the reverse order, any other filter with priority lower than 3000 (Priorities.HEADER_DECORATOR is 3000) will be executed after this filter. So, for example AUTHENTICATION filter (priority 1000) would be run after this filter.

Chapter 10. Asynchronous Services and Clients

This chapter describes the usage of asynchronous API on the client and server side. The term async will be sometimes used interchangeably with the term asynchronous in this chapter.

10.1. Asynchronous Server API

Request processing on the server works by default in a synchronous processing mode, which means that a client connection of a request is processed in a single I/O container thread. Once the thread processing the request returns to the I/O container, the container can safely assume that the request processing is finished and that the client connection can be safely released including all the resources associated with the connection. This model is typically sufficient for processing of requests for which the processing resource method execution takes a relatively short time. However, in cases where a resource method execution is known to take a long time to compute the result, server-side asynchronous processing model should be used. In this model, the association between a request processing thread and client connection is broken. I/O container that handles incoming request may no longer assume that a client connection can be safely closed when a request processing thread returns. Instead a facility for explicitly suspending, resuming and closing client connections needs to be exposed. Note that the use of server-side asynchronous processing model will not improve the request processing time perceived by the client. It will however increase the throughput of the server, by releasing the initial request processing thread back to the I/O container while the request may still be waiting in a queue for processing or the processing may still be running on another dedicated thread. The released I/O container thread can be used to accept and process new incoming request connections.

The following example shows a simple asynchronous resource method defined using the new JAX-RS async API:

Example 10.1. Simple async resource

@Path("/resource")
public class AsyncResource {
    @GET
    public void asyncGet(@Suspended final AsyncResponse asyncResponse) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                // ... very expensive operation
            }
        }).start();
    }
}


In the example above, a resource AsyncResource with one GET method asyncGet is defined. The asyncGet method injects a JAX-RS AsyncResponse instance using a JAX-RS @Suspended annotation. Please note that AsyncResponse must be injected by the @Suspended annotation and not by @Context as @Suspended does not only inject response but also says that the method is executed in the asynchronous mode. By the AsyncResponse parameter into a resource method we tell the Jersey runtime that the method is supposed to be invoked using the asynchronous processing mode, that is the client connection should not be automatically closed by the underlying I/O container when the method returns. Instead, the injected AsyncResponse instance (that represents the suspended client request connection) will be used to explicitly send the response back to the client using some other thread. In other words, Jersey runtime knows that when the asyncGet method completes, the response to the client may not be ready yet and the processing must be suspended and wait to be explictly resumed with a response once it becomes available. Note that the method asyncGetreturns void in our example. This is perfectly valid in case of an asynchronous JAX-RS resource method, even for a @GET method, as the response is never returned directly from the resource method as its return value. Instead, the response is later returned using AsyncResponse instance as it is demonstrated in the example. TheasyncGet resource method starts a new thread and exits from the method. In that state the request processing is suspended and the container thread (the one which entered the resource method) is returned back to the container's thread pool and it can process other requests. New thread started in the resource method may execute an expensive operation which might take a long time to finish. Once a result is ready it is resumed using the resume() method on the AsyncResponse instance. The resumed response is then processed in the new thread by Jersey in a same way as any other synchronous response, including execution of filters and interceptors, use of exception mappers as necessary and sending the response back to the client.

It is important to note that the asynchronous response (asyncResponse in the example) does not need to be resumed from the thread started from the resource method. The asynchronous response can be resumed even from different request processing thread as it is shown in the the example of the AsyncResponse javadoc. In the javadoc example the async response suspended from the GET method is resumed later on from the POST method. The suspended async response is passed between requests using a static field and is resumed from the other resource method running on a different request processing thread.

Imagine now a situation when there is a long delay between two requests and you would not like to let the client wait for the response "forever" or at least for an unacceptable long time. In asynchronous processing model, occurrences of such situations should be carefully considered with client connections not being automatically closed when the processing method returns and the response needs to be resumed explicitly based on an event that may actually even never happen. To tackle these situations asynchronous timeouts can be used.

The following example shows the usage of timeouts:

Example 10.2. Simple async method with timeout

@GET
public void asyncGetWithTimeout(@Suspended final AsyncResponse asyncResponse) {
    asyncResponse.setTimeoutHandler(new TimeoutHandler() {

        @Override
        public void handleTimeout(AsyncResponse asyncResponse) {
            asyncResponse.resume(Response.status(Response.Status.SERVICE_UNAVAILABLE)
                    .entity("Operation time out.").build());
        }
    });
    asyncResponse.setTimeout(20, TimeUnit.SECONDS);

    new Thread(new Runnable() {

        @Override
        public void run() {
            String result = veryExpensiveOperation();
            asyncResponse.resume(result);
        }

        private String veryExpensiveOperation() {
            // ... very expensive operation that typically finishes within 20 seconds
        }
    }).start();
}


By default, there is no timeout defined on the suspended AsyncResponse instance. A custom timeout and timeout event handler may be defined usingsetTimeoutHandler(TimeoutHandler) and setTimeout(long, TimeUnit) methods. The setTimeoutHandler(TimeoutHandler) method defines the handler that will be invoked when timeout is reached. The handler resumes the response with the response code 503 (from Response.Status.SERVICE_UNAVAILABLE). A timeout interval can be also defined without specifying a custom timeout handler (using just the setTimeout(long, TimeUnit) method). In such case the default behaviour of Jersey runtime is to throw a ServiceUnavailableException that gets mapped into 503, "Service Unavailable" HTTP error response, as defined by the JAX-RS specification.

10.1.1. Asynchronous Server-side Callbacks

As operations in asynchronous cases might take long time and they are not always finished within a single resource method invocation, JAX-RS offers facility to register callbacks to be invoked based on suspended async response state changes. In Jersey you can register two JAX-RS callbacks:

Example 10.3. CompletionCallback example

@Path("/resource")
public class AsyncResource {
    private static int numberOfSuccessResponses = 0;
    private static int numberOfFailures = 0;
    private static Throwable lastException = null;

    @GET
    public void asyncGetWithTimeout(@Suspended final AsyncResponse asyncResponse) {
        asyncResponse.register(new CompletionCallback() {
            @Override
            public void onComplete(Throwable throwable) {
                if (throwable == null) {
                    // no throwable - the processing ended successfully
                    // (response already written to the client)
                    numberOfSuccessResponses++;
                } else {
                    numberOfFailures++;
                    lastException = throwable;
                }
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                // ... very expensive operation
            }
        }).start();
    }
}


A completion callback is registered using register(...) method on the AsyncResponse instance. A registered completion callback is bound only to the response(s) to which it has been registered. In the example the CompletionCallback is used to calculate successfully processed responses, failures and to store last exception. This is only a simple case demonstrating the usage of the callback. You can use completion callback to release the resources, change state of internal resources or representations or handle failures. The method has an argument Throwable which is set only in case of an error. Otherwise the parameter will be null, which means that the response was successfully written. The callback is executed only after the response is written to the client (not immediately after the response is resumed).

The AsyncResponse register(...) method is overloaded and offers options to register a single callback as an Object (in the example), as a Class or multiple callbacks using varags.

As some async requests may take long time to process the client may decide to terminate it's connection to the server before the response has been resumed or before it has been fully written to the client. To deal with these use cases a ConnectionCallback can be used. This callback will be executed only if the connection was prematurely terminated or lost while the response is being written to the back client. Note that this callback will not be invoked when a response is written successfully and the client connection is closed as expected. See javadoc of ConnectionCallback for more information.

10.1.2. Chunked Output

Jersey offers a facility for sending response to the client in multiple more-or-less independent chunks using a chunked output. Each response chunk usually takes some (longer) time to prepare before sending it to the client. The most important fact about response chunks is that you want to send them to the client immediately as they become available without waiting for the remaining chunks to become available too. The first bytes of each chunked response consists of the HTTP headers that are sent to the client. The size -1 is set in the response Content-Length header to indicate that the response is chunked. As noted above, the entity of the response is then sent in chunks as they become available. Client knows that the response is going to be chunked, so it reads each chunk of the response separately, processes it, and waits for more chunks to arrive on the same connection. After some time, the server generates another response chunk and send it again to the client. Server keeps on sending response chunks until it closes the connection after sending the last chunk when the response processing is finished.

In Jersey you can use ChunkedOutput to send response to a client in chunks. Chunks are strictly defined pieces of a response body can be marshalled as a separate entities using Jersey/JAX-RS MessageBodyWriter<T> providers. A chunk can be String, Long or JAXB bean serialized to XML or JSON or any other dacustom type for which a MessageBodyWriter<T> is available.

The resource method that returns ChunkedOutput informs the Jersey runtime that the response will be chunked and that the processing works asynchronously as such. You do not need to inject AsyncResponse to start the asynchronous processing mode in this case. Returning a ChunkedOutput instance from the method is enough to indicate the asynchronous processing. Response headers will be sent to a client when the resource method returns and the client will wait for the stream of chunked data which you will be able to write from different thread using the same ChunkedOutput instance returned from the resource method earlier. The following example demonstrates this use case:

Example 10.4. ChunkedOutput example

@Path("/resource")
public class AsyncResource {
    @GET
    public ChunkedOutput<String> getChunkedResponse() {
        final ChunkedOutput<String> output = new ChunkedOutput<String>(String.class);

        new Thread() {
            public void run() {
                try {
                    String chunk;

                    while ((chunk = getNextString()) != null) {
                        output.write(chunk);
                    }
                } catch (IOException e) {
                    // IOException thrown when writing the
                    // chunks of response: should be handled
                } finally {
                    output.close();
                        // simplified: IOException thrown from
                        // this close() should be handled here...
                }
            }
        }.start();

        // the output will be probably returned even before
        // a first chunk is written by the new thread
        return output;
    }

    private String getNextString() {
        // ... long running operation that returns
        //     next string or null if no other string is accessible
    }
}


The example above defines a GET method that returns a ChunkedOutput instance. The generic type of ChunkedOutput defines the chunk types (in this case chunks are Strings). Before the instance is returned a new thread is started that writes individual chunks into the chunked output instance named output. Once the original thread returns from the resource method, Jersey runtime writes headers to the container response but does not close the client connection yet and waits for the response data to be written to the chunked output. New thread in a loop calls the method getNextString() which returns a next String or null if no other String exists (the method could for example load latest data from the database). Returned Strings are written to the chunked output. Such a written chunks are internally written to the container response and client can read them. At the end the chunked output is closed which determines the end of the chunked response. Please note that you must close the output explicitly in order to close the client connection as Jersey does not implicitly know when you are finished with writing the chunks.

A chunked output can be processed also from threads created from another request as it is explained in the sections above. This means that one resource method may e.g. only return a ChunkedOutput instance and other resource method(s) invoked from another request thread(s) can write data into the chunked output and/or close the chunked response.

10.2. Client API

The client API supports asynchronous processing too. Simple usage of asynchronous client API is shown in the following example:

Example 10.5. Simple client async invocation

final AsyncInvoker asyncInvoker = target().path("http://example.com/resource/")
        .request().async();
final Future<Response> responseFuture = asyncInvoker.get();
System.out.println("Request is being processed asynchronously.");
final Response response = responseFuture.get();
    // get() waits for the response to be ready
System.out.println("Response received.");


The difference against synchronous invocation is that the http method call get() is not called on SyncInvoker but on AsyncInvoker. The AsyncInvoker is returned from the call of method Invocation.Builder.async() as shown above. AsyncInvoker offers methods similar to SyncInvoker only these methods do not return a response synchronously. Instead a Future<...> representing response data is returned. These method calls also return immediately without waiting for the actual request to complete. In order to get the response of the invoked get() method, the responseFuture.get() is invoked which waits for the response to be finished (this call is blocking as defined by the Java SE Future contract).

Asynchronous Client API in JAX-RS is fully integrated in the fluent JAX-RS Client API flow, so that the async client-side invocations can be written fluently just like in the following example:

Example 10.6. Simple client fluent async invocation

final Future<Response> responseFuture = target().path("http://example.com/resource/")
        .request().async().get();


To work with asynchronous results on the client-side, all standard Future API facilities can be used. For example, you can use the isDone() method to determine whether a response has finished to avoid the use of a blocking call to Future.get().

10.2.1. Asynchronous Client Callbacks

Similarly to the server side, in the client API you can register asynchronous callbacks too. You can use these callbacks to be notified when a response arrives instead of waiting for the response on Future.get() or checking the status by Future.isDone() in a loop. A client-side asynchronous invocation callback can be registered as shown in the following example:

Example 10.7. Client async callback

final Future<Response> responseFuture = target().path("http://example.com/resource/")
        .request().async().get(new InvocationCallback<Response>() {
            @Override
            public void completed(Response response) {
                System.out.println("Response status code "
                        + response.getStatus() + " received.");
            }

            @Override
            public void failed(Throwable throwable) {
                System.out.println("Invocation failed.");
                throwable.printStackTrace();
            }
        });


The registered callback is expected to implement the InvocationCallback interface that defines two methods. First method completed(Response) gets invoked when an invocation successfully finishes. The result response is passed as a parameter to the callback method. The second method failed(Throwable) is invoked in case the invocation fails and the exception describing the failure is passed to the method as a parameter. In this case since the callback generic type is Response, thefailed(Throwable) method would only invoked in case the invocation fails because of an internal client-side processing error. It would not be invoked in case a server responds with an HTTP error code, for example if the requested resource is not found on the server and HTTP 404 response code is returned. In such casecompleted(Response) callback method would be invoked and the response passed to the method would contain the returned error response with HTTP 404 error code. This is a special behavior in case the generic callback return type is Response. In the next example an exception is thrown (or failed(Throwable) method on the invocation callback is invoked) even in case a non-2xx HTTP error code is returned.

As with the synchronous client API, you can retrieve the response entity as a Java type directly without requesting a Response first. In case of an InvocationCallback, you need to set its generic type to the expected response entity type instead of using the Response type as demonstrated in the example bellow:

Example 10.8. Client async callback for specific entity

final Future<String> entityFuture = target().path("http://example.com/resource/")
        .request().async().get(new InvocationCallback<String>() {
            @Override
            public void completed(String response) {
                System.out.println("Response entity '" + response + "' received.");
            }

            @Override
            public void failed(Throwable throwable) {
                System.out.println("Invocation failed.");
                throwable.printStackTrace();
            }
        });
System.out.println(entityFuture.get());


Here, the generic type of the invocation callback information is used to unmarshall the HTTP response content into a desired Java type.

Important

Please note that in this case the method failed(Throwable throwable) would be invoked even for cases when a server responds with a non HTTP-2xx HTTP error code. This is because in this case the user does not have any other means of finding out that the server returned an error response.

10.2.2. Chunked input

In an earlier section the ChunkedOutput was described. It was shown how to use a chunked output on the server. In order to read chunks on the client the ChunkedInputcan be used to complete the story.

You can, of course, process input on the client as a standard input stream but if you would like to leverage Jersey infrastructure to provide support of translating message chunk data into Java types using a ChunkedInput is much more straightforward. See the usage of the ChunkedInput in the following example:

Example 10.9. ChunkedInput example

final Response response = target().path("http://example.com/resource/")
        .request().get();
final ChunkedInput<String> chunkedInput =
        response.readEntity(new GenericType<ChunkedInput<String>>() {});
String chunk;
while ((chunk = chunkedInput.read()) != null) {
    System.out.println("Next chunk received: " + chunk);
}


The response is retrieved in a standard way from the server. The entity is read as a ChunkedInput entity. In order to do that the GenericEntity<T> is used to preserve a generic information at run time. If you would not use GenericEntity<T>, Java language generic type erasure would cause that the generic information would get lost at compile time and an exception would be thrown at run time complaining about the missing chunk type definition.

In the next lines in the example, individual chunks are being read from the response. Chunks can come with some delay, so they will be written to the console as they come from the server. After receiving last chunk the null will be returned from the read() method. This will mean that the server has sent the last chunk and closed the connection. Note that the read() is a blocking operation and the invoking thread is blocked until a new chunk comes.

Writing chunks with ChunkedOutput is simple, you only call method write() which writes exactly one chunk to the output. With the input reading it is slightly more complicated. The ChunkedInput does not know how to distinguish chunks in the byte stream unless being told by the developer. In order to define custom chunks boundaries, the ChunkedInput offers possibility to register a ChunkParser which reads chunks from the input stream and separates them. Jersey provides several chunk parser implementation and you can implement your own parser to separate your chunks if you need. In our example above the default parser provided by Jersey is used that separates chunks based on presence of a \r\n delimiting character sequence.

Each incoming input stream is firstly parsed by the ChunkParser, then each chunk is processed by the proper MessageBodyReader<T>. You can define the media type of chunks to aid the selection of a proper MessageBodyReader<T> in order to read chunks correctly into the requested entity types (in our case into Strings).

Chapter 11. URIs and Links

11.1. Building URIs

A very important aspect of REST is hyperlinks, URIs, in representations that clients can use to transition the Web service to new application states (this is otherwise known as "hypermedia as the engine of application state"). HTML forms present a good example of this in practice.

Building URIs and building them safely is not easy with URI, which is why JAX-RS has the UriBuilder class that makes it simple and easy to build URIs safely. UriBuildercan be used to build new URIs or build from existing URIs. For resource classes it is more than likely that URIs will be built from the base URI the web service is deployed at or from the request URI. The class UriInfo provides such information (in addition to further information, see next section).

The following example shows URI building with UriInfo and UriBuilder from the bookmark example:

Example 11.1. URI building

@Path("/users/")
public class UsersResource {

    @Context
    UriInfo uriInfo;

    ...

    @GET
    @Produces("application/json")
    public JSONArray getUsersAsJsonArray() {
        JSONArray uriArray = new JSONArray();
        for (UserEntity userEntity : getUsers()) {
            UriBuilder ub = uriInfo.getAbsolutePathBuilder();
            URI userUri = ub.
                    path(userEntity.getUserid()).
                    build();
            uriArray.put(userUri.toASCIIString());
        }
        return uriArray;
    }
}


UriInfo is obtained using the @Context annotation, and in this particular example injection onto the field of the root resource class is performed, previous examples showed the use of @Context on resource method parameters.

UriInfo can be used to obtain URIs and associated UriBuilder instances for the following URIs: the base URI the application is deployed at; the request URI; and the absolute path URI, which is the request URI minus any query components.

The getUsersAsJsonArray method constructs a JSONArrray, where each element is a URI identifying a specific user resource. The URI is built from the absolute path of the request URI by calling UriInfo.getAbsolutePathBuilder(). A new path segment is added, which is the user ID, and then the URI is built. Notice that it is not necessary to worry about the inclusion of '/' characters or that the user ID may contain characters that need to be percent encoded. UriBuilder takes care of such details.

UriBuilder can be used to build/replace query or matrix parameters. URI templates can also be declared, for example the following will build the URI"http://localhost/segment?name=value":

Example 11.2. Building URIs using query parameters

UriBuilder.fromUri("http://localhost/")
    .path("{a}")
    .queryParam("name", "{value}")
    .build("segment", "value");


11.2. Resolve and Relativize

JAX-RS 2.0 introduced additional URI resolution and relativization methods in the UriBuilder:

Resolve and relativize methods in UriInfo are essentially counterparts to the methods listed above - UriInfo.resolve(java.net.URI) resolves given relative URI to an absolute URI using application context URI as the base URI; UriInfo.relativize(java.net.URI) then transforms an absolute URI to a relative one, using again the applications context URI as the base URI.

UriBuilder also introduces a set of methods that provide ways of resolving URI templates by replacing individual templates with a provided value(s). A short example:

final URI uri = UriBuilder.fromUri("http://{host}/{path}?q={param}")
    .resolveTemplate("host", "localhost")
    .resolveTemplate("path", "myApp")
    .resolveTemplate("param", "value").build();

uri.toString(); // returns "http://localhost/myApp?q=value"

See the UriBuilder javadoc for more details.

11.3. Link

JAX-RS 2.0 introduces Link class, which serves as a representation of Web Link defined in RFC 5988. The JAX-RS Link class adds API support for providing additional metadata in HTTP messages, for example, if you are consuming a REST interface of a public library, you might have a resource returning description of a single book. Then you can include links to related resources, such as a book category, author, etc. to make the produced response concise but complete at the same time. Clients are then able to query all the additional information they are interested in and are not forced to consume details they are not interested in. At the same time, this approach relieves the server resources as only the information that is truly requested is being served to the clients.

Link can be serialized to an HTTP message (tyically a response) as additional HTTP header (there might be multiple Link headers provided, thus multiple links can be served in a single message). Such HTTP header may look like:

Link: <http://example.com/TheBook/chapter2>; rel="prev"; title="previous chapter"

Producing and consuming Links with JAX-RS API is demonstrated in the following example:

// server side - adding links to a response:
Response r = Response.ok().
    link("http://oracle.com", "parent").
    link(new URI("http://jersey.java.net"), "framework").
    build();

...

// client-side processing:
final Response response = target.request().get();

URI u = response.getLink("parent").getUri();
URI u = response.getLink("framework").getUri();

Instances of Link can be also created directly by invoking one of the factory methods on the Link API that returns a Link.Builder that can be used to configure and produce new links.

Chapter 12. Programmatic API for Building Resources

12.1. Introduction

A standard approach of developing JAX-RS application is to implement resource classes annotated with @Path with resource methods annotated with HTTP method annotations like @GET or @POST and implement needed functionality. This approach is described in the chapter JAX-RS Application, Resources and Sub-Resources. Besides this standard JAX-RS approach, Jersey offers an API for constructing resources programmatically.

Imagine a situation where a deployed JAX-RS application consists of many resource classes. These resources implement standard HTTP methods like @GET@POST,@DELETE. In some situations it would be useful to add an @OPTIONS method which would return some kind of meta data about the deployed resource. Ideally, you would want to expose the functionality as an additional feature and you want to decide at the deploy time whether you want to add your custom OPTIONS method. However, when custom OPTIONS method are not enabled you would like to be OPTIONS requests handled in the standard way by JAX-RS runtime. To achieve this you would need to modify the code to add or remove custom OPTIONS methods before deployment. Another way would be to use programmatic API to build resource according to your needs.

Another use case of programmatic resource builder API is when you build any generic RESTful interface which depends on lot of configuration parameters or for example database structure. Your resource classes would need to have different methods, different structure for every new application deploy. You could use more solutions including approaches where your resource classes would be built using Java byte code manipulation. However, this is exactly the case when you can solve the problem cleanly with the programmatic resource builder API. Let's have a closer look at how the API can be utilized.

12.2. Programmatic Hello World example

Jersey Programmatic API was designed to fully support JAX-RS resource model. In other words, every resource that can be designed using standard JAX-RS approach via annotated resource classes can be also modelled using Jersey programmatic API. Let's try to build simple hello world resource using standard approach first and then using the Jersey programmatic resource builder API.

The following example shows standard JAX-RS "Hello world!" resource class.

Example 12.1. A standard resource class

                    @Path("helloworld")
                    public class HelloWorldResource {

                        @GET
                        @Produces("text/plain")
                        public String getHello() {
                            return "Hello World!";
                        }
                    }
                


This is just a simple resource class with one GET method returning "Hello World!" string that will be serialized as text/plain media type.

Now we will design this simple resource using programmatic API.

Example 12.2. A programmatic resource

                    package org.glassfish.jersey.examples.helloworld;

                    import javax.ws.rs.container.ContainerRequestContext;
                    import javax.ws.rs.core.Application;
                    import javax.ws.rs.core.Response;
                    import org.glassfish.jersey.process.Inflector;
                    import org.glassfish.jersey.server.ResourceConfig;
                    import org.glassfish.jersey.server.model.Resource;
                    import org.glassfish.jersey.server.model.ResourceMethod;


                    public static class MyResourceConfig extends ResourceConfig {

                        public MyResourceConfig() {
                            final Resource.Builder resourceBuilder = Resource.builder();
                            resourceBuilder.path("helloworld");

                            final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET");
                            methodBuilder.produces(MediaType.TEXT_PLAIN_TYPE)
                                    .handledBy(new Inflector<ContainerRequestContext, String>() {

                                @Override
                                public String apply(ContainerRequestContext containerRequestContext) {
                                    return "Hello World!";
                                }
                            });

                            final Resource resource = resourceBuilder.build();
                            registerResources(resource);
                        }
                    }
                


First, focus on the content of the MyResourceConfig constructor in the example. The Jersey programmatic resource model is constructed from Resources that containResourceMethods. In the example, a single resource would be constructed from a Resource containing one GET resource method that returns "Hello World!". The main entry point for building programmatic resources in Jersey is the Resource.Builder class. Resource.Builder contains just a few methods like the path method used in the example, which sets the name of the path. Another useful method is a addMethod(String path) which adds a new method to the resource builder and returns a resource method builder for the new method. Resource method builder contains methods which set consumed and produced media type, define name bindings, timeout for asynchronous executions, etc. It is always necessary to define a resource method handler (i.e. the code of the resource method that will return "Hello World!"). There are more options how a resource method can be handled. In the example the implementation of Inflector is used. The Jersey Inflector interface defines a simple contract for transformation of a request into a response. An inflector can either return a Response or directly an entity object, the way it is shown in the example. Another option is to setup a Java method handler using handledBy(Class<?> handlerClass, Method method) and pass it the chosen java.lang.reflect.Method instance together with the enclosing class.

A resource method model construction can be explicitly completed by invoking build() on the resource method builder. It is however not necessary to do so as the new resource method model will be built automatically once the parent resource is built. Once a resource model is built, it is registered into the resource config at the last line of the MyResourceConfig constructor in the example.

12.2.1. Deployment of programmatic resources

Let's now look at how a programmatic resources are deployed. The easiest way to setup your application as well as register any programmatic resources in Jersey is to use a Jersey ResourceConfig utility class, an extension of Application class. If you deploy your Jersey application into a Servlet container you will need to provide aApplication subclass that will be used for configuration. You may use a web.xml where you would define a org.glassfish.jersey.servlet.ServletContainerServlet entry there and specify initial parameter javax.ws.rs.Application with the class name of your JAX-RS Application that you wish to deploy. In the example above, this application will be MyResourceConfig class. This is the reason why MyResourceConfig extends the ResourceConfig (which, if you remember extends the javax.ws.rs.Application).

The following example shows a fragment of web.xml that can be used to deploy the ResourceConfig JAX-RS application.

Example 12.3. A programmatic resource

                        ...
                        <servlet>
                            <servlet-name>org.glassfish.jersey.examples.helloworld.MyApplication</servlet-name>
                            <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
                            <init-param>
                                <param-name>javax.ws.rs.Application</param-name>
                                <param-value>org.glassfish.jersey.examples.helloworld.MyResourceConfig</param-value>
                            </init-param>
                            <load-on-startup>1</load-on-startup>
                        </servlet>
                        <servlet-mapping>
                            <servlet-name>org.glassfish.jersey.examples.helloworld.MyApplication</servlet-name>
                            <url-pattern>/*</url-pattern>
                        </servlet-mapping>
                        ...
                    


If you use another deployment options and you have accessible instance of ResourceConfig which you use for configuration, you can register programmatic resources directly by registerResources() method called on the ResourceConfig. Please note that the method registerResources() replaces all the previously registered resources.

Because Jersey programmatic API is not a standard JAX-RS feature the ResourceConfig must be used to register programmatic resources as shown above. Seedeployment chapter for more information.

12.3. Additional examples

Example 12.4. A programmatic resource

                    final Resource.Builder resourceBuilder = Resource.builder(HelloWorldResource.class);
                    resourceBuilder.addMethod("OPTIONS")
                        .handledBy(new Inflector<ContainerRequestContext, Response>() {
                            @Override
                            public Response apply(ContainerRequestContext containerRequestContext) {
                                return Response.ok("This is a response to an OPTIONS method.").build();
                            }
                        });
                    final Resource resource = resourceBuilder.build();
                


In the example above the Resource is built from a HelloWorldResource resource class. The resource model built this way contains a GET method producing'text/plain' responses with "Hello World!" entity. This is quite important as it allows you to whatever Resource objects based on introspecting existing JAX-RS resources and use builder API to enhance such these standard resources. In the example we used already implemented HelloWorldResource resource class and enhanced it by OPTIONS method. The OPTIONS method is handled by an Inflector which returns Response.

The following sample shows how to define sub-resource methods (methods that contains sub-path).

Example 12.5. A programmatic resource

                    final Resource.Builder resourceBuilder = Resource.builder("helloworld");

                    final Resource.Builder childResource = resourceBuilder.addChildResource("subresource");
                    childResource.addMethod("GET").handledBy(new GetInflector());

                    final Resource resource = resourceBuilder.build();
                


Sub-resource methods are defined using so called child resource models. Child resource models (or child resources) are programmatic resources build in the same way as any other programmatic resource but they are registered as a child resource of a parent resource. The child resource in the example is build directly from the parent builder using method addChildResource(String path). However, there is also an option to build a child resource model separately as a standard resource and then add it as a child resource to a selected parent resource. This means that child resource objects can be reused to define child resources in different parent resources (you just build a single child resource and then register it in multiple parent resources). Each child resource groups methods with the same sub-resource path. Note that a child resource cannot have any child resources as there is nothing like sub-sub-resource method concept in JAX-RS. For example if a sub resource method contains more path segments in its path (e.g. "/root/sub/resource/method" where "root" is a path of the resource and "sub/resource/method" is the sub resource method path) then parent resource will have path "root" and child resource will have path "sub/resource/method" (so, there will not be any separate nested sub-resources for "sub", "resource" and "method").

See the javadocs of the resource builder API for more information.

12.4. Model processors

Jersey gives you an option to register so called model processor providers. These providers are able to modify or enhance the application resource model during application deployment. This is an advanced feature and will not be needed in most use cases. However, imagine you would like to add OPTIONS resource method to each deployed resource as it is described at the top of this chapter. You would want to do it for every programmatic resource that is registered as well as for all standard JAX-RS resources.

To do that, you first need to register a model processor provider in your application, which implements org.glassfish.jersey.server.model.ModelProcessorextension contract. An example of a model processor implementation is shown here:

Example 12.6. A programmatic resource

                    import javax.ws.rs.GET;
                    import javax.ws.rs.Path;
                    import javax.ws.rs.Produces;
                    import javax.ws.rs.container.ContainerRequestContext;
                    import javax.ws.rs.core.Application;
                    import javax.ws.rs.core.Configuration;
                    import javax.ws.rs.core.MediaType;
                    import javax.ws.rs.core.Response;
                    import javax.ws.rs.ext.Provider;

                    import org.glassfish.jersey.process.Inflector;
                    import org.glassfish.jersey.server.model.ModelProcessor;
                    import org.glassfish.jersey.server.model.Resource;
                    import org.glassfish.jersey.server.model.ResourceMethod;
                    import org.glassfish.jersey.server.model.ResourceModel;

                    @Provider
                    public static class MyOptionsModelProcessor implements ModelProcessor {

                        @Override
                        public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) {
                            // we get the resource model and we want to enhance each resource by OPTIONS method
                            ResourceModel.Builder newResourceModelBuilder = new ResourceModel.Builder(false);
                            for (final Resource resource : resourceModel.getResources()) {
                                // for each resource in the resource model we create a new builder which is based on the old resource
                                final Resource.Builder resourceBuilder = Resource.builder(resource);

                                // we add a new OPTIONS method to each resource
                                // note that we should check whether the method does not yet exist to avoid failures
                                resourceBuilder.addMethod("OPTIONS")
                                    .handledBy(new Inflector<ContainerRequestContext, String>() {
                                        @Override
                                        public String apply(ContainerRequestContext containerRequestContext) {
                                            return "On this path the resource with " + resource.getResourceMethods().size()
                                                + " methods is deployed.";
                                        }
                                        }).produces(MediaType.TEXT_PLAIN);

                                // we add to the model new resource which is a combination of the old resource enhanced
                                // by the OPTIONS method
                                newResourceModelBuilder.addResource(resourceBuilder.build());
                            }

                            final ResourceModel newResourceModel = newResourceModelBuilder.build();
                            // and we return new model
                            return newResourceModel;
                        };

                        @Override
                        public ResourceModel processSubResource(ResourceModel subResourceModel, Configuration configuration) {
                            // we just return the original subResourceModel which means we do not want to do any modification
                            return subResourceModel;
                        }
                    }
                


The MyOptionsModelProcessor from the example is a relatively simple model processor which iterates over all registered resources and for all of them builds a new resource that is equal to the old resource except it is enhanced with a new OPTIONS method.

Note that you only need to register such a ModelProcessor as your custom extension provider in the same way as you would register any standard JAX-RS extension provider. During an application deployment, Jersey will look for any registered model processor and execute them. As you can seem, model processors are very powerful as they can do whatever manipulation with the resource model they like. A model processor can even, for example, completely ignore the old resource model and return a new custom resource model with a single "Hello world!" resource, which would result in only the "Hello world!" resource being deployed in your application. Of course, it would not not make much sense to implement such model processor, but the scenario demonstrates how powerful the model processor concept is. A better, real-life use case scenario would, for example, be to always add some custom new resource to each application that might return additional metadata about the deployed application. Or, you might want to filter out particular resources or resource methods, which is another situation where a model processor could be used successfully.

Also note that processSubResource(ResourceModel subResourceModel, Configuration configuration) method is executed for each sub resource returned from the sub resource locator. The example is simplified and does not do any manipulation but probably in such a case you would want to enhance all sub resources with a new OPTIONS method handlers too.

It is important to remember that any model processor must always return valid resource model. As you might have already noticed, in the example above this important rule is not followed. If any of the resources in the original resource model would already have an OPTIONS method handler defined, adding another handler would cause the application fail during the deployment in the resource model validation phase. In order to retain the consistency of the final model, a model processor implementation would have to be more robust than what is shown in the example.

Chapter 13. Server-Sent Events (SSE) Support

13.1. What are Server-Sent Events

In a standard HTTP request-response scenario a client opens a connection, sends a HTTP request to the server (for example a HTTP GET request), then receives a HTTP response back and the server closes the connection once the response is fully sent/received. The initiative always comes from a client when the client requests all the data. In contrast, Server-Sent Events (SSE) is a mechanism that allows server to asynchronously push the data from the server to the client once the client-server connection is established by the client. Once the connection is established by the client, it is the server who provides the data and decides to send it to the client whenever new "chunk" of data is available. When a new data event occurs on the server, the data event is sent by the server to the client. Thus the name Server-Sent Events. Note that at high level there are more technologies working on this principle, a short overview of the technologies supporting server-to-client communication is in this list:

Polling

With polling a client repeatedly sends new requests to a server. If the server has no new data, then it send appropriate indication and closes the connection. The client then waits a bit and sends another request after some time (after one second, for example).

Long-polling

With long-polling a client sends a request to a server. If the server has no new data, it just holds the connection open and waits until data is available. Once the server has data (message) for the client, it uses the connection and sends it back to the client. Then the connection is closed.

Server-Sent events

SSE is similar to the long-polling mechanism, except it does not send only one message per connection. The client sends a request and server holds a connection until a new message is ready, then it sends the message back to the client while still keeping the connection open so that it can be used for another message once it becomes available. Once a new message is ready, it is sent back to the client on the same initial connection. Client processes the messages sent back from the server individually without closing the connection after processing each message. So, SSE typically reuses one connection for more messages (called events). SSE also defines a dedicated media type that describes a simple format of individual evnets sent from the server to the client. SSE also offers standard javascript client API implemented most modern browsers. For more information about SSE, see the SSE API specification.

WebSocket

WebSocket technology is different from previous technologies as it provides a real full duplex connection. The initiator is again a client which sends a request to a server with a special HTTP header that informs the server that the HTTP connection may be "upgraded" to a full duplex TCP/IP WebSocket connection. If server supports WebSocket, it may choose to do so. Once a WebSocket connection is established, it can be used for bi-directional communication between the client and the server. Both client and server can then send data to the other party at will whenever it is needed. The communication on the new WebSocket connection is no longer based on HTTP protocol and can be used for example for for online gaming or any other applications that require fast exchange of small chunks of data in flowing in both directions.

13.2. When to use Server-Sent Events

As explained above, SSE is a technology that allows clients to subscribe to event notifications that originate on a server. Server generates new events and sends these events back to the clients subscribed to receive the notifications. In other words, SSE offers a solution for a one-way publish-subscribe model.

A good example of the use case where SSE can be used is a simple message exchange RESTful service. Clients POST new messages to the service and subscribe to receive messages from other clients. Let's call the resource messages. While POSTing a new message to this resource involves a typical HTTP request-response communication between a client and the messages resource, subscribing to receive all new message notifications would be hard and impractical to model with a sequence of standard request-response message exchanges. Using Server-sent events provides a much more practical approach here. You can use SSE to let clients subscribe to themessages resource via standard GET request (use a SSE client API, for example javascript API or Jersey Client SSE API) and let the server broadcast new messages to all connected clients in the form of individual events (in our case using Jersey Server SSE API). Note that with Jersey a SSE support is implemented as an usual JAX-RS resource method. There's no need to do anything special to provide a SSE support in your Jersey/JAX-RS applications, your SSE-enabled resources are a standard part of your RESTful Web application that defines the REST API of your application. The following chapters describes SSE support in Jersey in more details.

Important

Note, that while SSE in Jersey is supported with standard JAX-RS resources, Jersey SSE APIs are not part of the JAX-RS specification. SSE support and related APIs are a Jersey specific feature that extends JAX-RS.

13.3. Jersey Server-Sent Events API

This chapter briefly describes the Jersey support for SSE. Details and examples will be covered in chapters below.

Jersey contains support for SSE for both - server and client. SSE in Jersey is implemented as an extension supporting a new media type, which means that SSE really treated as just another media type that can be returned from a resource method and processed by the client. There is only a minimal additional support for "chunked" messages added to Jersey which could not be implemented as standard JAX-RS media type extension.

Before you start working with Jersey SSE, in order to add support for SSE you need to include the dependency to the SSE media type module:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-sse</artifactId>
</dependency>

Then you need register SseFeature. The SseFeature is a feature that can be registered for both, the client and the server.

SseFeature adds new supported entity (representation) Java types, namely OutboundEvent for the outbound server events and InboundEvent for inbound client events. These types are serialized by OutboundEvent and de-serialized by InboundEventReader. There is no restriction for a media type used in individual event messages; however the media type used for a SSE stream as whole is "text/event-stream" and this media type should be set on messages that are used to serve SSE events (for example on the server side using @Produces on the method that returns an EventOutput - see bellow). The InboundEvent and OutboundEvent contain all the fields needed for composing and processing individual SSE events. These entities represent the chunks sent or received over an open server-to-client connection that is represented by anChunkedOutput on the servers side and ChunkedInput on the client side (if you are not familiar with ChunkedOutput and ChunkedInput, see the Async chapter first for more details). In other words, our resource method that is used to open a SSE connection to a client does not return individual OutboundEvents. Instead, a new instance of EventOutput is returned. EventOutput is a typed extension of ChunkedOutput<OutboundEvent>. Similarly, to receive InboundEvents on a client side, Jersey SSE API provides a EventInput that represents a typed extension of ChunkedInput<InboundEvent>.

The Jersey server SSE API also contains a SseBroadcaster utility, that provides a convenient way of grouping multiple EventOutput instances that represent individual client connections into a group, and exposes methods for broadcasting new events to all the client connections grouped in the broadcaster. The SseBroadcaster inherits from Broadcaster which is the generic broadcaster implementation of the Jersey chunked message processing facility. On the he client side, the Jersey SSE API contains additional EventSource and EventListener classes that further improve convenience of processing new inbound SSE events.

13.4. Implementing SSE support in a JAX-RS resource

13.4.1. Simple SSE resource method

Firstly you need to add a Jersey SSE module dependency to your project as shown in the earlier section and register the SseFeature from this module in your Application orResourceConfig. Once done, you are ready to add SSE support to your resource:

Example 13.1. Simple SSE resource method

...
import org.glassfish.jersey.media.sse.EventOutput;
import org.glassfish.jersey.media.sse.OutboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
...

@Path("events")
public static class SseResource {

    @GET
    @Produces(SseFeature.SERVER_SENT_EVENTS)
    public EventOutput getServerSentEvents() {
        final EventOutput eventOutput = new EventOutput();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 10; i++) {
                        // ... code that waits 1 second
                        final OutboundEvent.Builder eventBuilder
                        = new OutboundEvent.Builder();
                        eventBuilder.name("message-to-client");
                        eventBuilder.data(String.class,
                            "Hello world " + i + "!");
                        final OutboundEvent event = eventBuilder.build();
                        eventOutput.write(event);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(
                        "Error when writing the event.", e);
                } finally {
                    try {
                        eventOutput.close();
                    } catch (IOException ioClose) {
                        throw new RuntimeException(
                            "Error when closing the event output.", ioClose);
                    }
                }
            }
        }).start();
        return eventOutput;
    }
}


The code above defines the resource deployed on URI "/events". This resource has a single @GET resource method which returns as an entity EventOutput - an extension of generic Jersey ChunkedOutput API for output chunked message processing.

Note

If you are not familiar with ChunkedOutput and ChunkedInput, see the Async chapter first for more details.

After the eventOutput is returned from the method, the Jersey runtime recognizes that this is a ChunkedOutput extension and does not close the client connection immediately. Instead, it writes the HTTP headers to the response stream and waits for more chunks (SSE events) to be sent. At this point the client can read headers and starts listening for individual events.

Note

Since Jersey runtime does not implicitly close the connection to the client (similarly to asynchronous processing), closing the connection is a responsibility of the resource method or the client listening on the open connection for new events (see following example).

In the Example 13.1, “Simple SSE resource method”, the resource method creates a new thread that sends a sequence of 10 events. There is a 1 second delay between two subsequent events as indicated in a comment. Each event is represented by OutboundEvent type and is built with a helpf of an outbound event Builder. TheOutboundEvent reflects the standardized format of SSE messages and contains properties that represent name (for named events), commentdata or id. The code also sets the event data media type using the mediaType(MediaType) method on the eventBuilder. The media type, together with the data type set by the data(Class, Object> method (in our case String.class), is used for serialization of the event data. Note that the event data media type will not be written to any headers as the response Content-type header is already defined by the @Produces and set to "text/event-stream" using constant from the SseFeature. The event media type is used for serialization of event data. Event data media type and Java type are used to select the proper MessageBodyWriter<T> for event data serialization and are passed to the selected writer that serializes the event data content. In our case the string "Hello world " + i + "!" is serialized as "text/plain". In event data you can send any Java entity and associate it with any media type that you would be able to serialize with an available MessageBodyWriter<T>. Typically, you may want to send e.g. JSON data, so you would fill the data with a JAXB annotated bean instance and define media type to JSON.

Note

If the event media type is not set explicitly, the "text/plain" media type is used by default.

Once an outbound event is ready, it can be written to the eventOutput. At that point the event is serialized by internal OutboundEventWriter which uses an appropriate MessageBodyWriter<T> to serialize the "Hello world " + i + "!" string. You can send as many messages as you like. At the end of the thread execution the response is closed which also closes the connection to the client. After that, no more messages can be send to the client on this connection. If the client would like to receive more messages, it would have to send a new request to the server to initiate a new SSE streaming connection.

A client connecting to our SSE-enabled resource will receive the following data from the entity stream:

event: message-to-client
data: Hello world 0!

event: message-to-client
data: Hello world 1!

event: message-to-client
data: Hello world 2!

event: message-to-client
data: Hello world 3!

event: message-to-client
data: Hello world 4!

event: message-to-client
data: Hello world 5!

event: message-to-client
data: Hello world 6!

event: message-to-client
data: Hello world 7!

event: message-to-client
data: Hello world 8!

event: message-to-client
data: Hello world 9!

Each message is received with a delay of one second.

13.4.2. Broadcasting with Jersey SSE

Jersey SSE server API defines SseBroadcaster which allows to broadcast individual events to multiple clients. A simple broadcasting implementation is shown in the following example:

Example 13.2. Broadcasting SSE messages

...
import org.glassfish.jersey.media.sse.SseBroadcaster;
...

@Singleton
@Path("broadcast")
public static class BroadcasterResource {

    private SseBroadcaster broadcaster = new SseBroadcaster();

    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.TEXT_PLAIN)
    public String broadcastMessage(String message) {
        OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
        OutboundEvent event = eventBuilder.name("message")
            .mediaType(MediaType.TEXT_PLAIN_TYPE)
            .data(String.class, message)
            .build();

        broadcaster.broadcast(event);

        return "Message was '" + message + "' broadcast.";
    }

    @GET
    @Produces(SseFeature.SERVER_SENT_EVENTS)
    public EventOutput listenToBroadcast() {
        final EventOutput eventOutput = new EventOutput();
        this.broadcaster.add(eventOutput);
        return eventOutput;
    }
}


Let's explore the example together. The BroadcasterResource resource class is annotated with @Singleton annotation which tells Jersey runtime that only a single instance of the resource class should be used to serve all the incoming requests to /broadcast path. This is needed as we want to keep an application-wide single reference to the private broadcaster field so that we can use the same instance for all requests. Clients that want to listen to SSE events first send a GET request to theBroadcasterResource, that is handled by the listenToBroadcast() resource method. The method creates a new EventOutput representing the connection to the requesting client and registers this eventOutput instance with the singleton broadcaster, using its add(EventOutput) method. The method then returns theeventOutput which causes Jersey to bind the eventOutput instance with the requesting client and send the response HTTP headers to the client. The client connection remains open and the client is now waiting ready to receive new SSE events. All the events are written to the eventOutput by broadcaster later on. This way developers can conveniently handle sending new events to all the clients that subscribe to them.

When a client wants to broadcast new message to all the clients listening on their SSE connections, it sends a POST request to BroadcasterResource resource with the message content. The method broadcastMessage(String) is invoked on BroadcasterResource resource with the message content as an input parameter. A new SSE outbound event is built in the standard way and passed to the broadcaster. The broadcaster internally invokes write(OutboundEvent) on all registeredEventOutputs. After that the method just return a standard text response to the POSTing client to inform the client that the message was successfully broadcast. As you can see, the broadcastMessage(String) resource method is just a simple JAX-RS resource method.

In order to implement such a scenario, you may have noticed, that the Jersey SseBroadcaster is not mandatory to complete the use case. individual EventOutputs can be just stored in a collection and iterated over in the broadcastMessage method. However, the SseBroadcaster internally identifies and handles also client disconnects. When a client closes the connection the broadcaster detects this and removes the stale connection from the internal collection of the registered EventOutputs as well as it frees all the server-side resources associated with the stale connection. Additionally, the SseBroadcaster is implemented to be thread-safe, so that clients can connect and disconnect in any time and SseBroadcaster will always broadcast messages to the most recent collection of registered and active set of clients.

13.5. Consuming SSE events with Jersey clients

On the client side, Jersey exposes APIs that support receiving and processing SSE events using two programming models:

Pull model - pulling events from a EventInput, or
Push model - listening for asynchronous notifications of EventSource

Both models will be described.

13.5.1. Reading SSE events with EventInput

The events can be read on the client side from a EventInput. See the following code:

Client client = ClientBuilder.newBuilder()
        .register(SseFeature.class).build();
WebTarget target = client.target("http://localhost:9998/events");

EventInput eventInput = target.request().get(EventInput.class);
while (!eventInput.isClosed()) {
    final InboundEvent inboundEvent = eventInput.read();
    if (inboundEvent == null) {
        // connection has been closed
        break;
    }
    System.out.println(inboundEvent.getName() + "; "
        + inboundEvent.getData(String.class));
}

In this example, a client connects to the server where the SseResource from the Example 13.1, “Simple SSE resource method” is deployed. At first, a new JAX-RS/Jerseyclient instance is created with a SseFeature registered. Then a WebTarget instance is retrieved from the client and is used to invoke a HTTP request. The returned response entity is directly read as a EventInput Java type, which is an extension of Jersey ChunkedInput that provides generic support for consuming chunked message payloads. The code in the example then process starts a loop to process the inbound SSE events read from the eventInput response stream. Each chunk read from the input is a InboundEvent. The method InboundEvent.getData(Class) provides a way for the client to indicate what Java type should be used for the event data de-serialization. In our example, individual events are de-serialized as String Java type instances. This method internally finds and executes a properMessageBodyReader<T> which is the used to do the actual de-serialization. This is similar to reading an entity from the Response by readEntity(Class). The methodgetData can also throw an IO exception.

The null check on inboundEvent is necessary to make sure that the chunk was properly read and connection has not been closed by the server. Once the connection is closed, the loop terminates and the program completes execution. The client code produces the following console output:

message-to-client; Hello world 0!
message-to-client; Hello world 1!
message-to-client; Hello world 2!
message-to-client; Hello world 3!
message-to-client; Hello world 4!
message-to-client; Hello world 5!
message-to-client; Hello world 6!
message-to-client; Hello world 7!
message-to-client; Hello world 8!
message-to-client; Hello world 9!

13.5.2. Asynchronous SSE processing with EventSource

The main Jersey SSE client API component used to read SSE events asynchronously is EventSource. The usage of the EventSource is shown on the following example.

Example 13.3. Registering EventListener with EventSource

Client client = ClientBuilder.newBuilder()
                        .register(SseFeature.class).build();
WebTarget target = client.target("http://example.com/events");
EventSource eventSource = new EventSource(target, false);
EventListener listener = new EventListener() {
        @Override
        public void onEvent(InboundEvent inboundEvent) {
            try {
                System.out.println(inboundEvent.getName() + "; "
                        + inboundEvent.getData(String.class));
            } catch (IOException e) {
                throw new RuntimeException(
                        "Error when deserializing of data.");
            }
        }
    };
eventSource.register(listener, "message-to-client");
eventSource.open();
...
eventSource.close();


In this example, the client code again connects to the server where the SseResource from the Example 13.1, “Simple SSE resource method” is deployed. The Clientinstance is again created and initialized with SseFeature. Then the WebTarget is built. In this case a request to the web target is not made directly in the code, instead, the web target instance is used to initialize a new EventSource instance. The second parameter false of the EventSource constructor tells the EventSource to not automatically connect to the target as part of its initialization logic in the constructor. The connection is established later by calling eventSource.open(). A customEventListener implementation is used to listen to and process incoming SSE events. The method getData(Class) says that the event data should be de-serialized from a received InboundEvent instance into a String Java type. This method call internally executes MessageBodyReader<T> which de-serializes the event data. This is similar to reading an entity from the Response by readEntity(Class). The method getData can throw an IO exception.

The custom event source listener is registered in the event source via EventSource.register(EventListener, String) method. The next method arguments define the names of the events to receive and can be omitted. If names are defined, the listener will be associated with the named events and will only invoked for events with a name from the set of defined event names. It will not be invoked for events with any other name or for events without a name.

Important

It is a common mistake to think that unnamed events will be processed by listeners that are registered to process events from a particular name set. That is NOT the case! Unnamed events are only processed by listeners that are not name-bound. The same limitation applied to HTML5 Javascript SSE Client API supported by modern browsers.

After a connection to the server is opened by calling the open() method on the event source, the eventSource starts listening to events. When an event named"message-to-client" comes, the listener will be executed by the event source. If any other event comes (with a name different from "message-to-client"), the registered listener is not invoked. Once the client is done with processing and does not want to receive events anymore, it closes the connection by calling the close()method on the event source.

The listener from the example above will print the following output:

message-to-client; Hello world 0!
message-to-client; Hello world 1!
message-to-client; Hello world 2!
message-to-client; Hello world 3!
message-to-client; Hello world 4!
message-to-client; Hello world 5!
message-to-client; Hello world 6!
message-to-client; Hello world 7!
message-to-client; Hello world 8!
message-to-client; Hello world 9!

When browsing through the Jersey SSE API documentation, you may have noticed that the EventSource implements EventListener and provides an empty implementation for the onEvent(InboundEvent inboundEvent) listener method. This adds more flexibility to the Jersey client-side SSE API. Instead of defining and registering a separate event listener, in simple scenarios you can also choose to derive directly from the EventSource and override the empty listener method to handle the incoming events. This programming model is shown in the following example:

Example 13.4. Overriding EventSource.onEvent(InboundEvent) method

Client client = ClientBuilder.newBuilder()
                        .register(SseFeature.class).build();
WebTarget target = client.target("http://example.com/events");
EventSource eventSource = new EventSource(target) {
    @Override
    public void onEvent(InboundEvent inboundEvent) {
        if ("message-to-client".equals(inboundEvent.getName())) {
            try {
                System.out.println(inboundEvent.getName() + "; "
                        + inboundEvent.getData(String.class));
            } catch (IOException e) {
                throw new RuntimeException(
                        "Error when deserializing of data.");
            }
        }
    }
};
...
eventSource.close();


The code above is very similar to the code in Example 13.3, “Registering EventListener with EventSource. The EventSource is constructed without the secondboolean open argument. This means, that the connection to the server is by default automatically opened in the event source constructor. The implementation of theEventListener has been moved into the overridden EventSource.onEvent(...) method. However, this time, the listener method will be executed for all events - unnamed as well as with any name. Therefore the code checks the name whether it is an event with the name "message-to-client" that we want to handle. Note that you can still register additional EventListeners later on. The overridden method on the event source allows you to handle messages even when no additional listeners are registered yet.

Chapter 14. Security

14.1. Securing server

14.1.1. SecurityContext

Security information is available by injecting a SecurityContext instance using @Context annotation, that provides essentially the equivalent of the functionality available onHttpServletRequest API. The injected security context depends on the actual Jersey application deployment. For example, if a Jersey application is deployed in a Servlet container, the Jersey SecurityContext will return information of the security context retrieved from Servlet request. For Jersey applications deployed on a Grizzly server, the SecurityContext will return information retrieved from the Grizzly request.

SecurityContext can be used in conjunction with sub-resource locators to return different resources if the user principle is included in a certain role. For example, a sub-resource locator could return a different resource if a user is a preferred customer:

Example 14.1. Accessing SecurityContext

@Path("basket")
public ShoppingBasketResource get(@Context SecurityContext sc) {
    if (sc.isUserInRole("PreferredCustomer") {
        return new PreferredCustomerShoppingBasketResource();
    } else {
        return new ShoppingBasketResource();
    }
}


SecurityContext can be injected also to singleton resources and providers as a class field. In such case the proxy of the request-scoped SecurityContext will be injected.

Example 14.2. Injecting SecurityContext into a singleton resource

@Path("resource")
@Singleton
public static class MyResource {
    @Context
    // Jersey will inject proxy of Security Context
    SecurityContext securityContext;

    @GET
    public String getUserPrincipal() {
        return securityContext.getUserPrincipal().getName();
    }
}


14.1.1.1. Initialize SecurityContext with Servlets

As described above, the SecurityContext by default (if not overwritten by filters) only offers information from an underlying container. In the case you deploy a Jersey application in a Servlet container, you need to setup the <security-constraint><auth-constraint> and user to roles mappings in order to pass correct information to the SecurityContext.

14.1.1.2. SecurityContext in ContainerRequestContext

The SecurityContext can be retrieved also from ContainerRequestContext via getSecurityContext() method. You can also set the SecurityContext into the request using method setSecurityContext(SecurityContext). If you set a new SecurityContext in the ContainerRequestFilter into theContainerRequestContext, then this security context will be used for injections in resource classes (wrapped into the proxy). This way you can implement a custom authentication filter that may setup your own SecurityContext to be used. To ensure the early execution of your custom authentication request filter, set the filter priority to AUTHENTICATION using constants from Priorities. An early execution of you authentication filter will ensure that all other filters, resources, resource methods and sub-resource locators will execute with your custom SecurityContext instance.

14.1.2. Authorization - securing resources

14.1.2.1. Security resources with web.xml

In cases where a Jersey application is deployed in a Servlet container you can rely only on the standard Java EE Web application security mechanisms offered by the Servlet container and configurable via application's web.xml descriptor. You need to define the <security-constraint> elements in the web.xml and assign roles which are able to access these resources. You can also define HTTP methods that are allowed to be executed. See the following example.

Example 14.3. Injecting SecurityContext into singletons

<security-constraint>
    <web-resource-collection>
        <url-pattern>/rest/admin/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>admin</role-name>
    </auth-constraint>
</security-constraint>
<security-constraint>
    <web-resource-collection>
        <url-pattern>/rest/orders/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>customer</role-name>
    </auth-constraint>
</security-constraint>
<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>my-defaul-realm</realm-name>
</login-config>


The example secures two kinds of URI namespaces using the HTTP Basic Authentication. rest/admin/* will be accessible only for user group "admin" andrest/orders/* will be accessible for "customer" user group. This security configuration does not use JAX-RS or Jersey features at all as it is enforced by the Servlet container even before a request reaches the Jersey application. Keeping this security constrains up to date with your JAX-RS application might not be easy as whenever you change the @Path annotations on your resource classes you may need to update also the web.xml security configurations to reflect the changed JAX-RS resource paths. Therefore Jersey offers a more flexible solution based on placing standard Java EE security annotations directly on JAX-RS resource classes and methods.

14.1.2.2. Securing JAX-RS resources with annotations

With Jersey you can define the access to resources based on the user group using annotations. You can for example define that only a user group "admin" can execute specific resource method. To do that you firstly need to register RolesAllowedDynamicFeature as a provider. The following example shows how to register the feature if your deployment is based on a ResourceConfig.

Example 14.4. Registering RolesAllowedDynamicFeature using ResourceConfig

final ResourceConfig resourceConfig = new ResourceConfig(MyResource.class);
resourceConfig.register(RolesAllowedDynamicFeature.class);


Then you can use annotations from package javax.annotation.security defined by JSR-250. See the following example.

Example 14.5. Injecting SecurityContext into singletons

@Path("/")
@PermitAll
public class Resource {
    @RolesAllowed("user")
    @GET
    public String get() { return "GET"; }

    @RolesAllowed("admin")
    @POST
    public String post(String content) { return content; }

    @Path("sub")
    public SubResource getSubResource() {
        return new SubResource();
    }
}


The resource class Resource defined in the example is annotated with a @PermitAll annotation. This means that all methods in the class which do not this annotation will be permitted for all user groups (no restrictions are defined). In our example, the annotation will only apply to the getSubResource() method as it is the only method that does not override the annotation by defining custom role-based security settings using the @RolesAllowed annotation. @RolesAllowed annotation present on other methods defines a role or a set of roles that are allowed to execute a particular method.

These Java EE security annotations are processed internally in the request filter registered using the Jersey RolesAllowedDynamicFeature. The roles defined in the annotations are tested against current roles set in the SecurityContext using the SecurityContext.isUserInRole(String role) method. In case the caller is not in the role specified by the annotation, the HTTP 404 error response is returned.

14.2. Client Security

For details about client security please see the Client chapter. Jersey client allows to define parameters of SSL communication using HTTPS protocol. You can also use jersey built-in authentication filter which performs HTTP Basic Authentication. See the client chapter for more details.

14.3. OAuth

OAuth 1.x support has not been migrated from Jersey 1.x to Jersey 2.x yet. The documentation will be updated once the OAuth support feature will be released in Jersey 2.

Chapter 15. WADL Support

15.1. WADL introduction

Jersey contains support for Web Application Description Language (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.

Let's start with the simple WADL example. In the example there is a simple CountryResource deployed and we request a wadl of this resource. The context root path of the application is http://localhost:9998.

Example 15.1. A simple WADL example - JAX-RS resource definition

@Path("country/{id}")
public static class CountryResource {

    private CountryService countryService;

    public CountryResource() {
        // init countryService
    }

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Country getCountry(@PathParam("countryId") int countryId) {
        return countryService.getCountry(countryId);
    }
}


The WADL of a Jersey application that contains the resource above can be requested by a HTTP GET request to http://localhost:9998/application.wadl. The Jersey will return a response with a WADL content similar to the one in the following example:

Example 15.2. A simple WADL example - WADL content

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.0-SNAPSHOT ${buildNumber}"/>
    <grammars/>
    <resources base="http://localhost:9998/">
        <resource path="country/{id}">
            <param xmlns:xs="http://www.w3.org/2001/XMLSchema"
                type="xs:int" style="template" name="countryId"/>
            <method name="GET" id="getCountry">
                <response>
                    <representation mediaType="application/xml"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="application/vnd.sun.wadl+xml"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="*/*"/>
                </response>
            </method>
        </resource>
        <resource path="application.wadl">
            <method name="GET" id="getWadl">
                <response>
                    <representation mediaType="application/vnd.sun.wadl+xml"/>
                    <representation mediaType="application/xml"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="*/*"/>
                </response>
            </method>
            <resource path="{path}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema"
                    type="xs:string" style="template" name="path"/>
                <method name="GET" id="geExternalGrammar">
                    <response>
                        <representation mediaType="application/xml"/>
                    </response>
                </method>
                <method name="OPTIONS" id="apply">
                    <request>
                        <representation mediaType="*/*"/>
                    </request>
                    <response>
                        <representation mediaType="text/plain"/>
                    </response>
                </method>
                <method name="OPTIONS" id="apply">
                    <request>
                        <representation mediaType="*/*"/>
                    </request>
                    <response>
                        <representation mediaType="*/*"/>
                    </response>
                </method>
            </resource>
        </resource>
    </resources>
</application>


In the example above the returned application WADL is shown in full. WADL schema is defined by the WADL specification. The root WADL document element is theapplication. It contains global information about the deployed JAX-RS application. Under this element there is a nested element resources which contains zero or moreresource elements. Each resource element describes a single deployed resource. In our example, there are only two root resources - "country/{id}" and"application.wadl". The "application.wadl" resource is the resource that was just requested in order to receive the application WADL document. Even though WADL support is an additional feature in Jersey it is still a resource deployed in the resource model and therefore it is itself present in the returned WADL document. The first resource element with the path="country/{id}" is the element that describes our custom deployed resource. This resource contains a GET method and three OPTIONSmethods. The GET method is our getCountry() method defined in the sample. There is a method name in the id attribute and @Produces is described in theresponse/representation WADL element. OPTIONS methods are the methods that are automatically added by Jersey to each resource. There is an OPTIONS method returning "text/plain" media type, that will return a response with a string entity containing the list of methods deployed on this resource (this means that instead of WADL you can use this OPTIONS method to get similar information in a textual representation). Another OPTIONS method returning */* will return a response with no entity and Allow header that will contain list of methods as a String. The last OPTIONS method producing "application/vnd.sun.wadl+xml" returns a WADL description of the resource "country/{id}". As you can see, all OPTIONS methods return information about the resource to which the HTTP OPTIONS request is made.

Second resource with a path "application.wadl" has, again, similar OPTIONS methods and one GET method which return this WADL. There is also a sub-resource with a path defined by path param {path}. This means that you can request a resource on the URI http://localhost:9998/application.wadl/something. This is used only to return an external grammar if there is any attached. Such a external grammar can be for example an XSD schema of the response entity which if the response entity is a JAXB bean. An external grammar support via Jersey extended WADL support is described in sections below.

Let's now send an HTTP OPTIONS request to "country/{id}" resource using the the curl command:

curl -X OPTIONS -H "Allow: application/vnd.sun.wadl+xml" \
    -v http://localhost:9998/country/15

We should see a WADL returned similar to this one:

Example 15.3. OPTIONS method returning WADL

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/"
        jersey:generatedBy="Jersey: 2.0-SNAPSHOT ${buildNumber}"/>
    <grammars/>
    <resources base="http://localhost:9998/">
        <resource path="country/15">
            <method name="GET" id="getCountry">
                <response>
                    <representation mediaType="application/xml"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="application/vnd.sun.wadl+xml"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="*/*"/>
                </response>
            </method>
        </resource>
    </resources>
</application>


The returned WADL document has the standard WADL structure that we saw in the WADL document returned for the whole Jersey application earlier. The main difference here is that the only resource is the resource to which the OPTIONS HTTP request was sent. The resource has now path "country/15" and not "country/{id}" as the path parameter {id} was already specified in the request to this concrete resource.

Another, a more complex WADL example is shown in the next example.

Example 15.4. More complex WADL example - JAX-RS resource definition

@Path("customer/{id}")
public static class CustomerResource {
    private CustomerService customerService;

    @GET
    public Customer get(@PathParam("id") int id) {
        return customerService.getCustomerById(id);
    }

    @PUT
    public Customer put(Customer customer) {
        return customerService.updateCustomer(customer);
    }

    @Path("address")
    public CustomerAddressSubResource getCustomerAddress(@PathParam("id") int id) {
        return new CustomerAddressSubResource(id);
    }

    @Path("additional-info")
    public Object getAdditionalInfoSubResource(@PathParam("id") int id) {
        return new CustomerAddressSubResource(id);
    }

}


public static class CustomerAddressSubResource {
    private final int customerId;
    private CustomerService customerService;

    public CustomerAddressSubResource(int customerId) {
        this.customerId = customerId;
        this.customerService = null; // init customer service here
    }

    @GET
    public String getAddress() {
        return customerService.getAddressForCustomer(customerId);
    }

    @PUT
    public void updateAddress(String address) {
        customerService.updateAddressForCustomer(customerId, address);
    }

    @GET
    @Path("sub")
    public String getDeliveryAddress() {
        return customerService.getDeliveryAddressForCustomer(customerId);
    }
}


The GET request to http://localhost:9998/application.wadl will return the following WADL document:

Example 15.5. More complex WADL example - WADL content

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/"
        jersey:generatedBy="Jersey: 2.0-SNAPSHOT ${buildNumber}"/>
    <grammars/>
    <resources base="http://localhost:9998/">
        <resource path="customer/{id}">
            <param xmlns:xs="http://www.w3.org/2001/XMLSchema"
                type="xs:int" style="template" name="id"/>
            <method name="GET" id="get">
                <response/>
            </method>
            <method name="PUT" id="put">
                <response/>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="application/vnd.sun.wadl+xml"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="*/*"/>
                </response>
            </method>
            <resource path="additional-info">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema"
                    type="xs:int" style="template" name="id"/>
            </resource>
            <resource path="address">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema"
                    type="xs:int" style="template" name="id"/>
                <method name="GET" id="getAddress">
                    <response/>
                </method>
                <method name="PUT" id="updateAddress"/>
                <resource path="sub">
                    <method name="GET" id="getDeliveryAddress">
                        <response/>
                    </method>
                </resource>
            </resource>
        </resource>
        <resource path="application.wadl">
            <method name="GET" id="getWadl">
                <response>
                    <representation mediaType="application/vnd.sun.wadl+xml"/>
                    <representation mediaType="application/xml"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="text/plain"/>
                </response>
            </method>
            <method name="OPTIONS" id="apply">
                <request>
                    <representation mediaType="*/*"/>
                </request>
                <response>
                    <representation mediaType="*/*"/>
                </response>
            </method>
            <resource path="{path}">
                <param xmlns:xs="http://www.w3.org/2001/XMLSchema"
                    type="xs:string" style="template" name="path"/>
                <method name="GET" id="geExternalGrammar">
                    <response>
                        <representation mediaType="application/xml"/>
                    </response>
                </method>
                <method name="OPTIONS" id="apply">
                    <request>
                        <representation mediaType="*/*"/>
                    </request>
                    <response>
                        <representation mediaType="text/plain"/>
                    </response>
                </method>
                <method name="OPTIONS" id="apply">
                    <request>
                        <representation mediaType="*/*"/>
                    </request>
                    <response>
                        <representation mediaType="*/*"/>
                    </response>
                </method>
            </resource>
        </resource>
    </resources>
</application>


The resource with path="customer/{id}" is similar to the country resource from the previous example. There is a path parameter which identifies the customer by id. The resource contains 2 user-declared methods and again auto-generated OPTIONS methods added by Jersey. THe resource declares 2 sub-resource locators which are represented in the returned WADL document as nested resource elements. Note that the sub-resource locator getCustomerAddress() returns a type CustomerAddressSubResource in the method declaration and also in the WADL there is a resource element for such a sub resource with full internal description. The second method getAdditionalInfoSubResource() returns only an Object in the method declaration. While this is correct from the JAX-RS perspective as the real returned type can be computed from a request information, it creates a problem for WADL generator because WADL is generated based on the static configuration of the JAX-RS application resources. The WADL generator does not know what type would be actually returned to a request at run time. That is the reason why the nestedresource element with path="additional-info" does not contain any information about the supported resource representations.

The CustomerAddressSubResource sub-resource described in the nested element <resource path="address"> does not contain an OPTIONS method. While these methods are in fact generated by Jersey for the sub-resource, Jersey WADL generator does not currently support adding these methods to the sub-resource description. This should be addressed in the near future. Still, there are two user-defined resource methods handling HTTP GET and PUT requests. The sub-resource methodgetDeliveryAddress() is represented as a separate nested resource with path="sub". Should there be more sub-resource methods defined with path="sub", then all these method descriptions would be placed into the same resource element. In other words, sub-resource methods are grouped in WADL as sub-resources based on their path value.

15.2. Configuration

WADL generation is enabled in Jersey by default. This means that OPTIONS methods are added by default to each resource and an auto-generated /application.wadlresource is deployed too. To override this default behavior and disable WADL generation in Jersey, setup the configuration property in your application:

jersey.config.server.wadl.disableWadl=true

This property can be setup in a web.xml if the Jersey application is deployed in the servlet with web.xml or the property can be returned from the Application.getProperties(). See Deployment chapter for more information on setting the application configuration properties in various deployments.

WADL support in Jersey is implemented via ModelProcessor extension. This implementation enhances the application resource model by adding the WADL providing resources. WADL ModelProcessor priority value is high (i.e. the priority is low) as it should be executed as one of the last model processors. Therefore, anyModelProcessor executed before will not see WADL extensions in the resource model. WADL handling resource model extensions (resources and OPTIONS resource methods) are not added to the application resource model if there is already a matching resource or a resource method detected in the model. In other words, if you define for example your own OPTIONS method that would produce "application.wadl" response content, this method will not be overridden by WADL model processor. SeeResource builder chapter for more information on ModelProcessor extension mechanism.

15.3. Extended WADL support

Please note that the API of extended WADL support is going to be changed in one of the future releases of Jersey 2.x (see below).

Jersey supports extension of WADL generation called extended WADL. Using the extended WADL support you can enhance the generated WADL document with additional information, such as resource method javadoc-based documentation of your REST APIs, adding general documentation, adding external grammar support, or adding any custom WADL extension information.

The documentation of the existing extended WADL can be found here: Extended WADL in Jersey 1. This contains description of an extended WADL generation in Jersey 1.x that is currently supported also by Jersey 2.x.

Again, note that the extended WADL in Jersey 2.x is NOT the intended final version and API is going to be changed. The existing set of features and functionality will be preserved but the APIs will be significantly re-designed to support additional use cases. This impacts mainly the APIs of WadlGeneratorWadlGeneratorConfig as well as any related classes. The API changes may impact your code if you are using a custom WadlGenerator or plan to implement one.

Chapter 16. Bean Validation Support

Validation is a process of verifying that some data obeys one or more pre-defined constraints. This chapter describes support for Bean Validation in Jersey in terms of the needed dependencies, configuration, registration and usage. For more detailed description on how JAX-RS provides native support for validating resource classes based on the Bean Validation refer to the chapter in the JAX-RS spec.

16.1. Bean Validation Dependencies

Bean Validation support in Jersey is provided as an extension module and needs to be mentioned explicitly in your pom.xml file (in case of using Maven):

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-bean-validation</artifactId>
    <version>2.0</version>
</dependency>

Note

If you're not using Maven make sure to have also all the transitive dependencies (see jersey-bean-validation) on the classpath.

This module depends directly on Hibernate Validator which provides a most commonly used implementation of the Bean Validation API spec.

If you want to use a different implementation of the Bean Validation API, use standard Maven mechanisms to exclude Hibernate Validator from the modules dependencies and add a dependency of your own.

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-bean-validation</artifactId>
    <version>2.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </exclusion>
    </exclusions>
</dependency>

16.2. Enabling Bean Validation in Jersey

As stated in Section 4.1, “Auto-Discoverable Features”, Jersey Bean Validation is one of the modules where you don't need to explicitly register it's Features (ValidationFeature) on the server as it's features are automatically discovered and registered when you add the jersey-bean-validation module to your classpath. There are three Jersey specific properties that could disable automatic discovery and registration of Jersey Bean Validation integration module:

Note

Jersey does not support Bean Validation on the client at the moment.

16.3. Configuring Bean Validation Support

Configuration of Bean Validation support in Jersey is twofold - there are few specific properties that affects Jersey behaviour (e.g. sending validation error entities to the client) and then there is ValidationConfig class that configures Validator used for validating resources in JAX-RS application.

To configure Jersey specific behaviour you can use the following properties:

ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK

Disables @ValidateOnExecution check. More on this is described in Section 16.5, “@ValidateOnExecution”.

ServerProperties.BV_SEND_ERROR_IN_RESPONSE

Enables sending validation errors in response entity to the client. More on this in Section 16.7.1, “ValidationError”.

Example 16.1. Configuring Jersey specific properties for Bean Validation.

new ResourceConfig()
    // Now you can expect validation errors to be sent to the client.
    .property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true)
    // @ValidateOnExecution annotations on subclasses won't cause errors.
    .property(ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK, true)
    // Further configuration of ResourceConfig.
    .register( ... );


Customization of the Validator used in validation of resource classes/methods can be done using ValidationConfig class and exposing it via ContextResolver<T>mechanism as shown in Example 16.2, “Using ValidationConfig to configure Validator.”. You can set custom instances for the following interfaces from the Bean Validation API:

Tip

In the latest versions of Jersey, the old-style setter methods (set*) on ValidationConfig are deprecated and replaced with methods that allow the fluent use of the API (e.g. ValidationConfig#messageInterpolator(MessageInterpolator)). Use of the new fluent methods is encouraged as the old setters will be removed from the API soon.

Example 16.2. Using ValidationConfig to configure Validator.

/**
 * Custom configuration of validation. This configuration defines custom:
 * <ul>
 *     <li>ConstraintValidationFactory - so that validators are able to inject Jersey providers/resources.</li>
 *     <li>ParameterNameProvider - if method input parameters are invalid, this class returns actual parameter names
 *     instead of the default ones ({@code arg0, arg1, ..})</li>
 * </ul>
 */
public class ValidationConfigurationContextResolver implements ContextResolver<ValidationConfig> {

    @Context
    private ResourceContext resourceContext;

    @Override
    public ValidationConfig getContext(final Class<?> type) {
        final ValidationConfig config = new ValidationConfig();
        config.setConstraintValidatorFactory(resourceContext.getResource(InjectingConstraintValidatorFactory.class));
        config.setParameterNameProvider(new CustomParameterNameProvider());
        return config;
    }

    /**
     * See ContactCardTest#testAddInvalidContact.
     */
    private class CustomParameterNameProvider implements ParameterNameProvider {

        private final ParameterNameProvider nameProvider;

        public CustomParameterNameProvider() {
            nameProvider = Validation.byDefaultProvider().configure().getDefaultParameterNameProvider();
        }

        @Override
        public List<String> getParameterNames(final Constructor<?> constructor) {
            return nameProvider.getParameterNames(constructor);
        }

        @Override
        public List<String> getParameterNames(final Method method) {
            // See ContactCardTest#testAddInvalidContact.
            if ("addContact".equals(method.getName())) {
                return Arrays.asList("contact");
            }
            return nameProvider.getParameterNames(method);
        }
    }
}

Register this class in your app:

final Application application = new ResourceConfig()
        // Validation.
        .register(ValidationConfigurationContextResolver.class)
        // Further configuration.
        .register( ... );

Note

This code snippet has been taken from Bean Validation example.


16.4. Validating JAX-RS resources and methods

JAX-RS specification states that constraint annotations are allowed in the same locations as the following annotations: @MatrixParam@QueryParam@PathParam,@CookieParam@HeaderParam and @Contextexcept in class constructors and property setters. Specifically, they are allowed in resource method parameters, fields and property getters as well as resource classes, entity parameters and resource methods (return values). Jersey provides support for validation (see following sections) annotated input parameters and return value of the invoked resource method as well as validation of resource class (class constraints, field constraints) where this resource method is placed. Jersey does not support, and doesn't validate, constraints placed on constructors and Bean Validation groups (only Default group is supported at the moment).

16.4.1. Constraint Annotations

The JAX-RS Server API provides support for extracting request values and mapping them into Java fields, properties and parameters using annotations such as@HeaderParam@QueryParam, etc. It also supports mapping of the request entity bodies into Java objects via non-annotated parameters (i.e., parameters without any JAX-RS annotations).

The Bean Validation specification supports the use of constraint annotations as a way of declaratively validating beans, method parameters and method returned values. For example, consider resource class from Example 16.3, “Constraint annotations on input parameters” augmented with constraint annotations.

Example 16.3. Constraint annotations on input parameters

@Path("/")
class MyResourceClass {

    @POST
    @Consumes("application/x-www-form-urlencoded")
    public void registerUser(
            @NotNull @FormParam("firstName") String firstName,
            @NotNull @FormParam("lastName") String lastName,
            @Email @FormParam("email") String email) {
        ...
    }
}


The annotations @NotNull and @Email impose additional constraints on the form parameters firstNamelastName and email. The @NotNull constraint is built-in to the Bean Validation API; the @Email constraint is assumed to be user defined in the example above. These constraint annotations are not restricted to method parameters, they can be used in any location in which JAX-RS binding annotations are allowed with the exception of constructors and property setters.

Rather than using method parameters, the MyResourceClass shown above could have been written as in Example 16.4, “Constraint annotations on fields”.

Example 16.4. Constraint annotations on fields

@Path("/")
class MyResourceClass {

    @NotNull
    @FormParam("firstName")
    private String firstName;

    @NotNull
    @FormParam("lastName")
    private String lastName;

    private String email;

    @FormParam("email")
    public void setEmail(String email) {
        this.email = email;
    }

    @Email
    public String getEmail() {
        return email;
    }

    ...
}


Note that in this version, firstName and lastName are fields initialized via injection and email is a resource class property. Constraint annotations on properties are specified in their corresponding getters.

Constraint annotations are also allowed on resource classes. In addition to annotating fields and properties, an annotation can be defined for the entire class. Let us assume that @NonEmptyNames validates that one of the two name fields in MyResourceClass is provided. Using such an annotation, the example above can be extended to look like Example 16.5, “Constraint annotations on class”

Example 16.5. Constraint annotations on class

@Path("/")
@NonEmptyNames
class MyResourceClass {

    @NotNull
    @FormParam("firstName")
    private String firstName;

    @NotNull
    @FormParam("lastName")
    private String lastName;

    private String email;

    ...
}


Constraint annotations on resource classes are useful for defining cross-field and cross-property constraints.

16.4.2. Annotation constraints and Validators

Annotation constraints and validators are defined in accordance with the Bean Validation specification. The @Email annotation used in Example 16.4, “Constraint annotations on fields” is defined using the Bean Validation @Constraint meta-annotation, see Example 16.6, “Definition of a constraint annotation”.

Example 16.6. Definition of a constraint annotation

@Target({ METHOD, FIELD, PARAMETER })
@Retention(RUNTIME)
@Constraint(validatedBy = EmailValidator.class)
public @interface Email {

    String message() default "{com.example.validation.constraints.email}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}


The @Constraint annotation must include a reference to the validator class that will be used to validate decorated values. The EmailValidator class must implementConstraintValidator<Email, T> where T is the type of values being validated, as described in Example 16.7, “Validator implementation.”.

Example 16.7. Validator implementation.

public class EmailValidator implements ConstraintValidator<Email, String> {

    public void initialize(Email email) {
        ...
    }

    public boolean isValid(String value, ConstraintValidatorContext context) {
        ...
    }
}


Thus, EmailValidator applies to values annotated with @Email that are of type String. Validators for other Java types can be defined for the same constraint annotation.

16.4.3. Entity Validation

Request entity bodies can be mapped to resource method parameters. There are two ways in which these entities can be validated. If the request entity is mapped to a Java bean whose class is decorated with Bean Validation annotations, then validation can be enabled using @Valid as in Example 16.8, “Entity validation”.

Example 16.8. Entity validation

@StandardUser
class User {

    @NotNull
    private String firstName;

    ...
}


@Path("/")
class MyResourceClass {

    @POST
    @Consumes("application/xml")
    public void registerUser(@Valid User user) {
        ...
    }
}


In this case, the validator associated with @StandardUser (as well as those for non-class level constraints like @NotNull) will be called to verify the request entity mapped to user.

Alternatively, a new annotation can be defined and used directly on the resource method parameter (Example 16.9, “Entity validation 2”).

Example 16.9. Entity validation 2

@Path("/")
class MyResourceClass {

    @POST
    @Consumes("application/xml")
    public void registerUser(@PremiumUser User user) {
        ...
    }
}


In the example above, @PremiumUser rather than @StandardUser will be used to validate the request entity. These two ways in which validation of entities can be triggered can also be combined by including @Valid in the list of constraints. The presence of @Valid will trigger validation of all the constraint annotations decorating a Java bean class.

Response entity bodies returned from resource methods can be validated in a similar manner by annotating the resource method itself. To exemplify, assuming both@StandardUser and @PremiumUser are required to be checked before returning a user, the getUser method can be annotated as shown in Example 16.10, “Response entity validation”.

Example 16.10. Response entity validation

@Path("/")
class MyResourceClass {

    @GET
    @Path("{id}")
    @Produces("application/xml")
    @Valid @PremiumUser
    public User getUser(@PathParam("id") String id) {
        User u = findUser(id);
        return u;
    }

    ...
}


Note that @PremiumUser is explicitly listed and @StandardUser is triggered by the presence of the @Valid annotation - see definition of User class earlier in this section.

16.4.4. Annotation Inheritance

The rules for inheritance of constraint annotation are defined in Bean Validation specification. It is worth noting that these rules are incompatible with those defined by JAX-RS. Generally speaking, constraint annotations in Bean Validation are cumulative (can be strengthen) across a given type hierarchy while JAX-RS annotations are inherited or, overridden and ignored.

For Bean Validation annotations Jersey follows the constraint annotation rules defined in the Bean Validation specification.

16.5. @ValidateOnExecution

According to Bean Validation specification, validation is enabled by default only for the so called constrained methods. Getter methods as defined by the Java Beans specification are not constrained methods, so they will not be validated by default. The special annotation @ValidateOnExecution can be used to selectively enable and disable validation. For example, you can enable validation on method getEmail shown in Example 16.11, “Validate getter on execution”.

Example 16.11. Validate getter on execution

@Path("/")
class MyResourceClass {

    @Email
    @ValidateOnExecution
    public String getEmail() {
        return email;
    }

    ...
}


The default value for the type attribute of @ValidateOnExecution is IMPLICIT which results in method getEmail being validated.

Note

According to Bean Validation specification @ValidateOnExecution cannot be overridden once is declared on a method (i.e. in subclass/sub-interface) and in this situations a ValidationException should be raised. This default behaviour can be suppressed by settingServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK property (Jersey specific) to true.

16.6. Injecting

Jersey allows you to inject registered resources/providers into your ConstraintValidator implementation and you can inject ConfigurationValidatorFactory and Validator as required by Bean Validation spec.

Note

Injected ConfigurationValidatorFactory and Validator do not inherit configuration provided by ValidationConfig and need to be configured manually.

Injection of JAX-RS components into ConstraintValidators is supported via a custom ConstraintValidatorFactory provided by Jersey. An example is shown inExample 16.12, “Injecting UriInfo into a ConstraintValidator”.

Example 16.12. Injecting UriInfo into a ConstraintValidator

public class EmailValidator implements ConstraintValidator<Email, String> {

    @Context
    private UriInfo uriInfo;

    public void initialize(Email email) {
        ...
    }

    public boolean isValid(String value, ConstraintValidatorContext context) {
        // Use UriInfo.

        ...
    }
}


Using a custom ConstraintValidatorFactory of your own disables registration of the one provided by Jersey and injection support for resources/providers (if needed) has to be provided by this new implementation. Example 16.13, “Support for injecting Jersey's resources/providers via ConstraintValidatorFactory.” shows how this can be achieved.

Example 16.13. Support for injecting Jersey's resources/providers via ConstraintValidatorFactory.

public class InjectingConstraintValidatorFactory implements ConstraintValidatorFactory {

    @Context
    private ResourceContext resourceContext;

    @Override
    public <T extends ConstraintValidator<?, ?>> T getInstance(final Class<T> key) {
        return resourceContext.getResource(key);
    }

    @Override
    public void releaseInstance(final ConstraintValidator<?, ?> instance) {
        // NOOP
    }
}


Note

This behaviour may likely change in one of the next version of Jersey to remove the need of manually providing support for injecting resources/providers from Jersey in your own ConstraintValidatorFactory implementation code.

16.7. Error Reporting

Bean Validation specification defines a small hierarchy of exceptions (they all inherit from ValidationException) that could be thrown during initialization of validation engine or (for our case more importantly) during validation of input/output values (ConstraintViolationException). If a thrown exception is a subclass of ValidationException exceptConstraintViolationException then this exception is mapped to a HTTP response with status code 500 (Internal Server Error). On the other hand, when aConstraintViolationException is throw two different status code would be returned:

  • 500 (Internal Server Error)

    If the exception was thrown while validating a method return type.

  • 400 (Bad Request)

    Otherwise.

16.7.1. ValidationError

By default, (during mapping ConstraintViolationExceptions) Jersey doesn't return any entities that would include validation errors to the client. This default behaviour could be changed by enabling ServerProperties.BV_SEND_ERROR_IN_RESPONSE property in your application (Example 16.1, “Configuring Jersey specific properties for Bean Validation.”). When this property is enabled then our custom ExceptionMapper<E extends Throwable> (that is handling ValidationExceptions) would transformConstraintViolationException(s) into ValidationError(s) and set this object (collection) as the new response entity which Jersey is able to sent to the client. FourMediaTypes are currently supported when sending ValidationErrors to the client:

  • text/plain

  • text/html

  • application/xml

  • application/json

    Note

    Note: You need to register one of the JSON (JAXB) providers (e.g. MOXy) to marshall validation errors to JSON.

Let's take a look at ValidationError class to see which properties are send to the client:

@XmlRootElement
public final class ValidationError {

    private String message;

    private String messageTemplate;

    private String path;

    private String invalidValue;

    ...
}

The message property is the interpolated error message, messageTemplate represents a non-interpolated error message (or key from your constraint definition e.g.{javax.validation.constraints.NotNull.message}), path contains information about the path in the validated object graph to the property holding invalid value and invalidValue is the string representation of the invalid value itself.

Here are few examples of ValidationError messages sent to client:

Example 16.14. ValidationError to text/plain

HTTP/1.1 500 Internal Server Error
Content-Length: 114
Content-Type: text/plain
Vary: Accept
Server: Jetty(6.1.24)

Contact with given ID does not exist. (path = ContactCardResource.getContact.<return value>, invalidValue = null)


Example 16.15. ValidationError to text/html

HTTP/1.1 500 Internal Server Error
Content-Length: ...
Content-Type: text/plain
Vary: Accept
Server: Jetty(6.1.24)

<div class="validation-errors">
    <div class="validation-error">
        <span class="message">Contact with given ID does not exist.</span>
        (
        <span class="path">
            <strong>path</strong>
            = ContactCardResource.getContact.<return value>
        </span>
        ,
        <span class="invalid-value">
            <strong>invalidValue</strong>
            = null
        </span>
        )
    </div>
</div>


Example 16.16. ValidationError to application/xml

HTTP/1.1 500 Internal Server Error
Content-Length: ...
Content-Type: text/plain
Vary: Accept
Server: Jetty(6.1.24)

<?xml version="1.0" encoding="UTF-8"?>
<validationErrors>
    <validationError>
        <message>Contact with given ID does not exist.</message>
        <messageTemplate>{contact.does.not.exist}</messageTemplate>
        <path>ContactCardResource.getContact.&lt;return value&gt;</path>
    </validationError>
</validationErrors>


Example 16.17. ValidationError to application/json

HTTP/1.1 500 Internal Server Error
Content-Length: 174
Content-Type: application/json
Vary: Accept
Server: Jetty(6.1.24)

[ {
   "message" : "Contact with given ID does not exist.",
   "messageTemplate" : "{contact.does.not.exist}",
   "path" : "ContactCardResource.getContact.<return value>"
} ]


16.8. Example

To see a complete wroking example of using Bean Validation (JSR-349) with Jersey refer to the Bean Validation example.

Chapter 17. MVC Templates

Jersey provides an extension to support the Model-View-Controller (MVC) design pattern. In the context of Jersey components, the Controller from the MVC pattern corresponds to a resource class or method, the View to a template bound to the resource class or method, and the Model to a Java object (or a Java bean) returned from a resource method.

17.1. Dependencies

Jersey MVC templating support is provided by Jersey as a set of (three) extension modules:

  • jersey-mvc

    The base module that provides API and extension SPI for MVC templating support in Jersey. This module is required by any particular MVC templating engine integration module that implements the exposed SPI.

  • jersey-mvc-freemarker

    An integration module with Freemarker-based templating engine. The module provides a custom TemplateProcessor for Freemarker templates and a set of related engine-specific configuration properties.

  • jersey-mvc-jsp

    An integration module for JSP-based templating engine. The module provides a custom TemplateProcessor for JSP templates, custom tag implementation and a set of related engine-specific configuration properties.

Note

In a typical set-up projects using the Jersey MVC templating support would depend on the base module that provides the API and SPI and a single templating engine module for the templating engine of your choice. These modules need to be mentioned explicitly in your pom.xml file.

If you want to use just templating API infrastructure provided by Jersey for the MVC templating support in order to implement your custom support for a templating engine other than the ones provided by Jersey (JSP/Freemarker), you will need to add the base jersey-mvc module into the list of your dependencies:

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-mvc</artifactId>
    <version>2.0</version>
</dependency>

To use one of the templating engines for which Jersey provides the integration implementation (JSP/Freemarker) in your project, you need to add the jersey-mvc-jsp or jersey-mvc-freemarker module to your pom.xml respectively:

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-mvc-jsp</artifactId>
    <version>2.0</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-mvc-freemarker</artifactId>
    <version>2.0</version>
</dependency>

Both of these modules transitively depend on the base jersey-mvc, so it is not necessary to add the base jersey-mvc module explicitly into your dependency list, however it is a recommended Maven practice to do so.

If you are not using Maven you need to make sure to have all required transitive dependencies (see jersey-mvc/jersey-mvc-freemarker/jersey-mvc-jsp) on the classpath.

17.2. Registration and Configuration

To use capabilities of Jersey MVC templating support in your JAX-RS/Jersey application you need to register Features provided by the modules mentioned above. Forjersey-mvc it is MvcFeature, for jersey-mvc-jsp it's JspMvcFeature and for jersey-mvc-freemarker it is FreemarkerMvcFeature.

Note

Both JspMvcFeature and FreemarkerMvcFeature also register MvcFeature so you don't need to register it explicitly when using these JSP/Freemarker modules.

Example 17.1. Registering MvcFeature

new ResourceConfig()
    .register(org.glassfish.jersey.server.mvc.MvcFeature.class)
    // Further configuration of ResourceConfig.
    .register( ... );


Example 17.2. Registering JspMvcFeature

new ResourceConfig()
    .register(org.glassfish.jersey.server.mvc.jsp.JspMvcFeature.class)
    // Further configuration of ResourceConfig.
    .register( ... );


Important

Jersey web applications that want to use MVC templating support feature should be registered as Servlet filters rather than Servlets in the application'sweb.xml. The web.xml-less deployment style introduced in Servlet 3.0 is not supported at the moment for web applications that require use of Jersey MVC templating support.

Each of the three MVC modules contains a *Properties (e.g. FreemarkerMvcProperties) file which defines a set of properties that could be set in a JAX-RSApplication / ResourceConfig in order to take effect, see the Example 17.3, “Setting MvcProperties.TEMPLATE_BASE_PATH value in ResourceConfig andExample 17.4, “Setting FreemarkerMvcProperties.TEMPLATE_BASE_PATH value in web.xml.

Following list contains description of the available properties:

  • MvcProperties.TEMPLATE_BASE_PATH - "jersey.config.server.mvc.templateBasepath"

    The base path where templates are located.

  • FreemarkerMvcProperties.TEMPLATE_BASE_PATH - "jersey.config.server.mvc.templateBasepath.freemarker"

    The base path where Freemarker templates are located.

  • JspMvcProperties.TEMPLATE_BASE_PATH - "jersey.config.server.mvc.templateBasepath.jsp"

    The base path where JSP templates are located.

Example 17.3. Setting MvcProperties.TEMPLATE_BASE_PATH value in ResourceConfig

new ResourceConfig()
    .property(MvcProperties.TEMPLATE_BASE_PATH, "templates")
    .register(MvcFeature.class)
    // Further configuration of ResourceConfig.
    .register( ... );


Example 17.4. Setting FreemarkerMvcProperties.TEMPLATE_BASE_PATH value in web.xml

<servlet>
    <servlet-name>org.glassfish.jersey.examples.freemarker.MyApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>org.glassfish.jersey.examples.freemarker.MyApplication</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.mvc.templateBasePath.freemarker</param-name>
        <param-value>freemarker</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


17.3. Explicit vs. Implicit View Templates

Note

Some of the passages/examples from this and the next section was taken from MVCJ blog article written by Paul Sandoz earlier.

In Jersey 2.0, the base MVC API (excluding the SPI part) consists of two classes (in the org.glassfish.jersey.server.mvc package in base MVC module) that we will explore in more detail now, namely Viewable and @Template. These classes determines which approach (explicit/implicit) you would be taking when working with Jersey MVC templating support.

17.3.1. Viewable - Explicit View Templates

In this approach a resource method explicitly returns a reference to a view template and the data model to be used. For this purpose the Viewable class has been introduced in Jersey 1 and is also present (under a different package) in Jersey 2. A simple example of usage can be seen in Example 17.5, “Using Viewable in a resource class”.

Example 17.5. Using Viewable in a resource class

package com.foo;

@Path("foo")
public class Foo {

    @GET
    public Viewable get() {
        return new Viewable("index", "FOO");
    }
}


In this example, the Foo JAX-RS resource class is the controller and the Viewable instance encapsulates the provided data model ("FOO" string) and a named reference to the associated view template ("index").

The template name reference "index" is a relative value that Jersey will resolve to its absolute template reference using the fully qualified class name of Foo (more on resolving relative template name to the absolute one can be found in the JavaDoc of Viewable class), which, in our case, is:

"/com/foo/Foo/index"

Jersey will then search all the registered template processors (see Section 17.5, “Custom Templating Engines”) to find a template processor that can resolve the absolute template reference further to a "processable" template reference. If a template processor is found then the "processable" template is processed using the supplied data model.

Let's change the resource GET method in our Foo resource a little:

Example 17.6. Using absolute path to template in Viewable

@GET
public Viewable get() {
    return new Viewable("/index", "FOO");
}


In this case, since the template reference begins with "/", Jersey will consider the reference to be absolute already and will not attempt to absolutize it again. The reference will be used "as is" when resolving it to a "processable" template reference as described earlier.

Tip

All HTTP methods may return Viewable instances. Thus a POST method may return a template reference to a template that produces a view that is the result of processing an HTML Form.

17.3.2. @Template - Implicit View Templates

17.3.2.1. Resource classes

A resource class can have templates implicitly associated with it via @Template annotation. For example, take a look at the resource class listing in Example 17.7, “Using@Template on a resource class”.

Example 17.7. Using @Template on a resource class

@Path("foo")
@Template
public class Foo {

    public String getFoo() {
        return "FOO";
    }
}


The example above uses a lot of conventions and requires some more explanation. First of all, you may have noticed that there is no resource method defined in this JAX-RS resource. Also, there is no template reference defined. In this case, since the @Template annotation placed on the resource class does not contain any information, the default relative template reference "index" will be used. Later it will get resolved to an absolute "/com/foo/Foo/index" template reference. As for the missing resource methods, a default @GET method will be implicitly generated by Jersey for the Foo resource (our MVC Controller). The implementation of the implicitly added resource method performs the equivalent of the following explicit resource method:

@GET
public Viewable get() {
    return new Viewable("index", this);
}

As you can see, the resource class serves in this case also as a model. Producible media types are determined based on the @Produces annotation declared on the resource class, if any.

Note

In case of a resource class-based implicit MVC view template, the controller is also the model. In this case the template reference "index" is special, it is the template reference associated with the controller itself.

Implicit sub-resource templates are also supported, for example, for a template reference "bar" that resolves to an absolute template reference "/com/foo/Foo/bar"that in turn resolves to a processable template reference. Following @GET method is also implicitly added to the Foo controller that performs the equivalent of the following explicit sub-resource method:

@GET
                        @Path("{implicit-view-path-parameter}")
                        public Viewable get(@PathParameter("{implicit-view-path-parameter}") String template) {
                        return new Viewable(template, this);
                        }

In other words, a HTTP GET request to a "/foo/bar" would be handled by this auto-generated method in the Foo resource and would delegate the request to a registered template processor supports processing of the absolute template reference "/com/foo/Foo/bar", while the model is still an instance of the JAX-RS resource class Foo.

17.3.2.2. Resource methods

In case a resource method is annotated with @Template annotation then the return value of the method defines the MVC model part. The processing of such a method is then essentially the same as if the return type of the method was an instance of the Viewable class. If a method is annotated with @Template and is also returning aViewable instance then the values (resolvingClass) from the Viewable instance take precedence over those defined in the annotation. Producible media types are determined from the method's @Produces annotation.

Note

Implicit view templates support works dynamically (as is the case for explicit MVC) so it is possible (if the deployment system is configured correctly) to add or modify templates while the application is running.

17.4. JSP

As stated earlier, Jersey provides support for JSP templates in jersey-mvc-jsp extension module. There is a JSP template processor that resolves absolute template references to processable template references represented as JSP pages as follows:

Procedure 17.1. Resolving JSP processable template reference

  1. if the absolute template reference does not end in ".jsp" append this suffix to the reference; and

  2. if Servlet.getResource returns a non-null value for the appended reference then return the appended reference as the processable template reference otherwise return null (to indicate the absolute reference has not been resolved by the JSP template processor).

Thus the absolute template reference "/com/foo/Foo/index" would be resolved to "/com/foo/Foo/index.jsp", provided there exists a"/com/foo/Foo/index.jsp" JSP page in the web application.

Jersey will assign the model instance to the attribute named "it". So in the case of the implicit example it is possible to referece the foo property on the Foo resource from the JSP template as follows:

<h1>${it.foo}</h1>

17.5. Custom Templating Engines

To add support for other (custom) templating engines into Jersey MVC Templating facility, you need to implement the TemplateProcessor and register this class into your application.

Tip

When writing template processors it is recommend that you use an appropriate unique suffix for the processable template references. In such case it is then possible to easily support mixing of multiple templating engines in a single application without any conflicts.

Example 17.8. Custom TemplateProcessor

@Provider
class MyTemplateProcessor implements TemplateProcessor<String> {

    @Override
    public String resolve(String path, final MediaType mediaType) {
        final String extension = ".testp";

        if (!path.endsWith(extension)) {
            path = path + extension;
        }

        final URL u = this.getClass().getResource(path);
        return u == null ? null : path;
    }

    @Override
    public void writeTo(String templateReference,
                        Viewable viewable,
                        MediaType mediaType,
                        OutputStream out) throws IOException {
        final PrintStream ps = new PrintStream(out);
        ps.print("path=");
        ps.print(templateReference);
        ps.println();
        ps.print("model=");
        ps.print(viewable.getModel().toString());
        ps.println();
    }

}


Example 17.9. Registering custom TemplateProcessor

new ResourceConfig()
    .register(MyTemplateProcessor.class)
    // Further configuration of ResourceConfig.
    .register( ... );


17.6. Other Examples

To see an example of MVC (JSP) templating support in Jersey refer to the MVC (Bookstore) example.

Chapter 18. Jersey Test Framework

Jersey Test Framework originated as an internal tool used for verifying the correct implementation of server-side components. Testing RESTful applications became a more pressing issue with "modern" approaches like test-driven development and users started to look for a tool that could help with designing and running the tests as fast as possible but with many options related to test execution environment.

Current implementation of Jersey Test Framework supports the following set of features:

  • pre-configured client to access deployed application

  • support for multiple containers - grizzly, in-memory, jdk, simple

  • able to run against any external container

  • automated configurable traffic logging

Jersey Test Framework is based on JUnit and works almost out-of-the box. It is easy to integrate it within your Maven-based project. While it is usable on all environments where you can run JUnit, we support primarily the Maven-based setups.

18.1. Basics

public class SimpleTest extends JerseyTest {

    @Path("hello")
    public static class HelloResource {
        @GET
        public String getHello() {
            return "Hello World!";
        }
    }

    @Override
    protected Application configure() {
        return new ResourceConfig(HelloResource.class);
    }

    @Test
    public void test() {
        final String hello = target("hello").request().get(String.class);
        assertEquals("Hello World!", hello);
    }
}

If you want to develop a test using Jersey Test Framework, you need to subclass JerseyTest and configure the set of resources and/or providers that will be deployed as part of the test application. This short code snippet shows basic resource class HelloResource used in tests defined as part of the SimpleTest class. The overriddenconfigure method returns a ResourceConfig of the test application,that contains only the HelloResource resource class. ResourceConfig is a sub-class of JAX-RSApplication. It is a Jersey convenience class for configuring JAX-RS applications. ResourceConfig also implements JAX-RS Configurable interface to make the application configuration more flexible.

18.2. Supported Containers

JerseyTest supports deploying applications on various containers, all (except the external container wrapper) need to have some "glue" code to be supported. Currently Jersey Test Framework provides support for Grizzly, In-Memory, JDK (com.sun.net.httpserver.HttpServer) and Simple HTTP container (org.simpleframework.http).

A test container is selected based on various inputs. JerseyTest#getTestContainerFactory() is always executed, so if you override it and provide your own version ofTestContainerFactory, nothing else will be considered. Setting a system variable TestProperties#CONTAINER_FACTORY has similar effect. This way you may defer the decision on which containers you want to run your tests from the compile time to the test execution time. Default implementation of TestContainerFactory looks for container factories on classpath. If more than one instance is found and there is a Grizzly test container factory among them, it will be used; if not, a warning will be logged and the first found factory will be instantiated.

Following is a brief description of all containers supported in Jersey Test Framework.

  • Grizzly container can run as a light-weight, plain HTTP container. Almost all Jersey tests are using Grizzly by default.

    <dependency>
        <groupId>org.glassfish.jersey.test-framework.providers</groupId>
        <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
        <version>2.0</version>
    </dependency>

  • In-Memory container is not a real container. It starts Jersey application and directly calls internal APIs to handle request created by client provided by test framework. There is no network communication involved. This containers does not support servlet and other container dependent features, but it is a perfect choice for simple unit tests.

    <dependency>
        <groupId>org.glassfish.jersey.test-framework.providers</groupId>
        <artifactId>jersey-test-framework-provider-inmemory</artifactId>
        <version>2.0</version>
    </dependency>

  • HttpServer from Oracle JDK is another supported test container.

    <dependency>
        <groupId>org.glassfish.jersey.test-framework.providers</groupId>
        <artifactId>jersey-test-framework-provider-jdk-http</artifactId>
        <version>2.0</version>
    </dependency>

  • Simple container (org.simpleframework.http) is another light-weight HTTP container that integrates with Jersey and is supported by Jersey Test Framework.

    <dependency>
        <groupId>org.glassfish.jersey.test-framework.providers</groupId>
        <artifactId>jersey-test-framework-provider-simple</artifactId>
        <version>2.0</version>
    </dependency>

18.3. Advanced features

18.3.1. JerseyTest Features

JerseyTest provide enable(...)forceEnable(...) and disable(...) methods, that give you control over configuring values of the properties defined and described in theTestProperties class. A typical code that overrides the default property values is listed bellow:

public class SimpleTest extends JerseyTest {
    // ...

    @Override
    protected Application configure() {
        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);

        // ...

    }
}

The code in the example above enables test traffic logging (inbound and outbound headers) as well as dumping the HTTP message entity as part of the traffic logging.

18.3.2. External container

Complicated test scenarios may require fully started containers with complex setup configuration, that is not easily doable with current Jersey container support. To address these use cases, Jersey Test Framework providers general fallback mechanism - an External Test Container Factory. Support of this external container "wrapper" is provided as the following module:

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-external</artifactId>
    <version>2.0</version>
</dependency>

As indicated, the "container" exposed by this module is just a wrapper or stub, that redirects all request to a configured host and port. Writing tests for this container is same as for any other but you have to provide the information about host and port during the test execution:

mvn test -Djersey.test.host=myhost.org -Djersey.config.test.container.port=8080

18.3.3. Test Client configuration

Tests might require some advanced client configuration. This is possible by overriding configureClient(ClientConfig clientConfig) method. Typical use case for this is registering more providers, such as MessageBodyReader<T>s or MessageBodyWriter<T>s, or enabling additional features.

18.3.4. Accessing the logged test records programmatically

Sometimes you might need to check a logged message as part of your test assertions. For this purpose Jersey Test Framework provides convenient access to the logged records via JerseyTest#getLastLoggedRecord() and JerseyTest#getLoggedRecords() methods. Note that this feature is not enabled by default, seeTestProperties#RECORD_LOG_LEVEL for more information.

Chapter 19. Building and Testing Jersey

19.1. Checking Out the Source

Jersey source code is available on GitHub. You can browse the sources at https://github.com/jersey/jersey.

In case you are not familiar with Git, we recommend reading some of the many "Getting Started with Git" articles you can find on the web. For example this DZone RefCard.

To clone the Jersey repository you can execute the following command on the command-line (provided you have a command-line Git client installed on your machine):

git clone git://github.com/jersey/jersey.git

This creates read-only copy of Jersey workspace. If you want to contribute, please use "pull request": https://help.github.com/articles/creating-a-pull-request.

Milestones and releases of Jersey are tagged. You can list the tags by executing the standard Git command in the repository directory:

git tag -l

or by visiting https://github.com/jersey/jersey/tags.

19.2. Building the Source

Jersey source code requires Java SE 6 or greater. The build is based on Maven. Maven 3 or greater is highly recommended. Also it is recommended you use the following Maven options when building the workspace (can be set in MAVEN_OPTS environment variable):

-Xmx1048m -XX:PermSize=64M -XX:MaxPermSize=128M

It is recommended to build all of Jersey after you cloned the source code repository. To do that execute the following commands in the directory where jersey source repository was cloned (typically the directory named "jersey"):

mvn -Dmaven.test.skip=true clean install

This command will build Jersey, but skip the test execution. If you don't want to skip the tests, execute the following instead:

mvn clean install

Building the whole Jersey project including tests could take significant amount of time.

19.3. Testing

Jersey contains many tests. Unit tests are in the individual Jersey modules, integration and end-to-end tests are in jersey/tests/e2e directory. You can run tests related to a particular area using the following command:

mvn -Dtest=<pattern> test

where pattern may be a comma separated set of names matching tests classes or individual methods (like LinkTest#testDelimiters).

19.4. Using NetBeans

NetBeans IDE has excellent maven support. The Jersey maven modules can be loaded, built and tested in NetBeans without any additional NetBeans-specific project files.

Chapter 20. Migrating from Jersey 1.x

This chapter is a migration guide for people switching from Jersey 1.x. Since many of the Jersey 1.x features became part of JAX-RS 2.0 standard which caused changes in the package names, we decided it is a good time to do a more significant incompatible refactoring, which will allow us to introduce some more interesting new features in the future. As the result, there are many incompatiblities between Jersey 1.x and Jersey 2.0. This chapter summarizes how to migrate the concepts found in Jersey 1.x to Jersey/JAX-RS 2.0 concepts.

20.1. Server API

Jersey 1.x contains number of proprietary server APIs. This section covers migration of application code relying on those APIs.

20.1.1. Injecting custom objects

Jersey 1.x have its own internal dependency injection framework which handles injecting various parameters into field or methods. It also provides a way how to register custom injection provider in Singleton or PerRequest scopes. Jersey 2.x uses HK2 as dependency injection framework and users are also able to register custom classes or instances to be injected in various scopes.

Main difference in Jersey 2.x is that you don't need to create special classes or providers for this task; everything should be achievable using HK2 API. Custom injectables can be registered at ResourceConfig level by adding new HK2 Module or by dynamically adding binding almost anywhere using injected HK2 Services instance.

Jersey 1.x Singleton:

ResourceConfig resourceConfig = new DefaultResourceConfig();
resourceConfig.getSingletons().add(
        new SingletonTypeInjectableProvider<Context, SingletonType>(
                SingletonType.class, new SingletonType()) {});
                

Jersey 1.x PerRequest:

ResourceConfig resourceConfig = new DefaultResourceConfig();
resourceConfig.getSingletons().add(
        new PerRequestTypeInjectableProvider<Context, PerRequestType>() {
            @Override
            public Injectable<PerRequestType> getInjectable(ComponentContext ic, Context context) {
                //...
            }
        });

Jersey 2.0 HK2 Module:

public static class MyBinder extends AbstractBinder {

    @Override
    protected void configure() {
        // request scope binding
        bind(MyInjectablePerRequest.class).to(MyInjectablePerRequest.class).in(RequestScope.class);
        // singleton binding
        bind(MyInjectableSingleton.class).in(Singleton.class);
        // singleton instance binding
        bind(new MyInjectableSingleton()).to(MyInjectableSingleton.class);
    }

}

// register module to ResourceConfig (can be done also in constructor)
ResourceConfig rc = new ResourceConfig();
rc.addClasses(/* ... */);
rc.addBinders(new MyBinder());

Jersey 2.0 dynamic binding:

public static class MyApplication extends Application {

    @Inject
    public MyApplication(ServiceLocator serviceLocator) {
        System.out.println("Registering injectables...");

        DynamicConfiguration dc = Injections.getConfiguration(serviceLocator);

        // request scope binding
        Injections.addBinding(
        Injections.newBinder(MyInjectablePerRequest.class).to(MyInjectablePerRequest.class).in(RequestScoped.class),
                dc);

        // singleton binding
        Injections.addBinding(
                Injections.newBinder(MyInjectableSingleton.class)
                        .to(MyInjectableSingleton.class)
                        .in(Singleton.class),
                dc);

        // singleton instance binding
        Injections.addBinding(
                Injections.newBinder(new MyInjectableSingleton())
                        .to(MyInjectableSingleton.class),
                dc);

        // request scope binding with specified custom annotation
        Injections.addBinding(
                Injections.newBinder(MyInjectablePerRequest.class)
                        .to(MyInjectablePerRequest.class)
                        .qualifiedBy(new MyAnnotationImpl())
                        .in(RequestScoped.class),
                dc);

        // commits changes
        dc.commit();
    }

    @Override
    public Set<Class<?>> getClasses() {
        return ...
    }}

20.1.2. ResourceConfig Reload

In Jersey 1, the reload functionality is based on two interfaces:

  1. com.sun.jersey.spi.container.ContainerListener
  2. com.sun.jersey.spi.container.ContainerNotifier

Containers, which support the reload functionality implement the ContainerListener interface, so that once you get access to the actual container instance, you could call it's onReload method and get the container re-load the config. The second interface helps you to obtain the actual container instance reference. An example on how things are wired together follows.

Example 20.1. Jersey 1 reloader implementation

public class Reloader implements ContainerNotifier {
    List<ContainerListener> ls;

    public Reloader() {
        ls = new ArrayList<ContainerListener>();
    }

    public void addListener(ContainerListener l) {
        ls.add(l);
    }

    public void reload() {
        for (ContainerListener l : ls) {
            l.onReload();
        }
    }
}


Example 20.2. Jersey 1 reloader registration

Reloader reloader = new Reloader();
resourceConfig.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_NOTIFIER, reloader);


In Jersey 2, two interfaces are involved again, but these have been re-designed.

  1. org.glassfish.jersey.server.spi.Container
  2. org.glassfish.jersey.server.spi.ContainerLifecycleListener

The Container interface introduces two reload methods, which you can call to get the application re-loaded. One of these methods allows to pass in a newResourceConfig instance. You can register your implementation of ContainerLifecycleListener the same way as any other provider (i.e. either by annotating it by@Provider annotation or adding it to the Jersey ResourceConfig directly either using the class (using ResourceConfig.addClasses()) or registering a particular instance using ResourceConfig.addSingletons() method.

An example on how things work in Jersey 2 follows.

Example 20.3. Jersey 2 reloader implementation

public class Reloader implements ContainerLifecycleListener {

    Container container;

    public void reload(ResourceConfig newConfig) {
        container.reload(newConfig);
    }

    public void reload() {
        container.reload();
    }

    @Override
    public void onStartup(Container container) {
        this.container = container;
    }

    @Override
    public void onReload(Container container) {
        // ignore or do whatever you want after reload has been done
    }

    @Override
    public void onShutdown(Container container) {
        // ignore or do something after the container has been shutdown
    }
}


Example 20.4. Jersey 2 reloader registration

Reloader reloader = new Reloader();
resourceConfig.addSingletons(reloader);
                    


20.1.3. MessageBodyReaders and MessageBodyWriters ordering

JAX-RS 2.0 defines new order of MessageBodyWorkers - whole set is sorted by declaration distance, media type and source (custom providers have smaller priority than Jersey provided). JAX-RS 1.x ordering can still be forced by setting parameter MessageProperties.LEGACY_WORKERS_ORDERING("jersey.config.workers.legacyOrdering") to true in ResourceConfig or ClientConfig properties.

20.2. Migrating Jersey Client API

JAX-RS 2.0 provides functionality that is equivalent to the Jersey 1.x proprietary client API. Here is a rough mapping between the Jersey 1.x and JAX-RS 2.0 Client API classes:

Table 20.1. Mapping of Jersey 1.x to JAX-RS 2.0 client classes

Jersey 1.x Class JAX-RS 2.0 Class Notes
com.sun.jersey.api.client.Client ClientBuilder For the static factory methods and constructors.
  Client For the instance methods.
com.sun.jersey.api.client.WebResource WebTarget  
com.sun.jersey.api.client.AsyncWebResource WebTarget You can access async versions of the async methods by calling WebTarget.request().async()

The following sub-sections show code examples.

20.2.1. Making a simple client request

Jersey 1.x way:

Client client = Client.create();
WebResource webResource = client.resource(restURL).path("myresource/{param}");
String result = webResource.pathParam("param", "value").get(String.class);

JAX-RS 2.0 way:

Client client = ClientFactory.newClient();
WebTarget target = client.target(restURL).path("myresource/{param}");
String result = target.pathParam("param", "value").get(String.class);

20.2.2. Registering filters

Jersey 1.x way:

Client client = Client.create();
WebResource webResource = client.resource(restURL);
webResource.addFilter(new HTTPBasicAuthFilter(username, password));

JAX-RS 2.0 way:

Client client = ClientFactory.newClient();
WebTarget target = client.target(restURL);
target.register(new HttpBasicAuthFilter(username, password));

20.2.3. Setting "Accept" header

Jersey 1.x way:

Client client = Client.create();
WebResource webResource = client.resource(restURL).accept("text/plain");
ClientResponse response = webResource.get(ClientResponse.class);

JAX-RS 2.0 way:

Client client = ClientFactory.newClient();
WebTarget target = client.target(restURL);
Response response = target.request("text/plain").get();

20.2.4. Attaching entity to request

Jersey 1.x way:

Client client = Client.create();
WebResource webResource = client.resource(restURL);
ClientResponse response = webResource.post(ClientResponse.class, "payload");

JAX-RS 2.0 way:

Client client = ClientFactory.newClient();
WebTarget target = client.target(restURL);
Response response = target.request().post(Entity.text("payload"));

20.2.5. Setting SSLContext and/or HostnameVerifier

Jersey 1.x way:

HTTPSProperties prop = new HTTPSProperties(hostnameVerifier, sslContext);
DefaultClientConfig dcc = new DefaultClientConfig();
dcc.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, prop);
Client client = Client.create(dcc);

Jersey 2.0 way:

Client client = ClientBuilder.newBuilder()
        .sslContext(sslContext)
        .hostnameVerifier(hostnameVerifier)
        .build();
                

Appendix A. Configuration Properties

A.1. Common (client/server) configuration properties

List of common configuration properties that can be found in CommonProperties class. All of these properties can be overridden by their server/client counterparts.

Table A.1. List of common configuration properties

Constant Value Description
CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE jersey.config.disableAutoDiscovery

Disables feature auto discovery globally on client/server. Default value is false.

CommonProperties.JSON_PROCESSING_FEATURE_DISABLE jersey.config.disableJsonProcessing

Disables configuration of Json Processing (JSR-353) feature. Default value is false.

CommonProperties.MOXY_JSON_FEATURE_DISABLE jersey.config.disableMoxyJson

Disables configuration of MOXy Json feature. Default value is false.

CommonProperties.OUTBOUND_CONTENT_LENGTH_BUFFER jersey.config.contentLength.buffer

An integer value that defines the buffer size used to buffer the outbound message entity in order to determine its size and set the value of HTTPContent-Length header. Default value is8192.


A.2. Server configuration properties

List of server configuration properties that can be found in ServerProperties class.

Table A.2. List of server configuration properties

Constant Value Description
  jersey.config.contentLength.buffer.server

An integer value that defines the buffer size used to buffer the outbound message entity in order to determine its size and set the value of HTTPContent-Length header. Default value is 8192.

ServerProperties.BV_FEATURE_DISABLE jersey.config.beanValidation.disable.server

Disables Bean Validation support. Default value isfalse.

ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK jersey.config.beanValidation.disable.validateOnExecutableCheck.server

Disables@ValidateOnExecutioncheck. Default value isfalse.

ServerProperties.BV_SEND_ERROR_IN_RESPONSE jersey.config.beanValidation.enableOutputValidationErrorEntity.server

Enables sending validation error information to the client. Default value isfalse.

ServerProperties.FEATURE_AUTO_DISCOVERY_DISABLE jersey.config.disableAutoDiscovery.server

Disables feature auto discovery on server. Default value is false.

ServerProperties.HTTP_METHOD_OVERRIDE jersey.config.server.httpMethodOverride

Defines configuration of HTTP method overriding. This property is used byHttpMethodOverrideFilter to determine where it should look for method override information (e.g. request header or query parameters).

ServerProperties.JSON_PROCESSING_FEATURE_DISABLE jersey.config.disableJsonProcessing.server

Disables configuration of Json Processing (JSR-353) feature. Default value isfalse.

ServerProperties.LANGUAGE_MAPPINGS jersey.config.server.languageMappings

Defines mapping of URI extensions to languages. The property is used byUriConnegFilter.

ServerProperties.MEDIA_TYPE_MAPPINGS jersey.config.server.mediaTypeMappings

Defines mapping of URI extensions to media types. The property is used byUriConnegFilter.

ServerProperties.MOXY_JSON_FEATURE_DISABLE jersey.config.disableMoxyJson.server

Disables configuration of MOXy Json feature. Default value is false.

ServerProperties.PROVIDER_CLASSNAMES jersey.config.server.provider.classnames

Defines one or more class names that implement application-specific resources and providers. If the property is set, the specified classes will be instantiated and registered as either application JAX-RS root resources or providers.

ServerProperties.PROVIDER_CLASSPATH jersey.config.server.provider.classpath

Defines class-path that contains application-specific resources and providers. If the property is set, the specified packages will be scanned for JAX-RS root resources and providers.

ServerProperties.PROVIDER_PACKAGES jersey.config.server.provider.packages

Defines one or more packages that contain application-specific resources and providers. If the property is set, the specified packages will be scanned for JAX-RS root resources and providers.

ServerProperties.PROVIDER_SCANNING_RECURSIVE jersey.config.server.provider.scanning.recursive

Sets the recursion strategy for package scanning. Default value is true.

ServerProperties.RESOURCE_VALIDATION_DISABLE jersey.config.server.resource.validation.disable

Disables Resourcevalidation. Default value isfalse.

ServerProperties.RESOURCE_VALIDATION_IGNORE_ERRORS jersey.config.server.resource.validation.ignoreErrors

Determines whether validation of application resource models should fail even in case of a fatal validation errors. Default value is false.

ServerProperties.WADL_FEATURE_DISABLE jersey.config.server.wadl.disableWadl

Disables WADL generation. Default value is false.

ServerProperties.WADL_GENERATOR_CONFIG jersey.config.server.wadl.generatorConfig

Defines the wadl generator configuration that provides a WadlGenerator.


A.3. Client configuration properties

List of client configuration properties that can be found in ClientProperties class.

Table A.3. List of client configuration properties

Constant Value Description
  jersey.config.contentLength.buffer.client

An integer value that defines the buffer size used to buffer the outbound message entity in order to determine its size and set the value of HTTPContent-Lengthheader. Default value is8192.

ClientProperties.ASYNC_THREADPOOL_SIZE jersey.config.client.async.threadPoolSize

Asynchronous thread pool size. Default value is not set. NOT SUPPORTED.

ClientProperties.BUFFER_RESPONSE_ENTITY_ON_EXCEPTION jersey.config.client.bufferResponseEntityOnException

Automatic response buffering in case of an exception. Default value is trueNOT SUPPORTED.

ClientProperties.CHUNKED_ENCODING_SIZE jersey.config.client.chunkedEncodingSize

Chunked encoding size. Default value is not set. NOT SUPPORTED.

ClientProperties.CONNECT_TIMEOUT jersey.config.client.connectTimeout

Read timeout interval, in milliseconds. Default value is 0 (infinity).

ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE jersey.config.disableAutoDiscovery.client

Disables feature auto discovery on client. Default value is false.

ClientProperties.FOLLOW_REDIRECTS jersey.config.client.followRedirects

Declares that the client will automatically redirect to the URI declared in 3xx responses. Default value is true.

ClientProperties.HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND jersey.config.client.httpUrlConnection.setMethodWorkaround

Declares that the client will try to set unsupported HTTP method toHttpURLConnectionvia reflection. Default value is false.

ClientProperties.JSON_PROCESSING_FEATURE_DISABLE jersey.config.disableJsonProcessing.client

Disables configuration of Json Processing (JSR-353) feature. Default value is false.

ClientProperties.MOXY_JSON_FEATURE_DISABLE jersey.config.disableMoxyJson.client

Disables configuration of MOXy Json feature. Default value is false.

ClientProperties.READ_TIMEOUT jersey.config.client.readTimeout

Read timeout interval, in milliseconds. Default value is 0 (infinity).

ClientProperties.USE_ENCODING jersey.config.client.useEncoding

Indicates the value ofContent-Encodingproperty theEncodingFilter should be adding. Default value is not set.


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Android提供了一种用于标识和定位资源的URI(统一资源标识符)路径URI路径是一种表示资源位置的字符串,它可以用于访问和操作各种类型的数据和内容。 在Android开发中,URI路径通常用于访问和操作应用程序内部的各种资源。这些资源可能包括图片、视频、音频、文档等。通过使用URI路径,我们可以轻松地访问这些资源并进行相应的操作。 Android的URI路径具有以下几个常见的特点: 1. 格式:URI路径由四个部分组成,包括协议、主机、路径和查询参数。例如:content://com.example.app/files/image.jpg。其中,content://是协议,com.example.app是主机,/files/image.jpg是路径。 2. 权限:访问URI路径中的某些资源可能需要特定的权限。例如,访问联系人列表需要READ_CONTACTS权限。在使用URI路径获取资源时,我们需要确保已经获取了相应的权限。 3. 操作:URI路径可以用于各种操作,如读取、写入、删除、查询等。根据具体的使用场景和需求,我们可以使用不同的URI路径来执行相应的操作。 4. 内容提供者:在许多情况下,我们需要通过内容提供者来访问和操作应用程序中的数据。内容提供者是一种用于在应用程序之间共享数据的机制,它通过URI路径提供对数据的访问。 总之,Android的URI路径是一种用于标识和定位资源的字符串表示形式。通过使用URI路径,我们可以方便地访问和操作应用程序内部的各种资源。同时,我们还需要注意相应的权限和操作方式,以确保能够正确地获取和处理资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值