Resteasy Reference Guide En US
User Manual:
Open the PDF directly: View PDF .Page Count: 346
RESTEasy JAX-RS
RESTFul Web Services for Java
3.6.2.Final
Preface ............................................................................................................................. ix
1. Overview ...................................................................................................................... 1
2. License ........................................................................................................................ 3
3. Installation/Configuration ............................................................................................ 5
3.1. RESTEasy modules in WildFly ............................................................................ 5
3.1.1. Other RESTEasy modules ........................................................................ 7
3.1.2. Upgrading RESTEasy within WildFly ......................................................... 7
3.2. Deploying a RESTEasy application to WildFly ...................................................... 7
3.3. Deploying to other servlet containers ................................................................... 8
3.3.1. Servlet 3.0 containers .............................................................................. 9
3.3.2. Older servlet containers ............................................................................ 9
3.4. Configuration switches ...................................................................................... 10
3.5. javax.ws.rs.core.Application ............................................................................... 14
3.6. RESTEasy as a ServletContextListener .............................................................. 15
3.7. RESTEasy as a Servlet Filter ............................................................................ 16
3.8. Client side ........................................................................................................ 16
4. Using @Path and @GET, @POST, etc. ...................................................................... 19
4.1. @Path and regular expression mappings ...........................................................
4.2. JAX-RS 2.0 Matching Algorithm .........................................................................
5. @PathParam ..............................................................................................................
5.1. Advanced @PathParam and Regular Expressions ..............................................
5.2. @PathParam and PathSegment ........................................................................
6. @QueryParam ............................................................................................................
7. @HeaderParam ..........................................................................................................
8. Linking resources ......................................................................................................
8.1. Link Headers ....................................................................................................
8.2. Atom links in the resource representations .........................................................
8.2.1. Configuration ..........................................................................................
8.2.2. Your first links injected ...........................................................................
8.2.3. Customising how the Atom links are serialised .........................................
8.2.4. Specifying which JAX-RS methods are tied to which resources ..................
8.2.5. Specifying path parameter values for URI templates .................................
8.2.6. Securing entities ....................................................................................
8.2.7. Extending the UEL context .....................................................................
8.2.8. Resource facades ..................................................................................
9. @MatrixParam ............................................................................................................
10. @CookieParam ........................................................................................................
11. @FormParam ...........................................................................................................
12. @Form .....................................................................................................................
13. Improved @…Param annotations ............................................................................
14. @DefaultValue ..........................................................................................................
15. @Encoded and encoding .........................................................................................
16. @Context .................................................................................................................
17. JAX-RS Resource Locators and Sub Resources .....................................................
20
21
23
24
24
27
29
31
31
31
31
31
34
34
35
38
38
40
43
45
47
49
53
55
57
59
61
iii
RESTEasy JAX-RS
18. Resources metadata configuration .......................................................................... 65
19. JAX-RS Content Negotiation .................................................................................... 69
19.1. URL-based negotiation ....................................................................................
19.2. Query String Parameter-based negotiation ........................................................
20. Content Marshalling/Providers .................................................................................
20.1. Default Providers and default JAX-RS Content Marshalling ................................
20.2. Content Marshalling with @Provider classes .....................................................
20.3. Providers Utility Class .....................................................................................
20.4. Configuring Document Marshalling ...................................................................
20.5. Text media types and character sets ................................................................
21. JAXB providers ........................................................................................................
21.1. JAXB Decorators ............................................................................................
21.2. Pluggable JAXBContext's with ContextResolvers ..............................................
21.3. JAXB + XML provider ......................................................................................
21.3.1. @XmlHeader and @Stylesheet .............................................................
21.4. JAXB + JSON provider ....................................................................................
21.5. JAXB + FastinfoSet provider ............................................................................
22.
23.
24.
25.
iv
70
71
73
73
74
75
78
79
81
82
83
84
84
86
90
21.6. Arrays and Collections of JAXB Objects ........................................................... 90
21.6.1. Retrieving Collections on the client side ................................................. 93
21.6.2. JSON and JAXB Collections/arrays ....................................................... 94
21.7. Maps of JAXB Objects .................................................................................... 95
21.7.1. Retrieving Maps on the client side ......................................................... 97
21.7.2. JSON and JAXB maps ......................................................................... 98
21.7.3. Possible Problems with Jettison Provider ............................................... 98
21.8. Interfaces, Abstract Classes, and JAXB ............................................................ 99
21.9. Configurating JAXB Marshalling ....................................................................... 99
RESTEasy Atom Support ....................................................................................... 101
22.1. RESTEasy Atom API and Provider ................................................................. 101
22.2. Using JAXB with the Atom Provider ............................................................... 102
JSON Support via Jackson .................................................................................... 105
23.1. Using Jackson 1.9.x Outside of WildFly .......................................................... 105
23.2. Using Jackson 1.9.x Inside WildFly 8 ............................................................. 105
23.3. Using Jackson 2 Outside of WildFly ............................................................... 105
23.4. Using Jackson 2 Inside WildFly 9 and above .................................................. 106
23.5. Additional RESTEasy Specifics ...................................................................... 106
23.6. Possible Conflict With JAXB Provider ............................................................. 107
23.7. JSONP Support ............................................................................................ 107
23.8. Jackson JSON Decorator .............................................................................. 109
23.9. JSON Filter Support ...................................................................................... 109
JSON Support via Java EE 7 JSON-P API .............................................................. 113
Multipart Providers ................................................................................................. 115
25.1. Input with multipart/mixed .............................................................................. 115
25.2. java.util.List with multipart data ....................................................................... 117
25.3. Input with multipart/form-data ......................................................................... 117
25.4. java.util.Map with multipart/form-data .............................................................. 118
25.5. Input with multipart/related ............................................................................. 118
25.6. Output with multipart .....................................................................................
25.7. Multipart Output with java.util.List ...................................................................
25.8. Output with multipart/form-data ......................................................................
25.9. Multipart FormData Output with java.util.Map ..................................................
25.10. Output with multipart/related .........................................................................
25.11. @MultipartForm and POJOs ........................................................................
25.12. XML-binary Optimized Packaging (Xop) ........................................................
25.13. Note about multipart parsing and working with other frameworks .....................
25.14. Overwriting the default fallback content type for multipart messages ................
25.15. Overwriting the content type for multipart messages ......................................
25.16. Overwriting the default fallback charset for multipart messages .......................
26. YAML Provider .......................................................................................................
27. JAX-RS 2.1 Additions .............................................................................................
27.1. CompletionStage support ...............................................................................
27.2. Reactive Clients API ......................................................................................
119
120
120
122
123
124
128
130
130
131
131
133
135
135
135
27.3. Server-Sent Events (SSE) .............................................................................
27.3.1. SSE Server ........................................................................................
27.3.2. SSE Broadcasting ..............................................................................
27.3.3. SSE Client .........................................................................................
27.4. Java API for JSON Binding ............................................................................
String marshalling for String based @*Param .......................................................
28.1. Simple conversion .........................................................................................
28.2. ParamConverter ............................................................................................
28.3. StringParameterUnmarshaller .........................................................................
28.4. Collections ....................................................................................................
28.4.1. @QueryParam ...................................................................................
28.4.2. @MatrixParam ...................................................................................
28.4.3. @HeaderParam ..................................................................................
28.4.4. @CookieParam ..................................................................................
28.4.5. @PathParam ......................................................................................
28.5. Extension to ParamConverter semantics .........................................................
Responses using javax.ws.rs.core.Response ........................................................
Exception Handling ................................................................................................
30.1. Exception Mappers ........................................................................................
30.2. RESTEasy Built-in Internally-Thrown Exceptions .............................................
30.3. Overriding RESTEasy Builtin Exceptions ........................................................
Configuring Individual JAX-RS Resource Beans ...................................................
Content encoding ...................................................................................................
32.1. GZIP Compression/Decompression ................................................................
32.1.1. Configuring GZIP compression / decompression ...................................
32.2. General content encoding ..............................................................................
CORS .....................................................................................................................
135
135
137
138
138
141
141
142
143
145
145
146
146
147
147
149
155
157
157
158
159
161
163
163
163
165
169
28.
29.
30.
31.
32.
33.
v
RESTEasy JAX-RS
34. Content-Range Support ......................................................................................... 171
35. RESTEasy Caching Features ................................................................................. 173
35.1. @Cache and @NoCache Annotations ............................................................
35.2. Client "Browser" Cache .................................................................................
35.3. Local Server-Side Response Cache ...............................................................
35.4. HTTP preconditions .......................................................................................
36. Filters and Interceptors ..........................................................................................
36.1. Server Side Filters ........................................................................................
36.1.1. Asynchronous filters ............................................................................
36.2. Client Side Filters ..........................................................................................
36.3. Reader and Writer Interceptors ......................................................................
36.4. Per Resource Method Filters and Interceptors .................................................
36.5. Ordering .......................................................................................................
37. Asynchronous HTTP Request Processing .............................................................
37.1. Using the @Suspended annotation ................................................................
37.2. Using Reactive return types ...........................................................................
37.3. Asynchronous filters ......................................................................................
173
174
175
177
179
179
180
180
181
181
182
183
183
184
185
38. Asynchronous Job Service ....................................................................................
38.1. Using Async Jobs .........................................................................................
38.2. Oneway: Fire and Forget ...............................................................................
38.3. Setup and Configuration ................................................................................
39. Reactive programming support .............................................................................
39.1. CompletionStage ...........................................................................................
39.2. CompletionStage in JAX-RS ..........................................................................
39.3. Beyond CompletionStage ...............................................................................
39.4. Pluggable reactive types: RxJava 2 in RESTEasy ...........................................
39.5. Proxies .........................................................................................................
39.6. Adding extensions .........................................................................................
40. Embedded Containers ............................................................................................
40.1. Undertow ......................................................................................................
40.2. Sun JDK HTTP Server ..................................................................................
40.3. TJWS Embeddable Servlet Container .............................................................
40.4. Netty ............................................................................................................
40.5. Vert.x ............................................................................................................
41. Server-side Mock Framework .................................................................................
42. Securing JAX-RS and RESTEasy ...........................................................................
43. JSON Web Signature and Encryption (JOSE-JWT) ................................................
43.1. JSON Web Signature (JWS) ..........................................................................
43.2. JSON Web Encryption (JWE) ........................................................................
44. Doseta Digital Signature Framework ......................................................................
44.1. Maven settings ..............................................................................................
44.2. Signing API ...................................................................................................
44.2.1. @Signed annotation ...........................................................................
44.3. Signature Verification API ..............................................................................
187
187
188
188
191
191
194
198
199
211
213
217
217
219
220
221
222
225
227
229
229
229
233
235
235
236
237
vi
44.3.1. Annotation-based verification ............................................................... 239
44.4. Managing Keys via a KeyRepository .............................................................. 240
44.4.1. Create a KeyStore ..............................................................................
44.4.2. Configure Restreasy to use the KeyRepository .....................................
44.4.3. Using DNS to Discover Public Keys .....................................................
Body Encryption and Signing via SMIME ..............................................................
45.1. Maven settings ..............................................................................................
45.2. Message Body Encryption .............................................................................
45.3. Message Body Signing ..................................................................................
45.4. application/pkcs7-signature ............................................................................
EJB Integration ......................................................................................................
Spring Integration ..................................................................................................
CDI Integration .......................................................................................................
48.1. Using CDI beans as JAX-RS components ......................................................
48.2. Default scopes ..............................................................................................
48.3. Configuration within WildFly ...........................................................................
48.4. Configuration with different distributions ..........................................................
240
240
242
245
245
245
248
250
251
253
261
261
261
262
262
49. Guice 3.0 Integration ..............................................................................................
49.1. Request Scope .............................................................................................
49.2. Binding JAX-RS utilities .................................................................................
49.3. Configuring Stage .........................................................................................
49.4. Custom Injector creation ................................................................................
50. RESTEasy Client API .............................................................................................
50.1. JAX-RS 2.0 Client API ...................................................................................
50.2. RESTEasy Proxy Framework .........................................................................
50.2.1. Abstract Responses ............................................................................
50.2.2. Response proxies ...............................................................................
50.2.3. Giving client proxy an ad hoc URI .......................................................
50.2.4. Sharing an interface between client and server .....................................
50.3. Apache HTTP Client 4.x and other backends ..................................................
50.3.1. HTTP redirect .....................................................................................
50.3.2. Apache HTTP Client pre-4.3 APIs .......................................................
50.3.3. Apache HTTP Client 4.3 APIs .............................................................
50.3.4. Asynchronous HTTP Request Processing ............................................
50.3.5. Jetty Client Engine .............................................................................
51. MicroProfile Rest Client .........................................................................................
51.1. Client proxies ................................................................................................
51.2. Beyond RESTEasy ........................................................................................
52. AJAX Client ............................................................................................................
52.1. Generated JavaScript API ..............................................................................
52.1.1. JavaScript API servlet .........................................................................
52.1.2. JavaScript API usage .........................................................................
52.1.3. Work with @Form ..............................................................................
52.1.4. MIME types and unmarshalling. ...........................................................
263
264
265
265
266
269
269
270
272
272
276
278
278
280
281
282
283
284
285
285
288
293
293
293
294
296
297
45.
46.
47.
48.
vii
RESTEasy JAX-RS
52.1.5. MIME types and marshalling. .............................................................. 299
52.2. Using the JavaScript API to build AJAX queries .............................................. 300
52.2.1. The REST object ................................................................................
52.2.2. The REST.Request class ....................................................................
52.3. Caching Features ..........................................................................................
RESTEasy WADL Support .....................................................................................
53.1. RESTEasy WADL Support for Servlet Container .............................................
53.2. RESTEasy WADL support for Sun JDK HTTP Server ......................................
53.3. RESTEasy WADL support for Netty Container ................................................
53.4. RESTEasy WADL Support for Undertow Container .........................................
Validation ...............................................................................................................
54.1. Violation reporting .........................................................................................
54.2. Validation Service Providers ..........................................................................
Internationalization and Localization .....................................................................
55.1. Internationalization .........................................................................................
55.2. Localization ...................................................................................................
Maven and RESTEasy ............................................................................................
300
301
302
303
303
303
305
305
307
308
312
317
317
319
321
57. Deprecated Security Modules ................................................................................
58. Migration to RESTEasy 3.5 series ..........................................................................
59. Migration to RESTEasy 3.1 series ..........................................................................
59.1. Upgrading with RESTEasy 3 API ...................................................................
59.2. Upgrading with RESTEasy 2 API ...................................................................
60. Migration from older versions ................................................................................
60.1. Migrating from RESTEasy 2 to RESTEasy 3 ...................................................
60.2. Migrating from 3.0.x to 4.0.0 ..........................................................................
61. Books You Can Read .............................................................................................
325
327
329
330
331
333
333
333
335
53.
54.
55.
56.
viii
Preface
Commercial development support, production support and training for RESTEasy JAX-RS is available through JBoss, a division of Red Hat Inc. (see http://www.jboss.com/).
In some of the example listings, what is meant to be displayed on one line does not fit inside the
available page width. These lines have been broken up. A '\' at the end of a line means that a
break has been introduced to fit in the page, with the following lines indented. So:
Let's pretend to have an extremely \
long line that \
does not fit
This one is short
Is really:
Let's pretend to have an extremely long line that does not fit
This one is short
ix
x
Chapter 1.
Chapter 1. Overview
JAX-RS 2.0 (JSR-339) and JAX-RS 2.1 (JSR-370), are JCP specifications that provide a Java API
for RESTful Web Services over the HTTP protocol. RESTEasy is a portable implementation of
these specifications which can run in any Servlet container. Tighter integration with WildFly application server is also available to make the user experience nicer in that environment. RESTEasy
also comes with additional features on top of plain JAX-RS functionalities.
1
2
Chapter 2.
Chapter 2. License
RESTEasy is distributed under the ASL 2.0 license. It does not distribute any thirdparty libraries
that are GPL. It does ship thirdparty libraries licensed under Apache ASL 2.0 and LGPL.
3
4
Chapter 3.
Chapter 3. Installation/
Configuration
RESTEasy is installed and configured in different ways depending on which environment you are
running in. If you are running in WildFly, RESTEasy is already bundled and integrated completely
so there is very little you have to do. If you are running in a different environment, there is some
manual installation and configuration you will have to do.
3.1. RESTEasy modules in WildFly
In WildFly, RESTEasy and the JAX-RS API are automatically loaded into your deployment's classpath if and only if you are deploying a JAX-RS application (as determined by the presence of JAXRS annotations). However, only some RESTEasy features are automatically loaded. See Table
3.1. If you need any of those libraries which are not loaded automatically, you'll have to bring them
in with a jboss-deployment-structure.xml file in the WEB-INF directory of your WAR file. Here's
an example:
The services attribute must be set to "import" for modules that have default providers in a METAINF/services/javax.ws.rs.ext.Providers file.
To get an idea of which RESTEasy modules are loaded by default when JAX-RS services are
deployed, please see the table below, which refers to a recent WildFly ditribution patched with the
current RESTEasy distribution. Clearly, future and unpatched WildFly distributions might differ a
bit in terms of modules enabled by default, as the container actually controls this too.
Table 3.1.
Module Name
Loaded by Default
Description
org.jboss.resteasy.resteasyatom-provider
yes
RESTEasy's atom library
org.jboss.resteasy.resteasycdi
yes
RESTEasy CDI integration
5
Chapter 3. Installation/Confi...
Module Name
Loaded by Default
Description
org.jboss.resteasy.resteasycrypto
yes
S/MIME, DKIM, and support
for other security formats.
org.jboss.resteasy.resteasyjackson-provider
no
Integration with the JSON
parser and object mapper
Jackson (deprecated)
org.jboss.resteasy.resteasyjackson2-provider
yes
Integration with the JSON
parser and object mapper
Jackson 2
org.jboss.resteasy.resteasyjaxb-provider
yes
XML JAXB integration.
org.jboss.resteasy.resteasyjaxrs
yes
Core RESTEasy libraries for
server and client. You will
need to include this in your deployment if you are only using
JAX-RS client.
org.jboss.resteasy.resteasyjettison-provider
no
Alternative JAXB-like parser
for JSON (deprecated)
org.jboss.resteasy.jose-jwt
no
JSON Web Token support.
org.jboss.resteasy.resteasyjsapi
yes
RESTEasy's Javascript API
org.jboss.resteasy.resteasyjson-p-provider
yes
JSON parsing API
org.jboss.resteasy.resteasyjson-binding-provider
yes
JSON binding API
javax.json.bind-api
yes
JSON binding API
org.eclipse.yasson
yes
RI implementation of JSON
binding API
org.jboss.resteasy.resteasymultipart-provider
yes
Support for multipart formats
org.jboss.resteasy.skeletonkey
no
OAuth2 support.
org.jboss.resteasy.resteasyspring
no
Spring provider
org.jboss.resteasy.resteasyvalidator-provider-11
yes
RESTEasy's interface to Hibernate Bean Validation 1.1
org.jboss.resteasy.resteasyyaml-provider
yes
YAML marshalling
6
Other RESTEasy modules
3.1.1. Other RESTEasy modules
Not all RESTEasy modules are bundled with WildFly. For example, resteasy-fastinfoset-provider
and resteasy-wadl are not included among the modules listed in Section 3.1, “RESTEasy modules
in WildFly”. If you want to use them in your application, you can include them in your WAR as
you would if you were deploying outside of WildFly. See Section 3.3, “Deploying to other servlet
containers” for more information.
3.1.2. Upgrading RESTEasy within WildFly
RESTEasy is bundled with WildFly, but you may want to upgrade RESTEasy in WildFly to
the latest version. The RESTEasy distribution comes with a zip file called resteasy-jboss-modules-.zip. Unzip this file within the modules/system/layers/base/ directory of the WildFly
distribution. This will configure WildFly to use new versions of the modules listed in Section 3.1,
“RESTEasy modules in WildFly”.
3.2. Deploying a RESTEasy application to WildFly
RESTEasy is bundled with WildFly and completely integrated as per the requirements of Java EE.
You can use it with EJB and CDI and you can rely completely on WildFly to scan for and deploy
your JAX-RS services and providers. All you have to provide is your JAX-RS service and provider
classes packaged within a WAR either as POJOs, CDI beans, or EJBs. A simple way to configure
an application is by simply providing an empty web.xml file. You can of course deploy any custom
servlet, filter or security constraint you want to within your web.xml, but none of them are required:
http://
Also, RESTEasy context-params (see Section 3.4, “Configuration switches”) are available if you
want to tweak or turn on/off any specific RESTEasy feature.
Since
we're
not
using
a
element, we must define a
javax.ws.rs.core.Application class (see Section 3.5, “javax.ws.rs.core.Application”) that is
annotated with the javax.ws.rs.ApplicationPath annotation. If you return any empty set for
classes and singletons, which is the behavior inherited from Application, your WAR will be
scanned for resource and provider classes as indicated by the presence of JAX-RS annotations.
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
7
Chapter 3. Installation/Confi...
@ApplicationPath("/root-path")
public class MyApplication extends Application
{
}
Note. Actually, if the application jar contains an Application class (or a subclass thereof) which
is annotated with an ApplicationPath annotation, a web.xml file isn't even needed. Of course,
even in this case it can be used to specify additional information such as context parameters.
If there is an Application class but it doesn't have an @ApplicationPath annotation, then a
web.xml file with at least a element is required.
Note. As mentioned in Section 3.1.1, “Other RESTEasy modules”, not all RESTEasy modules
are bundled with WildFly. For example, resteasy-fastinfoset-provider and resteasy-wadl are not
included among the modules listed in Section 3.1, “RESTEasy modules in WildFly”. If you want
to use them in your application, you can include them in your WAR as you would if you were
deploying outside of WildFly. See Section 3.3, “Deploying to other servlet containers” for more
information.
3.3. Deploying to other servlet containers
If you are using RESTEasy outside of WildFly, in a standalone servlet container like Tomcat or
Jetty, for example, you will need to include the appropriate RESTEasy jars in your WAR file. You
will need the core classes in the resteasy-jaxrs module, and you may need additional facilities like
the resteasy-jaxb-provider module. We strongly suggest that you use Maven to build your WAR
files as RESTEasy is split into a bunch of different modules:
org.jboss.resteasy
resteasy-jaxrs
${resteasy.version}
org.jboss.resteasy
resteasy-jaxb-provider
${resteasy.version}
You can see sample Maven projects in https://github.com/resteasy/resteasy-examples.
If you are not using Maven, you can include the necessary jars by hand. If you download
RESTEasy (from http://resteasy.jboss.org/downloads.html, for example) you will get a file like
resteasy-jaxrs--all.zip. If you unzip it you will see a lib/ directory that contains the libraries
needed by RESTEasy. Copy these, as needed, into your /WEB-INF/lib directory. Place your JAX-
8
Servlet 3.0 containers
RS annotated class resources and providers within one or more jars within /WEB-INF/lib or your
raw class files within /WEB-INF/classes.
3.3.1. Servlet 3.0 containers
RESTEasy uses the ServletContainerInitializer integration interface in Servlet 3.0 containers to initialize an application, automatically scanning for resources and providers. To enable automatic scanning, you must also include the resteasy-servlet-initializer artifact in your
WAR file as well:
org.jboss.resteasy
resteasy-servlet-initializer
${resteasy.version}
3.3.2. Older servlet containers
The resteasy-servlet-initializer artifact will not work in Servlet versions older than
3.0. You'll then have to manually declare the RESTEasy servlet in your WEB-INF/web.xml
file of your WAR project, and you'll have to use an Application class (see Section 3.5,
“javax.ws.rs.core.Application”) which explicitly lists resources and providers. For example:
Archetype Created Web Application
Resteasy
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
javax.ws.rs.Application
com.restfully.shop.services.ShoppingApplication
Resteasy
/*
9
Chapter 3. Installation/Confi...
The RESTEasy servlet is responsible for initializing some basic components of RESTEasy.
Note. It is likely that support for pre-3.0 Servlet specifications will be deprecated and eliminated
eventually.
3.4. Configuration switches
RESTEasy receives configuration options from elements.
Table 3.2.
Option Name
Default Value
resteasy.servlet.mapping.prefix no default
Description
If the url-pattern for the
RESTEasy servlet-mapping is
not /*
resteasy.scan
false
Automatically scan WEB-INF/
lib jars and WEB-INF/classes
directory for both @Provider
and JAX-RS resource classes (@Path, @GET, @POST
etc..) and register them.
This property is deprecated; please use a Servlet
3.0 container or higher and
the ResteasyServletInitializer
instead.
resteasy.scan.providers
false
Scan for @Provider classes
and register them. This property is deprecated; please use
a Servlet 3.0 container or higher and the ResteasyServletInitializer instead.
resteasy.scan.resources
false
Scan for JAX-RS resource
classes. This property is deprecated; please use a Servlet
3.0 container or higher and
the ResteasyServletInitializer
instead.
resteasy.providers
no default
A comma delimited list of fully qualified @Provider class
names you want to register
10
Configuration switches
Option Name
Default Value
Description
resteasy.use.builtin.providers
true
Whether or not to register default, built-in @Provider classes
resteasy.resources
no default
A comma delimited list of fully qualified JAX-RS resource
class names you want to register
resteasy.jndi.resources
no default
A comma delimited list of JNDI
names which reference objects you want to register as
JAX-RS resources
javax.ws.rs.Application
no default
Fully qualified name of Application class to bootstrap in a
spec portable way
resteasy.media.type.mappings no default
Replaces the need for an Accept header by mapping file
name extensions (like .xml
or .txt) to a media type. Used
when the client is unable
to use an Accept header to
choose a representation (i.e.
a browser). See Chapter 19,
JAX-RS Content Negotiation
for more details.
resteasy.language.mappings
no default
Replaces the need for an
Accept-Language header by
mapping file name extensions
(like .en or .fr) to a language.
Used when the client is unable to use an Accept-Language header to choose a language (i.e. a browser). See
Chapter 19, JAX-RS Content
Negotiation for more details.
resteasy.media.type.param.mapping
no default
Names a query parameter that
can be set to an acceptable
media type, enabling content
negotiation without an Accept
header. See Chapter 19, JAXRS Content Negotiation for
more details.
11
Chapter 3. Installation/Confi...
Option Name
Default Value
Description
resteasy.role.based.security
false
Enables role based security. See Chapter 42, Securing JAX-RS and RESTEasy for
more details.
resteasy.document.expand.entity.references
false
Expand external entities in
org.w3c.dom.Document documents and JAXB object representations
resteasy.document.secure.processing.feature
true
Impose
straints
security
conin
processing
org.w3c.dom.Document documents and JAXB object representations
resteasy.document.secure.disableDTDs
true
Prohibit
DTDs
in
org.w3c.dom.Document documents and JAXB object representations
resteasy.wider.request.matchingfalse
Turns off the JAX-RS spec
defined class-level expression
filtering and instead tries to
match version every method's
full path.
resteasy.use.container.form.params
false
Obtain
meters
form
by
parausing
HttpServletRequest.getParameterMap().
Use this switch if you are calling this method within a servlet
filter or eating the input stream
within the filter.
resteasy.rfc7232preconditions false
Enables RFC7232 compliant
HTTP preconditions handling.
resteasy.gzip.max.input
Imposes maximum size on decompressed gzipped .
10000000
resteasy.secure.random.max.use
100
The number of times a SecureRandom can be used before reseeding.
resteasy.buffer.exception.entity true
Upon receiving an exception,
the client side buffers any response entity before closing
the connection.
12
Configuration switches
Option Name
Default Value
Description
resteasy.add.charset
true
If a resource method returns
a text/* or application/xml* media type without an explicit
charset, RESTEasy will add
"charset=UTF-8" to the returned Content-Type header.
Note that the charset defaults
to UTF-8 in this case, independent of the setting of this parameter.
jaxrs.2.0.request.matching
false
In searching for a matching resource method with which to
respond to a request, consider only resource methods with
the best match for the request
path. See JAX-RS 2.0 Matching Algorithm for discussion.
resteasy.disable.html.sanitizer false
Normally, a response with media type "text/html" and a status of 400 will be processed
so that the characters "/", "<",
">", "&", """ (double quote), and
"'" (single quote) are escaped
to prevent an XSS attack. If
this parameter is set to "true",
escaping will not occur.
Note. The resteasy.servlet.mapping.prefix variable must be set if your servletmapping for the RESTEasy servlet has a url-pattern other than /*. For example, if the url-pattern is
Resteasy
/restful-services/*
Then the value of resteasy.servlet.mapping.prefix must be:
resteasy.servlet.mapping.prefix
/restful-services
13
Chapter 3. Installation/Confi...
3.5. javax.ws.rs.core.Application
The javax.ws.rs.core.Application class is a standard JAX-RS class that you may implement
to provide information on your deployment. It is simply a class the lists all JAX-RS root resources
and providers.
/**
* Defines the components of a JAX-RS application and supplies additional
* metadata. A JAX-RS application or implementation supplies a concrete
* subclass of this abstract class.
*/
public abstract class Application
{
private static final Set emptySet = Collections.emptySet();
/**
* Get a set of root resource and provider classes. The default lifecycle
* for resource class instances is per-request. The default lifecycle for
* providers is singleton.
*
* Implementations should warn about and ignore classes that do not
* conform to the requirements of root resource or provider classes.
* Implementations should warn about and ignore classes for which
* {@link #getSingletons()} returns an instance. Implementations MUST
* NOT modify the returned set.
*
* @return a set of root resource and provider classes. Returning null
* is equivalent to returning an empty set.
*/
public abstract Set> getClasses();
/**
* Get a set of root resource and provider instances. Fields and properties
* of returned instances are injected with their declared dependencies
* (see {@link Context}) by the runtime prior to use.
*
* Implementations should warn about and ignore classes that do not
* conform to the requirements of root resource or provider classes.
* Implementations should flag an error if the returned set includes
* more than one instance of the same class. Implementations MUST
* NOT modify the returned set.
*
* The default implementation returns an empty set.
*
14
RESTEasy as a ServletContextListener
* @return a set of root resource and provider instances. Returning null
* is equivalent to returning an empty set.
*/
public Set getSingletons()
{
return emptySet;
}
}
Note. If your web.xml file does not have a element, you must use an Application class annotated with @ApplicationPath.
3.6. RESTEasy as a ServletContextListener
This section is pretty much deprecated if you are using a Servlet 3.0 container or higher. Skip it if
you are and read the configuration section above on installing in Servlet 3.0. The initialization of
RESTEasy can be performed within a ServletContextListener instead of within the Servlet. You
may need this if you are writing custom Listeners that need to interact with RESTEasy at boot
time. An example of this is the RESTEasy Spring integration that requires a Spring ServletContextListener. The org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap class is a ServletContextListener that configures an instance of an ResteasyProviderFactory and Registry. You can
obtain instances of a ResteasyProviderFactory and Registry from the ServletContext attributes
org.jboss.resteasy.spi.ResteasyProviderFactory and org.jboss.resteasy.spi.Registry. From these
instances you can programmatically interact with RESTEasy registration interfaces.
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
Resteasy
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
Resteasy
15
Chapter 3. Installation/Confi...
/Resteasy/*
3.7. RESTEasy as a Servlet Filter
This section is pretty much deprecated if you are using a Servlet 3.0 container or higher. Skip it
if you are and read the configuration section above on installing in Servlet 3.0. The downside of
running RESTEasy as a Servlet is that you cannot have static resources like .html and .jpeg files
in the same path as your JAX-RS services. RESTEasy allows you to run as a Filter instead. If
a JAX-RS resource is not found under the URL requested, RESTEasy will delegate back to the
base servlet container to resolve URLs.
Resteasy
org.jboss.resteasy.plugins.server.servlet.FilterDispatcher
javax.ws.rs.Application
com.restfully.shop.services.ShoppingApplication
Resteasy
/*
3.8. Client side
JAX-RS 2.0 conforming implementations such as RESTEasy support a client side framework
which simplifies communicating with restful applications. In RESTEasy, the minimal set of modules
needed for the client framework consists of resteasy-jaxrs and resteasy-client. You can access
them by way of maven:
16
Client side
org.jboss.resteasy
resteasy-jaxrs
${resteasy.version}
org.jboss.resteasy
resteasy-client
${resteasy.version}
Other modules, such as resteasy-jaxb-provider, may be brought in as needed.
17
18
Chapter 4.
Chapter 4. Using @Path and @GET,
@POST, etc.
@Path("/library")
public class Library {
@GET
@Path("/books")
public String getBooks() {...}
@GET
@Path("/book/{isbn}")
public String getBook(@PathParam("isbn") String id) {
// search my database and get a string representation and return it
}
@PUT
@Path("/book/{isbn}")
public void addBook(@PathParam("isbn") String id, @QueryParam("name") String
name) {...}
@DELETE
@Path("/book/{id}")
public void removeBook(@PathParam("id") String id {...}
}
Let's say you have the RESTEasy servlet configured and reachable at a root path of http://
myhost.com/services. The requests would be handled by the Library class:
• GET http://myhost.com/services/library/books
• GET http://myhost.com/services/library/book/333
• PUT http://myhost.com/services/library/book/333
• DELETE http://myhost.com/services/library/book/333
The @javax.ws.rs.Path annotation must exist on either the class and/or a resource method. If it
exists on both the class and method, the relative path to the resource method is a concatenation
of the class and method.
In the @javax.ws.rs package there are annotations for each HTTP method. @GET, @POST,
@PUT, @DELETE, and @HEAD. You place these on public methods that you want to map to
19
Chapter 4. Using @Path and @G...
that certain kind of HTTP method. As long as there is a @Path annotation on the class, you do
not have to have a @Path annotation on the method you are mapping. You can have more than
one HTTP method as long as they can be distinguished from other methods.
When you have a @Path annotation on a method without an HTTP method, these are called
JAXRSResourceLocators.
4.1. @Path and regular expression mappings
The @Path annotation is not limited to simple path expressions. You also have the ability to insert
regular expressions into @Path's value. For example:
@Path("/resources)
public class MyResource {
@GET
@Path("{var:.*}/stuff")
public String get() {...}
}
The following GETs will route to the getResource() method:
GET /resources/stuff
GET /resources/foo/stuff
GET /resources/on/and/on/stuff
The format of the expression is:
"{" variable-name [ ":" regular-expression ] "}"
The regular-expression part is optional. When the expression is not provided, it defaults to a
wildcard matching of one particular segment. In regular-expression terms, the expression defaults
to
"([]*)"
For example:
20
JAX-RS 2.0 Matching Algorithm
@Path("/resources/{var}/stuff")
will match these:
GET /resources/foo/stuff
GET /resources/bar/stuff
but will not match:
GET /resources/a/bunch/of/stuff
4.2. JAX-RS 2.0 Matching Algorithm
The resource method matching algorithm mandated by JAX-RS 2.1 is more inclusive that that of
JAX-RS 2.0. There are three stages in each of the matching algorithms:
1. Use the request path to choose possible resource classes.
2. Use the request path to choose possible resource methods.
3. Use the HTTP verb and media types, coming and going, to choose a final resource method.
In JAX-RS 2.1, step 2 determines the set of matching resource methods and passes it on to step
3. However, in JAX-RS 2.0, that set is sorted, based on properties of @Path values like number
of literals, and only the maximal elements are passed on to step 3. It follows that in some cases,
the newer algorithm will find some matches that the earlier algoritm misses. For example,
@Path("/")
public static class TestResource
{
@GET
@Path("complex/match")
public String get()
{
return "content";
}
@POST
@Path("complex/{param}")
21
Chapter 4. Using @Path and @G...
public String post(@PathParam("param") String param)
{
return "<" + param + "/>";
}
}
Both methods can match a request with path "complex/match", but get() comes out ahead of
post() in the JAX-RS 2.0 sort because it has more literal characters, and only get() is considered
in step 3. [For more details about the sort, see the specification for JAX-RS 2.0.] Therefore, a
request that expects a POST method will fail.
On the other hand, both methods are passed on to step 3 in the JAX-RS 2.1 algorithm, so post()
is available as a potential match.
The algorithm from JAX-RS 2.1 would seem to be preferable, but, in case the earlier behavior is expected for backwards compatibility, RESTEasy provides a configuration switch,
"jaxrs.2.0.request.matching", which, if set to "true", will cause the JAX-RS 2.0 matching to be
used. The default value, of course, is "false".
22
Chapter 5.
Chapter 5. @PathParam
Note
RESTEasy supports @PathParam annotations with no parameter name..
@PathParam is a parameter annotation which allows you to map variable URI path fragments
into your method call.
@Path("/library")
public class Library {
@GET
@Path("/book/{isbn}")
public String getBook(@PathParam("isbn") String id) {
// search my database and get a string representation and return it
}
}
What this allows you to do is embed variable identification within the URIs of your resources. In
the above example, an isbn URI parameter is used to pass information about the book we want to
access. The parameter type you inject into can be any primitive type, a String, or any Java object
that has a constructor that takes a String parameter, or a static valueOf method that takes a String
as a parameter. For example, lets say we wanted isbn to be a real object. We could do:
@GET
@Path("/book/{isbn}")
public String getBook(@PathParam("isbn") ISBN id) {...}
public class ISBN {
public ISBN(String str) {...}
}
Or instead of a public String constructors, have a valueOf method:
public class ISBN {
public static ISBN valueOf(String isbn) {...}
23
Chapter 5. @PathParam
}
5.1. Advanced @PathParam and Regular Expressions
There are a few more complicated uses of @PathParams not discussed in the previous section.
You are allowed to specify one or more path params embedded in one URI segment. Here are
some examples:
1. @Path("/aaa{param}bbb")
2. @Path("/{name}-{zip}")
3. @Path("/foo{name}-{zip}bar")
So, a URI of "/aaa111bbb" would match #1. "/bill-02115" would match #2. "foobill-02115bar" would
match #3.
We discussed before how you can use regular expression patterns within @Path values.
@GET
@Path("/aaa{param:b+}/{many:.*}/stuff")
public String getIt(@PathParam("param") String bs, @PathParam("many") String
many) {...}
For the following requests, lets see what the values of the "param" and "many" @PathParams
would be:
Table 5.1.
Request
param
many
GET /aaabb/some/stuff
bb
some
GET /aaab/a/lot/of/stuff
b
a/lot/of
5.2. @PathParam and PathSegment
The specification has a very simple abstraction for examining a fragment of the URI path being
invoked on javax.ws.rs.core.PathSegment:
24
@PathParam and PathSegment
public interface PathSegment {
/**
* Get the path segment.
*
* @return the path segment
*/
String getPath();
/**
* Get a map of the matrix parameters associated with the path segment
* @return the map of matrix parameters
*/
MultivaluedMap getMatrixParameters();
}
You can have RESTEasy inject a PathSegment instead of a value with your @PathParam.
@GET
@Path("/book/{id}")
public String getBook(@PathParam("id") PathSegment id) {...}
This is very useful if you have a bunch of @PathParams that use matrix parameters. The idea
of matrix parameters is that they are an arbitrary set of name-value pairs embedded in a uri path
segment. The PathSegment object gives you access to these parameters. See also MatrixParam.
A matrix parameter example is:
GET http://host.com/library/book;name=EJB 3.0;author=Bill Burke
The basic idea of matrix parameters is that it represents resources that are addressable by their
attributes as well as their raw id.
25
26
Chapter 6.
Chapter 6. @QueryParam
Note
RESTEasy supports @QueryParam annotations with no parameter name..
The @QueryParam annotation allows you to map a URI query string parameter or url form encoded parameter to your method invocation.
GET /books?num=5
@GET
public String getBooks(@QueryParam("num") int num) {
...
}
Currently since RESTEasy is built on top of a Servlet, it does not distinguish between URI query
strings or url form encoded parameters. Like PathParam, your parameter type can be an String,
primitive, or class that has a String constructor or static valueOf() method.
27
28
Chapter 7.
Chapter 7. @HeaderParam
Note
RESTEasy supports @HeaderParam annotations with no parameter name..
The @HeaderParam annotation allows you to map a request HTTP header to your method invocation.
GET /books?num=5
@GET
public String getBooks(@HeaderParam("From") String from) {
...
}
Like PathParam, your parameter type can be an String, primitive, or class that has a String constructor or static valueOf() method. For example, MediaType has a valueOf() method and you
could do:
@PUT
public void put(@HeaderParam("Content-Type") MediaType contentType, ...)
29
30
Chapter 8.
Chapter 8. Linking resources
There are two mechanisms available in RESTEasy to link a resource to another, and to link resources to operations: the Link HTTP header, and Atom links inside the resource representations.
8.1. Link Headers
RESTEasy
has
both
client
and
server
side
support
for
the
header
specification
[http://tools.ietf.org/html/draft-nottingham-http-link-header-06].
the javadocs for org.jboss.resteasy.spi.LinkHeader, org.jboss.resteasy.spi.Link,
org.jboss.resteasy.client.ClientResponse.
Link
See
and
The main advantage of Link headers over Atom links in the resource is that those links are available without parsing the entity body.
8.2. Atom links in the resource representations
RESTEasy allows you to inject Atom links [http://tools.ietf.org/html/rfc4287#section-4.2.7] directly
inside the entity objects you are sending to the client, via auto-discovery.
Warning
This is only available when using the Jettison or JAXB providers (for JSON and
XML).
The main advantage over Link headers is that you can have any number of Atom links directly
over the concerned resources, for any number of resources in the response. For example, you
can have Atom links for the root response entity, and also for each of its children entities.
8.2.1. Configuration
There is no configuration required to be able to inject Atom links in your resource representation,
you just have to have this maven artifact in your path:
Table 8.1. Maven artifact for Atom link injection
Group
Artifact
Version
org.jboss.resteasy
resteasy-links
3.6.2.Final
8.2.2. Your first links injected
You need three things in order to tell RESTEasy to inject Atom links in your entities:
• Annotate the JAX-RS method with @AddLinks to indicate that you want Atom links injected in
your response entity.
31
Chapter 8. Linking resources
• Add RESTServiceDiscovery fields to the resource classes where you want Atom links injected.
• Annotate the JAX-RS methods you want Atom links for with @LinkResource, so that RESTEasy
knows which links to create for which resources.
The following example illustrates how you would declare everything in order to get the Atom links
injected in your book store:
@Path("/")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface BookStore {
@AddLinks
@LinkResource(value = Book.class)
@GET
@Path("books")
public Collection getBooks();
@LinkResource
@POST
@Path("books")
public void addBook(Book book);
@AddLinks
@LinkResource
@GET
@Path("book/{id}")
public Book getBook(@PathParam("id") String id);
@LinkResource
@PUT
@Path("book/{id}")
public void updateBook(@PathParam("id") String id, Book book);
@LinkResource(value = Book.class)
@DELETE
@Path("book/{id}")
public void deleteBook(@PathParam("id") String id);
}
And this is the definition of the Book resource:
@Mapped(namespaceMap = @XmlNsMap(jsonName
www.w3.org/2005/Atom"))
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
32
=
"atom",
namespace
=
"http://
Your first links injected
public class Book {
@XmlAttribute
private String author;
@XmlID
@XmlAttribute
private String title;
@XmlElementRef
private RESTServiceDiscovery rest;
}
If you do a GET /order/foo you will then get this XML representation:
href="http://localhost:8081/books" rel="add"/>
href="http://localhost:8081/book/foo" rel="self"/>
href="http://localhost:8081/book/foo" rel="update"/>
href="http://localhost:8081/book/foo" rel="remove"/>
And in JSON format:
{
"book":
{
"@title":"foo",
"@author":"bar",
"atom.link":
[
{"@href":"http://localhost:8081/books","@rel":"list"},
{"@href":"http://localhost:8081/books","@rel":"add"},
{"@href":"http://localhost:8081/book/foo","@rel":"self"},
{"@href":"http://localhost:8081/book/foo","@rel":"update"},
{"@href":"http://localhost:8081/book/foo","@rel":"remove"}
]
}
}
33
Chapter 8. Linking resources
8.2.3. Customising how the Atom links are serialised
Because the RESTServiceDiscovery is in fact a JAXB type which inherits from List you are free
to annotate it as you want to customise the JAXB serialisation, or just rely on the default with
@XmlElementRef.
8.2.4. Specifying which JAX-RS methods are tied to which resources
This is all done by annotating the methods with the @LinkResource annotation. It supports the
following optional parameters:
Table 8.2.
@LinkResource
parameters
Parameter
Type
Function
Default
value
Class
Declares an Atom link Defaults to the enfor the given type of re- tity body type (nonsources.
annotated parameter),
or the method's return type. This default
does not work with
Response or Collection types, they need
to be explicitly specified.
rel
String
The Atom link relation list
For GET methods
returning a Collection
self
For GET methods returning a
non-Collection
remove
For DELETE methods
update
For PUT methods
add
For POST methods
34
Specifying path parameter values for URI templates
You can add several @LinkResource annotations on a single method by enclosing them in a
@LinkResources annotation. This way you can add links to the same method on several resource
types. For example the /order/foo/comments operation can belongs on the Order resource with
the comments relation, and on the Comment resource with the list relation.
8.2.5. Specifying path parameter values for URI templates
When RESTEasy adds links to your resources it needs to insert the right values in the URI template. This is done either automatically by guessing the list of values from the entity, or by specifying the values in the @LinkResource pathParameters parameter.
8.2.5.1. Loading URI template values from the entity
URI template values are extracted from the entity from fields or Java Bean properties annotated
with @ResourceID, JAXB's @XmlID or JPA's @Id. If there are more than one URI template value
to find in a given entity, you can annotate your entity with @ResourceIDs to list the names of
fields or properties that make up this entity's Id. If there are other URI template values required
from a parent entity, we try to find that parent in a field or Java Bean property annotated with
@ParentResource. The list of URI template values extracted up every @ParentResource is then
reversed and used as the list of values for the URI template.
For example, let's consider the previous Book example, and a list of comments:
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Comment {
@ParentResource
private Book book;
@XmlElement
private String author;
@XmlID
@XmlAttribute
private String id;
@XmlElementRef
private RESTServiceDiscovery rest;
}
Given the previous book store service augmented with comments:
@Path("/")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface BookStore {
35
Chapter 8. Linking resources
@AddLinks
@LinkResources({
@LinkResource(value = Book.class, rel = "comments"),
@LinkResource(value = Comment.class)
})
@GET
@Path("book/{id}/comments")
public Collection getComments(@PathParam("id") String bookId);
@AddLinks
@LinkResource
@GET
@Path("book/{id}/comment/{cid}")
public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
@LinkResource
@POST
@Path("book/{id}/comments")
public void addComment(@PathParam("id") String bookId, Comment comment);
@LinkResource
@PUT
@Path("book/{id}/comment/{cid}")
public void updateComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
@LinkResource(Comment.class)
@DELETE
@Path("book/{id}/comment/{cid}")
public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
}
Whenever we need to make links for a Book entity, we look up the ID in the Book's @XmlID property.
Whenever we make links for Comment entities, we have a list of values taken from the Comment's
@XmlID and its @ParentResource: the Book and its @XmlID.
For a Comment with id "1" on a Book with title "foo" we will therefore get a list of URI template
values of {"foo", "1"}, to be replaced in the URI template, thus obtaining either "/book/foo/
comments" or "/book/foo/comment/1".
8.2.5.2. Specifying path parameters manually
If you do not want to annotate your entities with resource ID annotations (@ResourceID, @ResourceIDs, @XmlID or @Id) and @ParentResource, you can also specify the URI template values
inside the @LinkResource annotation, using Unified Expression Language expressions:
Table 8.3.
36
Specifying path parameter values for URI templates
@LinkResource
URI template parameter
Parameter
Type
Function
Default
pathParameters
String[]
Declares a list of UEL
expressions to obtain
the URI template values.
Defaults
to using
@ResourceID,
@ResourceIDs, @XmlID or
@Id and @ParentResource annotations to
extract the values
from the model.
The UEL expressions are evaluated in the context of the entity, which means that any unqualified
variable will be taken as a property for the entity itself, with the special variable this bound to
the entity we're generating links for.
The previous example of Comment service could be declared as such:
@Path("/")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface BookStore {
@AddLinks
@LinkResources({
@LinkResource(value = Book.class, rel = "comments", pathParameters = "${title}"),
@LinkResource(value = Comment.class, pathParameters = {"${book.title}", "${id}"})
})
@GET
@Path("book/{id}/comments")
public Collection getComments(@PathParam("id") String bookId);
@AddLinks
@LinkResource(pathParameters = {"${book.title}", "${id}"})
@GET
@Path("book/{id}/comment/{cid}")
public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
@LinkResource(pathParameters = {"${book.title}", "${id}"})
@POST
@Path("book/{id}/comments")
public void addComment(@PathParam("id") String bookId, Comment comment);
@LinkResource(pathParameters = {"${book.title}", "${id}"})
@PUT
@Path("book/{id}/comment/{cid}")
public void updateComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
@LinkResource(Comment.class, pathParameters = {"${book.title}", "${id}"})
37
Chapter 8. Linking resources
@DELETE
@Path("book/{id}/comment/{cid}")
public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
}
8.2.6. Securing entities
You can restrict which links are injected in the resource based on security restrictions for the client,
so that if the current client doesn't have permission to delete a resource he will not be presented
with the "delete" link relation.
Security restrictions can either be specified on the @LinkResource annotation, or using RESTEasy
and EJB's security annotation @RolesAllowed on the JAX-RS method.
Table 8.4.
@LinkResource
security restrictions
Parameter
Type
Function
Default
constraint
String
A UEL expression Defaults to using
which must evaluate @RolesAllowed from
to true to inject this the JAX-RS method.
method's link in the response entity.
8.2.7. Extending the UEL context
We've seen that both the URI template values and the security constraints of @LinkResource use
UEL to evaluate expressions, and we provide a basic UEL context with access only to the entity
we're injecting links in, and nothing more.
If you want to add more variables or functions in this context, you can by adding a @LinkELProvider annotation on the JAX-RS method, its class, or its package. This annotation's value
should point to a class that implements the ELProvider interface, which wraps the default ELContext in order to add any missing functions.
For example, if you want to support the Seam annotation s:hasPermission(target, permission) in your security constraints, you can add a package-info.java file like this:
@LinkELProvider(SeamELProvider.class)
package org.jboss.resteasy.links.test;
import org.jboss.resteasy.links.*;
With the following provider implementation:
38
Extending the UEL context
package org.jboss.resteasy.links.test;
import
import
import
import
javax.el.ELContext;
javax.el.ELResolver;
javax.el.FunctionMapper;
javax.el.VariableMapper;
import org.jboss.seam.el.SeamFunctionMapper;
import org.jboss.resteasy.links.ELProvider;
public class SeamELProvider implements ELProvider {
public ELContext getContext(final ELContext ctx) {
return new ELContext() {
private SeamFunctionMapper functionMapper;
@Override
public ELResolver getELResolver() {
return ctx.getELResolver();
}
@Override
public FunctionMapper getFunctionMapper() {
if (functionMapper == null)
functionMapper = new SeamFunctionMapper(ctx
.getFunctionMapper());
return functionMapper;
}
@Override
public VariableMapper getVariableMapper() {
return ctx.getVariableMapper();
}
};
}
}
And then use it as such:
@Path("/")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface BookStore {
39
Chapter 8. Linking resources
@AddLinks
@LinkResources({
@LinkResource(value=Book.class,rel="comments",constraint="${s:hasPermission(this,
'add-comment')}"),
@LinkResource(value = Comment.class, constraint = "${s:hasPermission(this,
'insert')}")
})
@GET
@Path("book/{id}/comments")
public Collection getComments(@PathParam("id") String bookId);
@AddLinks
@LinkResource(constraint = "${s:hasPermission(this, 'read')}")
@GET
@Path("book/{id}/comment/{cid}")
public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
@LinkResource(constraint = "${s:hasPermission(this, 'insert')}")
@POST
@Path("book/{id}/comments")
public void addComment(@PathParam("id") String bookId, Comment comment);
@LinkResource(constraint = "${s:hasPermission(this, 'update')}")
@PUT
@Path("book/{id}/comment/{cid}")
public void updateComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
@LinkResource(Comment.class, constraint = "${s:hasPermission(this,
'delete')}")
@DELETE
@Path("book/{id}/comment/{cid}")
public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") String commentI
}
8.2.8. Resource facades
Sometimes it is useful to add resources which are just containers or layers on other resources. For
example if you want to represent a collection of Comment with a start index and a certain number
of entries, in order to implement paging. Such a collection is not really an entity in your model, but
it should obtain the "add" and "list" link relations for the Comment entity.
This is possible using resource facades. A resource facade is a resource which implements the
ResourceFacade interface for the type T, and as such, should receive all links for that type.
Since in most cases the instance of the T type is not directly available in the resource facade,
we need another way to extract its URI template values, and this is done by calling the resource
facade's pathParameters() method to obtain a map of URI template values by name. This map
40
Resource facades
will be used to fill in the URI template values for any link generated for T, if there are enough
values in the map.
Here is an example of such a resource facade for a collection of Comments:
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class ScrollableCollection implements ResourceFacade {
private String bookId;
@XmlAttribute
private int start;
@XmlAttribute
private int totalRecords;
@XmlElement
private List comments = new ArrayList();
@XmlElementRef
private RESTServiceDiscovery rest;
public Class facadeFor() {
return Comment.class;
}
public Map pathParameters() {
HashMap map = new HashMap();
map.put("id", bookId);
return map;
}
}
This will produce such an XML collection:
great book
terrible book
41
Chapter 8. Linking resources
42
Chapter 9.
Chapter 9. @MatrixParam
Note
RESTEasy supports @MatrixParam annotations with no parameter name..
The idea of matrix parameters is that they are an arbitrary set of name-value pairs embedded in
a uri path segment. A matrix parameter example is:
GET http://host.com/library/book;name=EJB 3.0;author=Bill Burke
The basic idea of matrix parameters is that it represents resources that are addressable by their
attributes as well as their raw id. The @MatrixParam annotation allows you to inject URI matrix
parameters into your method invocation
@GET
public String getBook(@MatrixParam("name") String name, @MatrixParam("author")
String author) {...}
There is one big problem with @MatrixParam that the current version of the specification does
not resolve. What if the same MatrixParam exists twice in different path segments? In this case,
right now, its probably better to use PathParam combined with PathSegment.
43
44
Chapter 10.
Chapter 10. @CookieParam
Note
RESTEasy supports @CookieParam annotations with no parameter name..
The @CookieParam annotation allows you to inject the value of a cookie or an object representation of an HTTP request cookie into your method invocation
GET /books?num=5
@GET
public String getBooks(@CookieParam("sessionid") int id) {
...
}
@GET
public
{...}
String
getBooks(@CookieParam("sessionid")
javax.ws.rs.core.Cookie
id)
Like PathParam, your parameter type can be an String, primitive, or class that has a String constructor or static valueOf() method. You can also get an object representation of the cookie via
the javax.ws.rs.core.Cookie class.
45
46
Chapter 11.
Chapter 11. @FormParam
Note
RESTEasy supports @FormParam annotations with no parameter name..
When the input request body is of the type "application/x-www-form-urlencoded", a.k.a. an HTML
Form, you can inject individual form parameters from the request body into method parameter
values.
If you post through that form, this is what the service might look like:
@Path("/")
public class NameRegistry {
@Path("/resources/service")
@POST
public
void
addName(@FormParam("firstname")
@FormParam("lastname") String last) {...}
String
first,
You cannot combine @FormParam with the default "application/x-www-form-urlencoded" that unmarshalls to a MultivaluedMap. i.e. This is illegal:
@Path("/")
public class NameRegistry {
@Path("/resources/service")
@POST
@Consumes("application/x-www-form-urlencoded")
47
Chapter 11. @FormParam
public
void
addName(@FormParam("firstname")
MultivaluedMap form) {...}
48
String
first,
Chapter 12.
Chapter 12. @Form
This is a RESTEasy specific annotation that allows you to re-use any @*Param annotation within an injected class. RESTEasy will instantiate the class and inject values into any annotated
@*Param or @Context property. This is useful if you have a lot of parameters on your method
and you want to condense them into a value object.
public class MyForm {
@FormParam("stuff")
private int stuff;
@HeaderParam("myHeader")
private String header;
@PathParam("foo")
public void setFoo(String foo) {...}
}
@POST
@Path("/myservice")
public void post(@Form MyForm form) {...}
When somebody posts to /myservice, RESTEasy will instantiate an instance of MyForm and inject
the form parameter "stuff" into the "stuff" field, the header "myheader" into the header field, and
call the setFoo method with the path param variable of "foo".
Also, @Form has some expanded @FormParam features. If you specify a prefix within the Form
param, this will prepend a prefix to any form parameter lookup. For example, let's say you have
one Address class, but want to reference invoice and shipping addresses from the same set of
form parameters:
public static class Person
{
@FormParam("name")
private String name;
@Form(prefix = "invoice")
private Address invoice;
49
Chapter 12. @Form
@Form(prefix = "shipping")
private Address shipping;
}
public static class Address
{
@FormParam("street")
private String street;
}
@Path("person")
public static class MyResource
{
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String post(@Form Person p)
{
return p.toString();
}
}
In this example, the client could send the following form parameters:
name=bill
invoice.street=xxx
shipping.street=yyy
The Person.invoice and Person.shipping fields would be populated appropriately. Also, prefix
mappings also support lists and maps:
public static class Person {
@Form(prefix="telephoneNumbers") List telephoneNumbers;
@Form(prefix="address") Map addresses;
}
public static class TelephoneNumber {
@FormParam("countryCode") private String countryCode;
@FormParam("number") private String number;
}
public static class Address {
@FormParam("street") private String street;
@FormParam("houseNumber") private String houseNumber;
50
}
@Path("person")
public static class MyResource {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void post (@Form Person p) {}
The following form params could be submitted and the Person.telephoneNumbers and
Person.addresses fields would be populated appropriately
request.addFormHeader("telephoneNumbers[0].countryCode", "31");
request.addFormHeader("telephoneNumbers[0].number", "0612345678");
request.addFormHeader("telephoneNumbers[1].countryCode", "91");
request.addFormHeader("telephoneNumbers[1].number", "9717738723");
request.addFormHeader("address[INVOICE].street", "Main Street");
request.addFormHeader("address[INVOICE].houseNumber", "2");
request.addFormHeader("address[SHIPPING].street", "Square One");
request.addFormHeader("address[SHIPPING].houseNumber", "13");
51
52
Chapter 13.
Chapter 13. Improved
annotations
@…Param
With the addition of parameter names in the bytecode since Java 8, it is no longer necessary
to require users to specify parameter names in the following annotations: @PathParam, @QueryParam, @FormParam, @CookieParam, @HeaderParam and @MatrixParam. In order to benefit from
this feature, you have to switch to new annotations with the same name, in a different package,
which have an optional value parameter. To use this, follow these steps:
• Import the org.jboss.resteasy.annotations.jaxrs package to replace annotations from
the JAX-RS spec.
• Tell your build system to record method parameter names in the bytecode.
• Remove the annotation value if the name matches the name of the annotated variable.
Note that you can omit the annotation name for annotated method parameters as well as annotated fields or JavaBean properties.
For Maven users, recording method parameter names in the bytecode can be enabled by setting
the maven.compiler.parameters to true:
true
Usage:
import org.jboss.resteasy.annotations.jaxrs.*;
@Path("/library")
public class Library {
@GET
@Path("/book/{isbn}")
public String getBook(@PathParam String isbn) {
// search my database and get a string representation and return it
}
}
53
Chapter 13. Improved @…Param ...
If your annotated variable does not have the same name as the path parameter, you can still
specify the name:
import org.jboss.resteasy.annotations.jaxrs.*;
@Path("/library")
public class Library {
@GET
@Path("/book/{isbn}")
public String getBook(@PathParam("isbn") String id) {
// search my database and get a string representation and return it
}
}
54
Chapter 14.
Chapter 14. @DefaultValue
@DefaultValue is a parameter annotation that can be combined with any of the other @*Param
annotations to define a default value when the HTTP request item does not exist.
@GET
public String getBooks(@QueryParam("num") @DefaultValue("10") int num) {...}
55
56
Chapter 15.
Chapter 15. @Encoded and
encoding
JAX-RS allows you to get encoded or decoded @*Params and specify path definitions and parameter names using encoded or decoded strings.
The @javax.ws.rs.Encoded annotation can be used on a class, method, or param. By default,
inject @PathParam and @QueryParams are decoded. By additionally adding the @Encoded annotation, the value of these params will be provided in encoded form.
@Path("/")
public class MyResource {
@Path("/{param}")
@GET
public String get(@PathParam("param") @Encoded String param) {...}
}
In the above example, the value of the @PathParam injected into the param of the get() method
will be URL encoded. Adding the @Encoded annotation as a paramater annotation triggers this
affect.
You may also use the @Encoded annotation on the entire method and any combination of
@QueryParam or @PathParam's values will be encoded.
@Path("/")
public class MyResource {
@Path("/{param}")
@GET
@Encoded
public String get(@QueryParam("foo") String foo, @PathParam("param") String
param) {}
}
In the above example, the values of the "foo" query param and "param" path param will be injected
as encoded values.
You can also set the default to be encoded for the entire class.
57
Chapter 15. @Encoded and encoding
@Path("/")
@Encoded
public class ClassEncoded {
@GET
public String get(@QueryParam("foo") String foo) {}
}
The @Path annotation has an attribute called encode. Controls whether the literal part of the
supplied value (those characters that are not part of a template variable) are URL encoded. If true,
any characters in the URI template that are not valid URI character will be automatically encoded.
If false then all characters must be valid URI characters. By default this is set to true. If you want
to encoded the characters yourself, you may.
@Path(value="hello%20world", encode=false)
Much like @Path.encode(), this controls whether the specified query param name should be encoded by the container before it tries to find the query param in the request.
@QueryParam(value="hello%20world", encode=false)
58
Chapter 16.
Chapter 16. @Context
The @Context annotation allows you to inject instances of
• javax.ws.rs.core.HttpHeaders
• javax.ws.rs.core.UriInfo
• javax.ws.rs.core.Request
• javax.servlet.http.HttpServletRequest
• javax.servlet.http.HttpServletResponse
• javax.servlet.ServletConfig
• javax.servlet.ServletContext
• javax.ws.rs.core.SecurityContext
objects.
59
60
Chapter 17.
Chapter 17. JAX-RS Resource
Locators and Sub Resources
Resource classes are able to partially process a request and provide another "sub" resource object
that can process the remainder of the request. For example:
@Path("/")
public class ShoppingStore {
@Path("/customers/{id}")
public Customer getCustomer(@PathParam("id") int id) {
Customer cust = ...; // Find a customer object
return cust;
}
}
public class Customer {
@GET
public String get() {...}
@Path("/address")
public String getAddress() {...}
}
Resource methods that have a @Path annotation, but no HTTP method are considered sub-resource locators. Their job is to provide an object that can process the request. In the above example ShoppingStore is a root resource because its class is annotated with @Path. The getCustomer() method is a sub-resource locator method.
If the client invoked:
GET /customer/123
The ShoppingStore.getCustomer() method would be invoked first. This method provides a Customer object that can service the request. The http request will be dispatched to the Customer.get()
method. Another example is:
GET /customer/123/address
61
Chapter 17. JAX-RS Resource L...
In this request, again, first the ShoppingStore.getCustomer() method is invoked. A customer object
is returned, and the rest of the request is dispatched to the Customer.getAddress() method.
Another interesting feature of Sub-resource locators is that the locator method result is
dynamically processed at runtime to figure out how to dispatch the request. So, the
ShoppingStore.getCustomer() method does not have to declare any specific type.
@Path("/")
public class ShoppingStore {
@Path("/customers/{id}")
public java.lang.Object getCustomer(@PathParam("id") int id) {
Customer cust = ...; // Find a customer object
return cust;
}
}
public class Customer {
@GET
public String get() {...}
@Path("/address")
public String getAddress() {...}
}
In the above example, getCustomer() returns a java.lang.Object. Per request, at runtime, the JAXRS server will figure out how to dispatch the request based on the object returned by getCustomer(). What are the uses of this? Well, maybe you have a class hierarchy for your customers.
Customer is the abstract base, CorporateCustomer and IndividualCustomer are subclasses. Your
getCustomer() method might be doing a Hibernate polymorphic query and doesn't know, or care,
what concrete class is it querying for, or what it returns.
@Path("/")
public class ShoppingStore {
@Path("/customers/{id}")
public java.lang.Object getCustomer(@PathParam("id") int id) {
Customer cust = entityManager.find(Customer.class, id);
return cust;
}
}
62
public class Customer {
@GET
public String get() {...}
@Path("/address")
public String getAddress() {...}
}
public class CorporateCustomer extends Customer {
@Path("/businessAddress")
public String getAddress() {...}
}
63
64
Chapter 18.
Chapter 18. Resources metadata
configuration
When processing JAX-RS deployments, RESTEasy relies on ResourceBuilder to create metadata for each JAX-RS resource. Such metadata is defined using the metadata SPI in package
org.jboss.resteasy.spi.metadata, in particular the ResourceClass interface:
package org.jboss.resteasy.spi.metadata;
public interface ResourceClass
{
String getPath();
Class getClazz();
ResourceConstructor getConstructor();
FieldParameter[] getFields();
SetterParameter[] getSetters();
ResourceMethod[] getResourceMethods();
ResourceLocator[] getResourceLocators();
}
Among the other classes and interfaces defining metadata SPI, the following interfaces are worth
a mention here:
public interface ResourceConstructor
{
ResourceClass getResourceClass();
Constructor getConstructor();
ConstructorParameter[] getParams();
}
public interface ResourceMethod extends ResourceLocator
{
Set getHttpMethods();
65
Chapter 18. Resources metadat...
MediaType[] getProduces();
MediaType[] getConsumes();
boolean isAsynchronous();
void markAsynchronous();
}
public interface ResourceLocator
{
ResourceClass getResourceClass();
Class getReturnType();
Type getGenericReturnType();
Method getMethod();
Method getAnnotatedMethod();
MethodParameter[] getParams();
String getFullpath();
String getPath();
}
Now, the interesting point is that RESTEasy allows tuning the metadata generation by providing
implementations of the ResourceClassProcessor interface:
package org.jboss.resteasy.spi.metadata;
public interface ResourceClassProcessor
{
/**
* Allows the implementation of this method to modify the resource metadata
represented by
* the supplied {@link ResourceClass} instance. Implementation will typically
create
* wrappers which modify only certain aspects of the metadata.
*
* @param clazz The original metadata
66
* @return the (potentially modified) metadata (never null)
*/
ResourceClass process(ResourceClass clazz);
}
The processors are meant to be, and are resolved as, regular JAX-RS annotated providers. They
allow for wrapping resource metadata classes with custom versions that can be used for various
advanced scenarios like
• adding additional resource method/locators to the resource
• altering the http methods
• altering the @Produces / @Consumes media types
• ...
67
68
Chapter 19.
Chapter 19. JAX-RS Content
Negotiation
The HTTP protocol has built in content negotiation headers that allow the client and server to
specify what content they are transferring and what content they would prefer to get. The server
declares content preferences via the @Produces and @Consumes headers.
@Consumes is an array of media types that a particular resource or resource method consumes.
For example:
@Consumes("text/*")
@Path("/library")
public class Library {
@POST
public String stringBook(String book) {...}
@Consumes("text/xml")
@POST
public String jaxbBook(Book book) {...}
}
When a client makes a request, JAX-RS first finds all methods that match the path, then, it sorts
things based on the content-type header sent by the client. So, if a client sent:
POST /library
Content-Type: text/plain
This is a nice book
The stringBook() method would be invoked because it matches to the default "text/*" media type.
Now, if the client instead sends XML:
POST /library
Content-Type: text/xml
69
Chapter 19. JAX-RS Content Ne...
The jaxbBook() method would be invoked.
The @Produces is used to map a client request and match it up to the client's Accept header.
The Accept HTTP header is sent by the client and defines the media types the client prefers to
receive from the server.
@Produces("text/*")
@Path("/library")
public class Library {
@GET
@Produces("application/json")
public String getJSON() {...}
@GET
public String get() {...}
So, if the client sends:
GET /library
Accept: application/json
The getJSON() method would be invoked.
@Consumes and @Produces can list multiple media types that they support. The client's Accept
header can also send multiple types it might like to receive. More specific media types are chosen
first. The client Accept header or @Produces @Consumes can also specify weighted preferences
that are used to match up requests with resource methods. This is best explained by RFC 2616
section 14.1 . RESTEasy supports this complex way of doing content negotiation.
A variant in JAX-RS is a combination of media type, content-language, and content encoding as well as etags, last modified headers, and other preconditions. This is a more complex
form of content negotiation that is done programmatically by the application developer using the
javax.ws.rs.Variant, VarianListBuilder, and Request objects. Request is injected via @Context.
Read the javadoc for more info on these.
19.1. URL-based negotiation
Some clients, like browsers, cannot use the Accept and Accept-Language headers to negotiation the representation's media type or language. RESTEasy allows you to map file name
suffixes like (.xml, .txt, .en, .fr) to media types and languages. These file name suffixes take
the place and override any Accept header sent by the client. You configure this using the
70
Query String Parameter-based negotiation
resteasy.media.type.mappings and resteasy.language.mappings context-param variables within
your web.xml.
Archetype Created Web Application
resteasy.media.type.mappings
html : text/html, json : application/json, xml : application/
xml
resteasy.language.mappings
en : en-US, es : es, fr : fr
...
Mappings are a comma delimited list of suffix/mediatype or suffix/language mappings. Each mapping is delimited by a ':'. So, if you invoked GET /foo/bar.xml.en, this would be equivalent to invoking the following request:
GET /foo/bar
Accept: application/xml
Accept-Language: en-US
The mapped file suffixes are stripped from the target URL path before the request is dispatched
to a corresponding JAX-RS resource.
19.2. Query String Parameter-based negotiation
RESTEasy can do content negotiation based in a parameter in query string. To enable this, the
web.xml can be configured like follow:
Archetype Created Web Application
resteasy.media.type.param.mapping
someName
71
Chapter 19. JAX-RS Content Ne...
...
The param-value is the name of the query string parameter that RESTEasy will use in the place
of the Accept header.
Invoking http://service.foo.com/resouce?someName=application/xml, will give the application/xml
media type the highest priority in the content negotiation.
In cases where the request contains both the parameter and the Accept header, the parameter
will be more relevant.
It is possible to left the param-value empty, what will cause the processor to look for a parameter
named 'accept'.
72
Chapter 20.
Chapter 20. Content Marshalling/
Providers
20.1. Default Providers and default JAX-RS Content
Marshalling
RESTEasy can automatically marshal and unmarshal a few different message bodies.
Table 20.1.
Media Types
Java Type
application/*+xml, text/*+xml, application/* JaxB annotated classes
+json,
application/*+fastinfoset,
application/atom+*
application/*+xml, text/*+xml
org.w3c.dom.Document
*/*
java.lang.String
*/*
java.io.InputStream
text/plain
primitives, java.lang.String, or any type
that has a String constructor, or static
valueOf(String) method for input, toString() for
output
*/*
javax.activation.DataSource
*/*
java.io.File
*/*
byte[]
application/x-www-form-urlencoded
javax.ws.rs.core.MultivaluedMap
Note. When a java.io.File is created, as in
@Path("/test")
public class TempFileDeletionResource
{
@POST
@Path("post")
public Response post(File file) throws Exception
{
return Response.ok(file.getPath()).build();
}
}
73
Chapter 20. Content Marshalli...
a temporary file is created in the file system. On the server side, that temporary file will be deleted
at the end of the invocation. On the client side, however, it is the responsibility of the user to delete
the temporary file.
20.2. Content Marshalling with @Provider classes
The JAX-RS specification allows you to plug in your own request/response body reader and writers. To do this, you annotate a class with @Provider and specify the @Produces types for a writer
and @Consumes types for a reader. You must also implement a MessageBodyReader/Writer
interface respectively. Here is an example:
@Provider
@Produces("text/plain")
@Consumes("text/plain")
public class DefaultTextPlain
MessageBodyWriter {
implements
MessageBodyReader,
public boolean isReadable(Class type, Type genericType, Annotation[]
annotations, MediaType mediaType) {
// StringTextStar should pick up strings
return
!String.class.equals(type)
&&
TypeConverter.isConvertable(type);
}
public Object readFrom(Class type, Type genericType,
Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
InputStream delegate = NoContent.noContentCheck(httpHeaders,
entityStream);
String value = ProviderHelper.readString(delegate, mediaType);
return TypeConverter.getType(type, value);
}
public boolean isWriteable(Class type, Type genericType, Annotation[]
annotations, MediaType mediaType) {
// StringTextStar should pick up strings
return !String.class.equals(type) && !type.isArray();
}
public long getSize(Object o, Class type, Type genericType, Annotation[]
annotations, MediaType mediaType) {
String charset = mediaType.getParameters().get("charset");
if (charset != null)
74
Providers Utility Class
try {
return o.toString().getBytes(charset).length;
} catch (UnsupportedEncodingException e) {
// Use default encoding.
}
return o.toString().getBytes(StandardCharsets.UTF_8).length;
}
public void writeTo(Object o, Class type, Type genericType, Annotation[]
annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream
entityStream) throws IOException, WebApplicationException {
String charset = mediaType.getParameters().get("charset");
if
(charset
==
null)
entityStream.write(o.toString().getBytes(StandardCharsets.UTF_8));
else entityStream.write(o.toString().getBytes(charset));
}
}
The RESTEasy ServletContextLoader will automatically scan your WEB-INF/lib and classes directories for classes annotated with @Provider or you can manually configure them in web.xml.
See Installation/Configuration.
20.3. Providers Utility Class
javax.ws.rs.ext.Providers is a simple injectable interface that allows you to look up MessageBodyReaders, Writers, ContextResolvers, and ExceptionMappers. It is very useful, for instance,
for implementing multipart providers. Content types that embed other random content types.
public interface Providers
{
/**
* Get a message body reader that matches a set of criteria. The set of
* readers is first filtered by comparing the supplied value of
* {@code mediaType} with the value of each reader's
* {@link javax.ws.rs.Consumes}, ensuring the supplied value of
* {@code type} is assignable to the generic type of the reader, and
* eliminating those that do not match.
* The list of matching readers is then ordered with those with the best
* matching values of {@link javax.ws.rs.Consumes} (x/y > x/* > */*)
* sorted first. Finally, the
* {@link MessageBodyReader#isReadable}
* method is called on each reader in order using the supplied criteria and
* the first reader that returns {@code true} is selected and returned.
75
Chapter 20. Content Marshalli...
*
* @param type
the class of object that is to be written.
* @param mediaType
the media type of the data that will be read.
* @param genericType the type of object to be produced. E.g. if the
*
message body is to be converted into a method
parameter, this will be
*
the formal type of the method parameter as returned by
*
Class.getGenericParameterTypes
.
* @param annotations an array of the annotations on the declaration of the
*
artifact that will be initialized with the produced
instance. E.g. if the
*
message body is to be converted into a method
parameter, this will be
*
the annotations on that parameter returned by
*
Class.getParameterAnnotations
.
* @return a MessageBodyReader that matches the supplied criteria or null
*
if none is found.
*/
MessageBodyReader getMessageBodyReader(Class type,
Type genericType, Annotation
annotations[], MediaType mediaType);
/**
* Get a message body writer that matches a set of criteria. The set of
* writers is first filtered by comparing the supplied value of
* {@code mediaType} with the value of each writer's
* {@link javax.ws.rs.Produces}, ensuring the supplied value of
* {@code type} is assignable to the generic type of the reader, and
* eliminating those that do not match.
* The list of matching writers is then ordered with those with the best
* matching values of {@link javax.ws.rs.Produces} (x/y > x/* > */*)
* sorted first. Finally, the
* {@link MessageBodyWriter#isWriteable}
* method is called on each writer in order using the supplied criteria and
* the first writer that returns {@code true} is selected and returned.
*
* @param mediaType
the media type of the data that will be written.
* @param type
the class of object that is to be written.
* @param genericType the type of object to be written. E.g. if the
*
message body is to be produced from a field, this
*
the declared type of the field as returned by
*
Field.getGenericType
.
* @param annotations an array of the annotations on the declaration
*
artifact that will be written. E.g. if the
*
message body is to be produced from a field, this
*
the annotations on that field returned by
*
Field.getDeclaredAnnotations
.
* @return a MessageBodyReader that matches the supplied criteria or
*
if none is found.
76
will be
of the
will be
null
Providers Utility Class
*/
MessageBodyWriter getMessageBodyWriter(Class type,
Type genericType, Annotation
annotations[], MediaType mediaType);
/**
* Get an exception mapping provider for a particular class of exception.
* Returns the provider whose generic type is the nearest superclass of
* {@code type}.
*
* @param type the class of exception
* @return an {@link ExceptionMapper} for the supplied type or null if none
*
is found.
*/
ExceptionMapper getExceptionMapper(Class type);
/**
* Get a context resolver for a particular type of context and media type.
* The set of resolvers is first filtered by comparing the supplied value of
* {@code mediaType} with the value of each resolver's
* {@link javax.ws.rs.Produces}, ensuring the generic type of the context
* resolver is assignable to the supplied value of {@code contextType}, and
* eliminating those that do not match. If only one resolver matches the
* criteria then it is returned. If more than one resolver matches then the
* list of matching resolvers is ordered with those with the best
* matching values of {@link javax.ws.rs.Produces} (x/y > x/* > */*)
* sorted first. A proxy is returned that delegates calls to
* {@link ContextResolver#getContext(java.lang.Class)} to each matching context
* resolver in order and returns the first non-null value it obtains or null
* if all matching context resolvers return null.
*
* @param contextType the class of context desired
* @param mediaType
the media type of data for which a context is required.
* @return a matching context resolver instance or null if no matching
*
context providers are found.
*/
ContextResolver getContextResolver(Class contextType,
MediaType mediaType);
}
A Providers instance is injectable into MessageBodyReader or Writers:
@Provider
@Consumes("multipart/fixed")
public class MultipartProvider implements MessageBodyReader {
77
Chapter 20. Content Marshalli...
private @Context Providers providers;
...
}
20.4. Configuring Document Marshalling
XML document parsers are subject to a form of attack known as the XXE (Xml eXternal Entity)
Attack (http://www.securiteam.com/securitynews/6D0100A5PU.html), in which expanding an external entity causes an unsafe file to be loaded. For example, the document
]>
bill
&xxe;
could cause the passwd file to be loaded.
By default, RESTEasy's built-in unmarshaller for org.w3c.dom.Document documents will not expand external entities, replacing them by the empty string instead. It can be configured to replace
external entities by values defined in the DTD by setting the context parameter
to "true" in the web.xml file:
resteasy.document.expand.entity.references
true
Another way of dealing with the problem is by prohibiting DTDs, which RESTEasy does by default.
This behavior can be changed by setting the context parameter
to "false".
Documents are also subject to Denial of Service Attacks when buffers are overrun by large entities
or too many attributes. For example, if a DTD defined the following entities
78
Text media types and character sets
foo1 '&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;&foo;'>
foo2 '&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;&foo1;'>
foo3 '&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;&foo2;'>
foo4 '&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;&foo3;'>
foo5 '&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;&foo4;'>
foo6 '&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;&foo5;'>
then the expansion of &foo6; would result in 1,000,000 foos. By default, RESTEasy will limit the
number of expansions and the number of attributes per entity. The exact behavior depends on
the underlying parser. The limits can be turned off by setting the context parameter
to "false".
20.5. Text media types and character sets
The JAX-RS specification says
When writing responses, implementations SHOULD respect application-supplied
character
set metadata and SHOULD use UTF-8 if a character set is not specified by the
application
or if the application specifies a character set that is unsupported.
On the other hand, the HTTP specification says
When no explicit charset parameter is provided by the sender, media subtypes
of the
"text" type are defined to have a default charset value of "ISO-8859-1" when
received
via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST
be labeled
with an appropriate charset value.
It follows that, in the absence of a character set specified by a resource or resource method,
RESTEasy SHOULD use UTF-8 as the character set for text media types, and, if it does, it
MUST add an explicit charset parameter to the Content-Type response header. RESTEasy started adding the explicit charset parameter in releases 3.1.2.Final and 3.0.22.Final, and that new
behavior could cause some compatibility problems. To specify the previous behavior, in which
79
Chapter 20. Content Marshalli...
UTF-8 was used for text media types, but the explicit charset was not appended, the context parameter "resteasy.add.charset" may be set to "false". It defaults to "true".
Note. By "text" media types, we mean
• a media type with type "text" and any subtype;
• a media type with type ""application" and subtype beginning with "xml".
The latter set includes "application/xml-external-parsed-entity" and "application/xml-dtd".
80
Chapter 21.
Chapter 21. JAXB providers
As required by the specification, RESTEasy JAX-RS includes support for (un)marshalling JAXB
annotated classes. RESTEasy provides multiple JAXB Providers to address some subtle differences between classes generated by XJC and classes which are simply annotated with @XmlRootElement, or working with JAXBElement classes directly.
For the most part, developers using the JAX-RS API, the selection of which provider is invoked
will be completely transparent. For developers wishing to access the providers directly (which
most folks won't need to do), this document describes which provider is best suited for different
configurations.
A JAXB Provider is selected by RESTEasy when a parameter or return type is an object that
is annotated with JAXB annotations (such as @XmlRootEntity or @XmlType) or if the type is a
JAXBElement. Additionally, the resource class or resource method will be annotated with either
a @Consumes or @Produces annotation and contain one or more of the following values:
• text/*+xml
• application/*+xml
• application/*+fastinfoset
• application/*+json
RESTEasy will select a different provider based on the return type or parameter type used in the
resource. This section describes how the selection process works.
@XmlRootEntity When a class is annotated with a @XmlRootElement annotation, RESTEasy will
select the JAXBXmlRootElementProvider. This provider handles basic marshaling and unmarshalling of custom JAXB entities.
@XmlType Classes which have been generated by XJC will most likely not contain an @XmlRootEntity annotation. In order for these classes to marshalled, they must be wrapped within a
JAXBElement instance. This is typically accomplished by invoking a method on the class which
serves as the XmlRegistry and is named ObjectFactory.
The JAXBXmlTypeProvider provider is selected when the class is annotated with an XmlType
annotation and not an XmlRootElement annotation.
This provider simplifies this task by attempting to locate the XmlRegistry for the target class. By
default, a JAXB implementation will create a class called ObjectFactory and is located in the same
package as the target class. When this class is located, it will contain a "create" method that takes
the object instance as a parameter. For example, if the target type is called "Contact", then the
ObjectFactory class will have a method:
public JAXBElement createContact(Contact value) {..
81
Chapter 21. JAXB providers
JAXBElement If your resource works with the JAXBElement class directly, the RESTEasy
runtime will select the JAXBElementProvider. This provider examines the ParameterizedType
value of the JAXBElement in order to select the appropriate JAXBContext.
21.1. JAXB Decorators
Resteasy's JAXB providers have a pluggable way to decorate Marshaller and Unmarshaller instances. The way it works is that you can write an annotation that can trigger the decoration of
a Marshaller or Unmarshaller. Your decorators can do things like set Marshaller or Unmarshaller
properties, set up validation, stuff like that. Here's an example. Let's say we want to have an annotation that will trigger pretty-printing, nice formatting, of an XML document. If we were doing raw
JAXB, we would set a property on the Marshaller of Marshaller.JAXB_FORMATTED_OUTPUT.
Let's write a Marshaller decorator.
First we define a annotation:
import org.jboss.resteasy.annotations.Decorator;
@Target({ElementType.TYPE,
ElementType.METHOD,
ElementType.PARAMETER,
ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Decorator(processor = PrettyProcessor.class, target = Marshaller.class)
public @interface Pretty {}
To get this to work, we must annotate our @Pretty annotation with a meta-annotation called @Decorator. The target() attribute must be the JAXB Marshaller class. The processor() attribute is a
class we will write next.
import org.jboss.resteasy.core.interception.DecoratorProcessor;
import org.jboss.resteasy.annotations.DecorateTypes;
import
import
import
import
import
javax.xml.bind.Marshaller;
javax.xml.bind.PropertyException;
javax.ws.rs.core.MediaType;
javax.ws.rs.Produces;
java.lang.annotation.Annotation;
/**
* @author Bill Burke
* @version $Revision: 1 $
*/
@DecorateTypes({"text/*+xml", "application/*+xml"})
82
Pluggable JAXBContext's with ContextResolvers
public class PrettyProcessor implements DecoratorProcessor
{
public Marshaller decorate(Marshaller target, Pretty annotation,
Class type, Annotation[] annotations, MediaType mediaType)
{
target.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
}
}
The processor implementation must implement the DecoratorProcessor interface and should also
be annotated with @DecorateTypes. This annotation specifies what media types the processor
can be used with. Now that we've defined our annotation and our Processor, we can use it on our
JAX-RS resource methods or JAXB types as follows:
@GET
@Pretty
@Produces("application/xml")
public SomeJAXBObject get() {...}
If you are confused, check the RESTEasy source code for the implementation of @XmlHeader
21.2. Pluggable JAXBContext's with ContextResolvers
You should not use this feature unless you know what you're doing.
Based on the class you are marshalling/unmarshalling, RESTEasy will, by default create and
cache JAXBContext instances per class type. If you do not want RESTEasy to create JAXBContexts, you can plug-in your own by implementing an instance of javax.ws.rs.ext.ContextResolver
public interface ContextResolver
{
T getContext(Class type);
}
@Provider
@Produces("application/xml")
public class MyJAXBContextResolver implements ContextResolver
{
JAXBContext getContext(Class type)
{
if (type.equals(WhateverClassIsOverridedFor.class)) return
JAXBContext.newInstance()...;
}
83
Chapter 21. JAXB providers
}
You must provide a @Produces annotation to specify the media type the context is meant for.
You must also make sure to implement ContextResolver. This helps the runtime
match to the correct context resolver. You must also annotate the ContextResolver class with
@Provider.
There are multiple ways to make this ContextResolver available.
1. Return it as a class or instance from a javax.ws.rs.core.Application implementation
2. List it as a provider with resteasy.providers
3. Let RESTEasy automatically scan for it within your WAR file. See Configuration Guide
4. Manually add it via ResteasyProviderFactory.getInstance().registerProvider(Class)
registerProviderInstance(Object)
or
21.3. JAXB + XML provider
RESTEasy is required to provide JAXB provider support for XML. It has a few extra annotations
that can help code your app.
21.3.1. @XmlHeader and @Stylesheet
Sometimes when outputting XML documents you may want to set an XML header. RESTEasy
provides the @org.jboss.resteasy.annotations.providers.jaxb.XmlHeader annotation for this. For
example:
@XmlRootElement
public static class Thing
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
84
@XmlHeader and @Stylesheet
@Path("/test")
public static class TestService
{
@GET
@Path("/header")
@Produces("application/xml")
@XmlHeader("")
public Thing get()
{
Thing thing = new Thing();
thing.setName("bill");
return thing;
}
}
The @XmlHeader here forces the XML output to have an xml-stylesheet header. This header
could also have been put on the Thing class to get the same result. See the javadocs for more
details on how you can use substitution values provided by resteasy.
RESTEasy also has a convenience annotation for stylesheet headers. For example:
@XmlRootElement
public static class Thing
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
@Path("/test")
public static class TestService
{
@GET
@Path("/stylesheet")
@Produces("application/xml")
@Stylesheet(type="text/css", href="${basepath}foo.xsl")
@Junk
public Thing getStyle()
85
Chapter 21. JAXB providers
{
Thing thing = new Thing();
thing.setName("bill");
return thing;
}
}
21.4. JAXB + JSON provider
RESTEasy allows you to marshall JAXB annotated POJOs to and from JSON. This provider wraps
the Jettison JSON library to accomplish this. You can obtain more information about Jettison and
how it works from https://github.com/jettison-json/jettison.
To use this integration with Jettision you need to import the resteasy-jettison-provider Maven module. Older versions of RESTEasy used to include this within the resteasy-jaxb-provider but we
decided to modularize it more.
Jettison has two mapping formats. One is BadgerFish the other is a Jettison Mapped Convention
format. The Mapped Convention is the default mapping.
For example, consider this JAXB class:
@XmlRootElement(name = "book")
public class Book
{
private String author;
private String ISBN;
private String title;
public Book()
{
}
public Book(String author, String ISBN, String title)
{
this.author = author;
this.ISBN = ISBN;
this.title = title;
}
@XmlElement
public String getAuthor()
{
return author;
}
86
JAXB + JSON provider
public void setAuthor(String author)
{
this.author = author;
}
@XmlElement
public String getISBN()
{
return ISBN;
}
public void setISBN(String ISBN)
{
this.ISBN = ISBN;
}
@XmlAttribute
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
}
This is how the JAXB Book class would be marshalled to JSON using the BadgerFish Convention:
{"book":
{
"@title":"EJB 3.0",
"author":{"$":"Bill Burke"},
"ISBN":{"$":"596529260"}
}
}
Notice that element values have a map associated with them and to get to the value of the element,
you must access the "$" variable. Here's an example of accessing the book in Javascript:
var data = eval("(" + xhr.responseText + ")");
document.getElementById("zone").innerHTML = data.book.@title;
87
Chapter 21. JAXB providers
document.getElementById("zone").innerHTML += data.book.author.$;
To
use
the
BadgerFish
Convention
you
must
use
the
@org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish annotation on the JAXB class
you are marshalling/unmarshalling, or, on the JAX-RS resource method or parameter:
@BadgerFish
@XmlRootElement(name = "book")
public class Book {...}
If you are returning a book on the JAX-RS method and you don't want to (or can't) pollute your
JAXB classes with RESTEasy annotations, add the annotation to the JAX-RS method:
@BadgerFish
@GET
public Book getBook(...) {...}
If a Book is your input then you put it on the parameter:
@POST
public void newBook(@BadgerFish Book book) {...}
The default Jettison Mapped Convention would return JSON that looked like this:
{ "book" :
{
"@title":"EJB 3.0",
"author":"Bill Burke",
"ISBN":596529260
}
}
Notice that the @XmlAttribute "title" is prefixed with the '@' character. Unlike BadgerFish, the '$'
does not represent the value of element text. This format is a bit simpler than the BadgerFish convention which is why it was chose as a default. Here's an example of accessing this in Javascript:
88
JAXB + JSON provider
var data = eval("(" + xhr.responseText + ")");
document.getElementById("zone").innerHTML = data.book.@title;
document.getElementById("zone").innerHTML += data.book.author;
The Mapped Convention allows you to fine tune the JAXB mapping using the
@org.jboss.resteasy.annotations.providers.jaxb.json.Mapped annotation. You can provide an
XML Namespace to JSON namespace mapping. For example, if you defined your JAXB namespace within your package-info.java class like this:
@javax.xml.bind.annotation.XmlSchema(namespace="http://jboss.org/books")
package org.jboss.resteasy.test.books;
You would have to define a JSON to XML namespace mapping or you would receive an exception
of something like this:
java.lang.IllegalStateException: Invalid JSON namespace: http://jboss.org/books
at
org.codehaus.jettison.mapped.MappedNamespaceConvention.getJSONNamespace(MappedNamespaceConvent
at
org.codehaus.jettison.mapped.MappedNamespaceConvention.createKey(MappedNamespaceConvention.jav
at
org.codehaus.jettison.mapped.MappedXMLStreamWriter.writeStartElement(MappedXMLStreamWriter.jav
To fix this problem you need another annotation, @Mapped. You use the @Mapped annotation on
your JAXB classes, on your JAX-RS resource method, or on the parameter you are unmarshalling
import org.jboss.resteasy.annotations.providers.jaxb.json.Mapped;
import org.jboss.resteasy.annotations.providers.jaxb.json.XmlNsMap;
...
@GET
@Produces("application/json")
@Mapped(namespaceMap = {
@XmlNsMap(namespace = "http://jboss.org/books", jsonName = "books")
})
public Book get() {...}
89
Chapter 21. JAXB providers
Besides mapping XML to JSON namespaces, you can also force @XmlAttribute's to be marshaled
as XMLElements.
@Mapped(attributeAsElements={"title"})
@XmlRootElement(name = "book")
public class Book {...}
If you are returning a book on the JAX-RS method and you don't want to (or can't) pollute your
JAXB classes with RESTEasy annotations, add the annotation to the JAX-RS method:
@Mapped(attributeAsElements={"title"})
@GET
public Book getBook(...) {...}
If a Book is your input then you put it on the parameter:
@POST
public void newBook(@Mapped(attributeAsElements={"title"}) Book book) {...}
21.5. JAXB + FastinfoSet provider
RESTEasy supports the FastinfoSet mime type with JAXB annotated classes. Fast infoset documents are faster to serialize and parse, and smaller in size, than logically equivalent XML documents. Thus, fast infoset documents may be used whenever the size and processing time of XML
documents is an issue. It is configured the same way the XML JAXB provider is so really no other
documentation is needed here.
To use this integration with Fastinfoset you need to import the resteasy-fastinfoset-provider Maven
module. Older versions of RESTEasy used to include this within the resteasy-jaxb-provider but
we decided to modularize it more.
21.6. Arrays and Collections of JAXB Objects
RESTEasy will automatically marshal arrays, java.util.Set's, and java.util.List's of JAXB objects to
and from XML, JSON, Fastinfoset (or any other new JAXB mapper Restasy comes up with).
90
Arrays and Collections of JAXB Objects
@XmlRootElement(name = "customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer
{
@XmlElement
private String name;
public Customer()
{
}
public Customer(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
@Path("/")
public class MyResource
{
@PUT
@Path("array")
@Consumes("application/xml")
public void putCustomers(Customer[] customers)
{
Assert.assertEquals("bill", customers[0].getName());
Assert.assertEquals("monica", customers[1].getName());
}
@GET
@Path("set")
@Produces("application/xml")
public Set getCustomerSet()
{
HashSet set = new HashSet();
set.add(new Customer("bill"));
set.add(new Customer("monica"));
return set;
}
@PUT
91
Chapter 21. JAXB providers
@Path("list")
@Consumes("application/xml")
public void putCustomers(List customers)
{
Assert.assertEquals("bill", customers.get(0).getName());
Assert.assertEquals("monica", customers.get(1).getName());
}
}
The above resource can publish and receive JAXB objects. It is assumed that are wrapped in a
collection element
bill
monica
You can change the namespace URI, namespace tag, and collection element name by using the
@org.jboss.resteasy.annotations.providers.jaxb.Wrapped annotation on a parameter or method
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Wrapped
{
String element() default "collection";
String namespace() default "http://jboss.org/resteasy";
String prefix() default "resteasy";
}
So, if we wanted to output this XML
bill
monica
We would use the @Wrapped annotation as follows:
92
Retrieving Collections on the client side
@GET
@Path("list")
@Produces("application/xml")
@Wrapped(element="list", namespace="http://foo.org", prefix="foo")
public List getCustomerSet()
{
List list = new ArrayList();
list.add(new Customer("bill"));
list.add(new Customer("monica"));
return list;
}
21.6.1. Retrieving Collections on the client side
If you try to retrieve a List or Set of JAXB objects in the obvious way on the client side:
Response response = request.get();
List list = response.readEntity(List.class);
the call to readEntity() will fail because it has no way of knowing the element type Customer.
The trick is to use an instance of javax.ws.rs.core.GenericType:
Response response = request.get();
GenericType> genericType = new GenericType>()
{};
List list = response.readEntity(genericType);
For more information about GenericType, please see its javadoc.
The same trick applies to retrieving a Set:
Response response = request.get();
GenericType> genericType = new GenericType>()
{};
Set set = response.readEntity(genericType);
On the other hand, GenericType is not necessary to retrieve an array of JAXB objects:
93
Chapter 21. JAXB providers
Response response = request.get();
Customer[] array = response.readEntity(Customer[].class);
21.6.2. JSON and JAXB Collections/arrays
RESTEasy supports using collections with JSON. It encloses lists, sets, or arrays of returned
JAXB objects within a simple JSON array. For example:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public static class Foo
{
@XmlAttribute
private String test;
public Foo()
{
}
public Foo(String test)
{
this.test = test;
}
public String getTest()
{
return test;
}
public void setTest(String test)
{
this.test = test;
}
}
This a List or array of this Foo class would be represented in JSON like this:
[{"foo":{"@test":"bill"}},{"foo":{"@test":"monica}"}}]
It also expects this format for input
94
Maps of JAXB Objects
21.7. Maps of JAXB Objects
RESTEasy will automatically marshal maps of JAXB objects to and from XML, JSON, Fastinfoset
(or any other new JAXB mapper Restasy comes up with). Your parameter or method return type
must be a generic with a String as the key and the JAXB object's type.
@XmlRootElement(namespace = "http://foo.com")
public static class Foo
{
@XmlAttribute
private String name;
public Foo()
{
}
public Foo(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
@Path("/map")
public static class MyResource
{
@POST
@Produces("application/xml")
@Consumes("application/xml")
public Map post(Map map)
{
Assert.assertEquals(2, map.size());
Assert.assertNotNull(map.get("bill"));
Assert.assertNotNull(map.get("monica"));
Assert.assertEquals(map.get("bill").getName(), "bill");
Assert.assertEquals(map.get("monica").getName(), "monica");
return map;
}
}
95
Chapter 21. JAXB providers
The above resource can publish and receive JAXB objects within a map. By default, they are
wrapped in a "map" element in the default namespace. Also, each "map" element has zero or
more "entry" elements with a "key" attribute.
You can change the namespace URI, namespace prefix and map, entry, and key element and attribute names by using the @org.jboss.resteasy.annotations.providers.jaxb.WrappedMap annotation on a parameter or method
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface WrappedMap
{
/**
* map element name
*/
String map() default "map";
/**
* entry element name *
*/
String entry() default "entry";
/**
* entry's key attribute name
*/
String key() default "key";
String namespace() default "";
String prefix() default "";
}
So, if we wanted to output this XML
96
Retrieving Maps on the client side
We would use the @WrappedMap annotation as follows:
@Path("/map")
public static class MyResource
{
@GET
@Produces("application/xml")
@WrappedMap(map="hashmap", entry="hashentry", key="hashkey")
public Map get()
{
...
return map;
}
}
21.7.1. Retrieving Maps on the client side
If you try to retrieve a Map of JAXB objects in the obvious way on the client side:
Response response = request.get();
Map map = response.readEntity(Map.class);
the call to readEntity() will fail because it has no way of knowing the element type Customer.
The trick is to use an instance of javax.ws.rs.core.GenericType:
Response response = request.get();
GenericType genericType = new GenericType>() {};
Map map = response.readEntity(genericType);
For more information about GenericType, please see its javadoc.
97
Chapter 21. JAXB providers
21.7.2. JSON and JAXB maps
RESTEasy supports using maps with JSON. It encloses maps returned JAXB objects within a
simple JSON map. For example:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public static class Foo
{
@XmlAttribute
private String test;
public Foo()
{
}
public Foo(String test)
{
this.test = test;
}
public String getTest()
{
return test;
}
public void setTest(String test)
{
this.test = test;
}
}
This a List or array of this Foo class would be represented in JSON like this:
{ "entry1" : {"foo":{"@test":"bill"}}, "entry2" : {"foo":{"@test":"monica}"}}}
It also expects this format for input
21.7.3. Possible Problems with Jettison Provider
If you have the resteasy-jackson-provider-xxx.jar in your classpath, the Jackson JSON provider
will be triggered. This will screw up code that is dependent on the Jettison JAXB/JSon provider.
98
Interfaces, Abstract Classes, and JAXB
If you had been using the Jettison JAXB/Json providers, you must either remove Jackson from
your WEB-INF/lib or classpath, or use the @NoJackson annotation on your JAXB classes.
21.8. Interfaces, Abstract Classes, and JAXB
Some objects models use abstract classes and interfaces heavily. Unfortunately, JAXB doesn't
work with interfaces that are root elements and RESTEasy can't unmarshal parameters that are
interfaces or raw abstract classes because it doesn't have enough information to create a JAXBContext. For example:
public interface IFoo {}
@XmlRootElement
public class RealFoo implements IFoo {}
@Path("/jaxb")
public class MyResource {
@PUT
@Consumes("application/xml")
public void put(IFoo foo) {...}
}
In this example, you would get an error from RESTEasy of something like "Cannot find a MessageBodyReader for...". This is because RESTEasy does not know that implementations of IFoo are
JAXB classes and doesn't know how to create a JAXBContext for it. As a workaround, RESTEasy
allows you to use the JAXB annotation @XmlSeeAlso on the interface to correct the problem.
(NOTE, this will not work with manual, hand-coded JAXB).
@XmlSeeAlso(RealFoo.class)
public interface IFoo {}
The extra @XmlSeeAlso on IFoo allows RESTEasy to create a JAXBContext that knows how to
unmarshal RealFoo instances.
21.9. Configurating JAXB Marshalling
As a consumer of XML datasets, JAXB is subject to a form of attack known as the XXE (Xml eXternal Entity) Attack (http://www.securiteam.com/securitynews/6D0100A5PU.html), in which expanding an external entity causes an unsafe file to be loaded. Preventing the expansion of external entities is discussed in Section 20.4, “Configuring Document Marshalling”. The same context
parameter,
99
Chapter 21. JAXB providers
applies to JAXB unmarshallers as well.
Section 20.4, “Configuring Document Marshalling” also discusses the prohibition of DTDs and the
imposition of limits on entity expansion and the number of attributes per element. The context
parameters
and
discussed there, and their default values, also apply to the representation of JAXB objects.
100
Chapter 22.
Chapter 22. RESTEasy Atom
Support
From W3.org (http://tools.ietf.org/html/rfc4287):
"Atom is an XML-based document format that describes lists of related information known as
"feeds". Feeds are composed of a number of items, known as "entries", each with an extensible
set of attached metadata. For example, each entry has a title. The primary use case that Atom
addresses is the syndication of Web content such as weblogs and news headlines to Web sites
as well as directly to user agents."
Atom is the next-gen RSS feed. Although it is used primarily for the syndication of blogs and news,
many are starting to use this format as the envelope for Web Services, for example, distributed
notifications, job queues, or simply a nice format for sending or receiving data in bulk from a
service.
22.1. RESTEasy Atom API and Provider
RESTEasy has defined a simple object model in Java to represent Atom and uses JAXB to marshal and unmarshal it. The main classes are in the org.jboss.resteasy.plugins.providers.atom
package and are Feed, Entry, Content, and Link. If you look at the source, you'd see that these are
annotated with JAXB annotations. The distribution contains the javadocs for this project and are a
must to learn the model. Here is a simple example of sending an atom feed using the RESTEasy
API.
import
import
import
import
import
org.jboss.resteasy.plugins.providers.atom.Content;
org.jboss.resteasy.plugins.providers.atom.Entry;
org.jboss.resteasy.plugins.providers.atom.Feed;
org.jboss.resteasy.plugins.providers.atom.Link;
org.jboss.resteasy.plugins.providers.atom.Person;
@Path("atom")
public class MyAtomService
{
@GET
@Path("feed")
@Produces("application/atom+xml")
public Feed getFeed() throws URISyntaxException
{
Feed feed = new Feed();
feed.setId(new URI("http://example.com/42"));
feed.setTitle("My Feed");
feed.setUpdated(new Date());
101
Chapter 22. RESTEasy Atom Support
Link link = new Link();
link.setHref(new URI("http://localhost"));
link.setRel("edit");
feed.getLinks().add(link);
feed.getAuthors().add(new Person("Bill Burke"));
Entry entry = new Entry();
entry.setTitle("Hello World");
Content content = new Content();
content.setType(MediaType.TEXT_HTML_TYPE);
content.setText("Nothing much");
entry.setContent(content);
feed.getEntries().add(entry);
return feed;
}
}
Because RESTEasy's atom provider is JAXB based, you are not limited to sending atom objects using XML. You can automatically re-use all the other JAXB providers that RESTEasy has
like JSON and fastinfoset. All you have to do is have "atom+" in front of the main subtype. i.e.
@Produces("application/atom+json") or @Consumes("application/atom+fastinfoset")
22.2. Using JAXB with the Atom Provider
The org.jboss.resteasy.plugins.providers.atom.Content class allows you to unmarshal and marshal JAXB annotated objects that are the body of the content. Here's an example of sending an
Entry with a Customer object attached as the body of the entry's content.
@XmlRootElement(namespace = "http://jboss.org/Customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer
{
@XmlElement
private String name;
public Customer()
{
}
public Customer(String name)
{
this.name = name;
}
public String getName()
{
return name;
102
Using JAXB with the Atom Provider
}
}
@Path("atom")
public static class AtomServer
{
@GET
@Path("entry")
@Produces("application/atom+xml")
public Entry getEntry()
{
Entry entry = new Entry();
entry.setTitle("Hello World");
Content content = new Content();
content.setJAXBObject(new Customer("bill"));
entry.setContent(content);
return entry;
}
}
The Content.setJAXBObject() method is used to tell the content object you are sending back a
Java JAXB object and want it marshalled appropriately. If you are using a different base format
other than XML, i.e. "application/atom+json", this attached JAXB object will be marshalled into
that same format.
If you have an atom document as your input, you can also extract JAXB objects from Content using
the Content.getJAXBObject(Class clazz) method. Here is an example of an input atom document
and extracting a Customer object from the content.
@Path("atom")
public static class AtomServer
{
@PUT
@Path("entry")
@Produces("application/atom+xml")
public void putCustomer(Entry entry)
{
Content content = entry.getContent();
Customer cust = content.getJAXBObject(Customer.class);
}
}
103
104
Chapter 23.
Chapter 23. JSON Support via
Jackson
Besides the Jettision JAXB adapter for JSON, RESTEasy also supports integration with the
Jackson project. Many users find the output from Jackson much nicer than the Badger format
or Mapped format provided by Jettison. For more on Jackson 2, see http://wiki.fasterxml.com/
JacksonHome. Besides JAXB like APIs, it has a JavaBean based model, described at http://
wiki.fasterxml.com/JacksonDataBinding, which allows you to easily marshal Java objects to and
from JSON. RESTEasy integrates with the JavaBean model. While Jackson does come with its
own JAX-RS integration, RESTEasy expanded it a little, as decribed below.
NOTE. The resteasy-jackson-provider module, which is based on the outdated Jackson 1.9.x, is
currently deprecated, and will be removed in a release subsequent to 3.1.0.Final. The resteasyjackson2-provider module is based on Jackson 2.
23.1. Using Jackson 1.9.x Outside of WildFly
If you're deploying RESTEasy outside of WildFly, add the RESTEasy Jackson provder to your
WAR pom.xml build:
org.jboss.resteasy
resteasy-jackson-provider
${version.resteasy}
23.2. Using Jackson 1.9.x Inside WildFly 8
If you're deploying RESTEasy with WildFly 8, there's nothing you need to do except to make sure
you've updated your installation with the latest and greatest RESTEasy. See the Installation/Configuration section of this documentation for more details.
23.3. Using Jackson 2 Outside of WildFly
If you're deploying RESTEasy outside of WildFly, add the RESTEasy Jackson provder to your
WAR pom.xml build:
org.jboss.resteasy
105
Chapter 23. JSON Support via ...
resteasy-jackson2-provider
${version.resteasy}
23.4. Using Jackson 2 Inside WildFly 9 and above
If you're deploying RESTEasy with WildFly 9 or above, there's nothing you need to do except
to make sure you've updated your installation with the latest and greatest RESTEasy. See the
Installation/Configuration section of this documentation for more details.
23.5. Additional RESTEasy Specifics
The first extra piece that RESTEasy added to the integration was to support "application/*+json".
Jackson would only accept "application/json" and "text/json" as valid media types. This allows you
to create json-based media types and still let Jackson marshal things for you. For example:
@Path("/customers")
public class MyService {
@GET
@Produces("application/vnd.customer+json")
public Customer[] getCustomers() {}
}
Another problem that occurs is when you are using the RESTEasy JAXB providers alongside Jackson. You may want to use Jettison and JAXB to output your JSON instead of Jackson. In this case, you must either not install the Jackson provider, or use the annotation
@org.jboss.resteasy.annotations.providers.NoJackson on your JAXB annotated classes. For example:
@XmlRootElement
@NoJackson
public class Customer {...}
@Path("/customers")
public class MyService {
@GET
@Produces("application/vnd.customer+json")
public Customer[] getCustomers() {}
}
106
Possible Conflict With JAXB Provider
If you can't annotate the JAXB class with @NoJackson, then you can use the annotation on a
method parameter. For example:
@XmlRootElement
public class Customer {...}
@Path("/customers")
public class MyService {
@GET
@Produces("application/vnd.customer+json")
@NoJackson
public Customer[] getCustomers() {}
@POST
@Consumes("application/vnd.customer+json")
public void createCustomer(@NoJackson Customer[] customers) {...}
}
23.6. Possible Conflict With JAXB Provider
If your Jackson classes are annotated with JAXB annotations and you
have the resteasy-jaxb-provider in your classpath, you may trigger the Jettision JAXB marshalling code. To turn off the JAXB json marshaller use the
@org.jboss.resteasy.annotations.providers.jaxb.IgnoreMediaTypes("application/*+json") on your
classes.
23.7. JSONP Support
If
you're
using
Jackson,
RESTEasy
has
JSONP
[http://
en.wikipedia.org/wiki/JSONP]
that
you
can
turn
on
by
adding
the
provider
org.jboss.resteasy.plugins.providers.jackson.JacksonJsonpInterceptor
(Jackson2JsonpInterceptor if you're using the Jackson2 provider) to your deployments. If the media type of the response is json and a callback query parameter is given, the response will be
a javascript snippet with a method call of the method defined by the callback parameter. For example:
GET /resources/stuff?callback=processStuffResponse
will produce this response:
107
Chapter 23. JSON Support via ...
processStuffResponse()
This supports the default behavior of jQuery [http://api.jquery.com/jQuery.ajax/
]. To enable JacksonJsonpInterceptor in WildFly, you need to import annotations from org.jboss.resteasy.resteasy-jackson-provider module using jboss-deployment-structure.xml:
You can change the name of the callback parameter by setting the callbackQueryParameter property.
JacksonJsonpInterceptor can wrap the response into a try-catch block:
try{processStuffResponse()}catch(e){}
You can enable this feature by setting the resteasy.jsonp.silent property to true
Note. Because JSONP can be used in Cross Site Scripting Inclusion (XSSI) attacks,
Jackson2JsonpInterceptor is disabled by default. Two steps are necessary to enable it:
1. As noted above, Jackson2JsonpInterceptor must be included in the deployment. For example, a service file META-INF/services/javax.ws.rs.ext.Providers with the line
org.jboss.resteasy.plugins.providers.jackson.Jackson2JsonpInterceptor
may be included on the classpath
2. Also, the servlet context parameter parameter "resteasy.jsonp.enable" must be set to "true".
108
Jackson JSON Decorator
23.8. Jackson JSON Decorator
If you are using the Jackson 2 provider, RESTEasy has provided a pretty-printing annotation
simliar with the one in JAXB provider:
org.jboss.resteasy.annotations.providers.jackson.Formatted
Here is an example:
@GET
@Produces("application/json")
@Path("/formatted/{id}")
@Formatted
public Product getFormattedProduct()
{
return new Product(333, "robot");
}
As the example shown above, the @Formatted annotation will enable the underlying Jackson
option "SerializationFeature.INDENT_OUTPUT".
23.9. JSON Filter Support
In Jackson2 , there is new feature JsonFilter [http://wiki.fasterxml.com/JacksonFeatureJsonFilter]
to allow annotate class with @JsonFilter and doing dynamic filtering. Here is an example which
defines mapping from "nameFilter" to filter instances and filter bean properties when serilize to
json format:
@JsonFilter(value="nameFilter")
public class Jackson2Product {
protected String name;
protected int id;
public Jackson2Product() {
}
public Jackson2Product(final int id, final String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
109
Chapter 23. JSON Support via ...
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
@JsonFilter annotates resource class to filter out some property not to serialize in the json response. To map the filter id and instance we need to create another jackson class to add the id
and filter instance map:
public class ObjectFilterModifier extends ObjectWriterModifier {
public ObjectFilterModifier() {
}
@Override
public ObjectWriter modify(EndpointConfigBase endpoint,
MultivaluedMap httpHeaders, Object valueToWrite,
ObjectWriter w, JsonGenerator jg) throws IOException {
FilterProvider filterProvider = new SimpleFilterProvider().addFilter(
"nameFilter",
SimpleBeanPropertyFilter.filterOutAllExcept("name"));
return w.with(filterProvider);
}
}
Here the method modify() will take care of filtering all properties except "name" property before
write. To make this work, we need let RESTEasy know this mapping info. This can be easily set
in a WriterInterceptor using Jackson's ObjectWriterInjector:
@Provider
public class JsonFilterWriteInterceptor implements WriterInterceptor{
private ObjectFilterModifier modifier = new ObjectFilterModifier();
@Override
110
JSON Filter Support
public void aroundWriteTo(WriterInterceptorContext context)
throws IOException, WebApplicationException {
//set a threadlocal modifier
ObjectWriterInjector.set(modifier);
context.proceed();
}
}
Alternatively, Jackson's documentation suggest doing the same in a servlet filter; that however
potentially leads to issues on RESTEasy, as the ObjectFilterModifier ends up being stored using
a ThreadLocal object and there's no guarantee the same thread serving the servlet filter will be
running the resource endpoint execution too. So, for the servlet filter scenario, RESTEasy offers
its own injector that relies on the current thread context classloader for carrying over the specified
modifier:
public class ObjectWriterModifierFilter implements Filter {
private static ObjectFilterModifier modifier = new ObjectFilterModifier();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
modifier);
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
111
112
Chapter 24.
Chapter 24. JSON Support via Java
EE 7 JSON-P API
No, this is not the JSONP you are thinking of! JSON-P is a new Java EE 7 JSON parsing API.
Horrible name for a new JSON parsing API! What were they thinking? Anyways, RESTEasy has a
provider for it. If you are using WildFly, it is required by Java EE 7 so you will have it automatically
bundled. Otherwise, use this maven dependency.
org.jboss.resteasy
resteasy-json-p-provider
3.6.2.Final
It has built in support for JsonObject, JsonArray, and JsonStructure as request or response entities. It should not conflict with Jackson or Jettison if you have that in your path too.
113
114
Chapter 25.
Chapter 25. Multipart Providers
RESTEasy has rich support for the "multipart/*" and "multipart/form-data" mime types. The multipart mime format is used to pass lists of content bodies. Multiple content bodies are embedded
in one message. "multipart/form-data" is often found in web application HTML Form documents
and is generally used to upload files. The form-data format is the same as other multipart formats,
except that each inlined piece of content has a name associated with it.
RESTEasy provides a custom API for reading and writing multipart types as well as marshalling
arbitrary List (for any multipart type) and Map (multipart/form-data only) objects
25.1. Input with multipart/mixed
When writing a JAX-RS service, RESTEasy provides an interface that allows you to read in any
multipart mime type. org.jboss.resteasy.plugins.providers.multipart.MultipartInput
package org.jboss.resteasy.plugins.providers.multipart;
public interface MultipartInput
{
List getParts();
String getPreamble();
// You must call close to delete any temporary files created
// Otherwise they will be deleted on garbage collection or on JVM exit
void close();
}
public interface InputPart
{
MultivaluedMap getHeaders();
String getBodyAsString();
T getBody(Class type, Type genericType) throws IOException;
T getBody(org.jboss.resteasy.util.GenericType type) throws IOException;
MediaType getMediaType();
boolean isContentTypeFromMessage();
}
115
Chapter 25. Multipart Providers
MultipartInput is a simple interface that allows you to get access to each part of the multipart
message. Each part is represented by an InputPart interface. Each part has a set of headers
associated with it You can unmarshall the part by calling one of the getBody() methods. The Type
genericType parameter can be null, but the Class type parameter must be set. RESTEasy will find
a MessageBodyReader based on the media type of the part as well as the type information you
pass in. The following piece of code is unmarshalling parts which are XML into a JAXB annotated
class called Customer.
@Path("/multipart")
public class MyService
{
@PUT
@Consumes("multipart/mixed")
public void put(MultipartInput input)
{
List customers = new ArrayList...;
for (InputPart part : input.getParts())
{
Customer cust = part.getBody(Customer.class, null);
customers.add(cust);
}
input.close();
}
}
Sometimes you may want to unmarshall a body part that is sensitive to generic type metadata.
In this case you can use the org.jboss.resteasy.util.GenericType class. Here's an example of
unmarshalling a type that is sensitive to generic type metadata.
@Path("/multipart")
public class MyService
{
@PUT
@Consumes("multipart/mixed")
public void put(MultipartInput input)
{
for (InputPart part : input.getParts())
{
List cust = part.getBody(new GenericType>List>Customer<<()
{});
}
input.close();
}
116
java.util.List with multipart data
}
Use of GenericType is required because it is really the only way to obtain generic type information
at runtime.
25.2. java.util.List with multipart data
If your body parts are uniform, you do not have to manually unmarshall each and every part. You
can just provide a java.util.List as your input parameter. It must have the type it is unmarshalling
with the generic parameter of the List type declaration. Here's an example again of unmarshalling
a list of customers.
@Path("/multipart")
public class MyService
{
@PUT
@Consumes("multipart/mixed")
public void put(List customers)
{
...
}
}
25.3. Input with multipart/form-data
When writing a JAX-RS service, RESTEasy provides an interface that allows you to read in multipart/form-data mime type. "multipart/form-data" is often found in web application HTML Form
documents and is generally used to upload files. The form-data format is the same as other multipart formats, except that each inlined piece of content has a name associated with it. The interface
used for form-data input is org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput
public interface MultipartFormDataInput extends MultipartInput
{
@Deprecated
Map getFormData();
Map> getFormDataMap();
T getFormDataPart(String key, Class rawType, Type genericType) throws
IOException;
T getFormDataPart(String key, GenericType type) throws IOException;
117
Chapter 25. Multipart Providers
}
It works in much the same way as MultipartInput described earlier in this chapter.
25.4. java.util.Map with multipart/form-data
With form-data, if your body parts are uniform, you do not have to manually unmarshall each and
every part. You can just provide a java.util.Map as your input parameter. It must have the type it
is unmarshalling with the generic parameter of the List type declaration. Here's an example of of
unmarshalling a Map of Customer objects which are JAXB annotated classes.
@Path("/multipart")
public class MyService
{
@PUT
@Consumes("multipart/form-data")
public void put(Map customers)
{
...
}
}
25.5. Input with multipart/related
When writing a JAX-RS service, RESTEasy provides an interface that allows you to read in multipart/related mime type. A multipart/related is used to indicate that message parts should not be
considered individually but rather as parts of an aggregate whole. One example usage for multipart/related is to send a web page complete with images in a single message. Every multipart/related message has a root/start part that references the other parts of the message. The parts are
identified by their "Content-ID" headers. multipart/related is defined by RFC 2387. The interface
used for related input is org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedInput
public interface MultipartRelatedInput extends MultipartInput
{
String getType();
String getStart();
String getStartInfo();
InputPart getRootPart();
118
Output with multipart
Map getRelatedMap();
}
It works in much the same way as MultipartInput described earlier in this chapter.
25.6. Output with multipart
RESTEasy provides a simple API to output multipart data.
package org.jboss.resteasy.plugins.providers.multipart;
public class MultipartOutput
{
public OutputPart addPart(Object entity, MediaType mediaType)
public
mediaType)
OutputPart
addPart(Object
entity,
GenericType
type,
MediaType
public OutputPart addPart(Object entity, Class type, Type genericType,
MediaType mediaType)
public List getParts()
public String getBoundary()
public void setBoundary(String boundary)
}
public class OutputPart
{
public MultivaluedMap getHeaders()
public Object getEntity()
public Class getType()
public Type getGenericType()
public MediaType getMediaType()
}
When you want to output multipart data it is as simple as creating a MultipartOutput object and
calling addPart() methods. RESTEasy will automatically find a MessageBodyWriter to marshall
your entity objects. Like MultipartInput, sometimes you may have marshalling which is sensitive to
generic type metadata. In that case, use GenericType. Most of the time though passing in an Ob-
119
Chapter 25. Multipart Providers
ject and its MediaType is enough. In the example below, we are sending back a "multipart/mixed"
format back to the calling client. The parts are Customer objects which are JAXB annotated and
will be marshalling into "application/xml".
@Path("/multipart")
public class MyService
{
@GET
@Produces("multipart/mixed")
public MultipartOutput get()
{
MultipartOutput output = new MultipartOutput();
output.addPart(new Customer("bill"), MediaType.APPLICATION_XML_TYPE);
output.addPart(new Customer("monica"), MediaType.APPLICATION_XML_TYPE);
return output;
}
}
25.7. Multipart Output with java.util.List
If your body parts are uniform, you do not have to manually marshall each and every part or even
use a MultipartOutput object.. You can just provide a java.util.List. It must have the generic type
it is marshalling with the generic parameter of the List type declaration. You must also annotate
the method with the @PartType annotation to specify what media type each part is. Here's an
example of sending back a list of customers back to a client. The customers are JAXB objects
@Path("/multipart")
public class MyService
{
@GET
@Produces("multipart/mixed")
@PartType("application/xml")
public List get()
{
...
}
}
25.8. Output with multipart/form-data
RESTEasy provides a simple API to output multipart/form-data.
120
Output with multipart/form-data
package org.jboss.resteasy.plugins.providers.multipart;
public class MultipartFormDataOutput extends MultipartOutput
{
public OutputPart addFormData(String key, Object entity, MediaType mediaType)
public OutputPart addFormData(String key, Object entity, GenericType type,
MediaType mediaType)
public OutputPart addFormData(String key, Object entity, Class type, Type
genericType, MediaType mediaType)
public Map getFormData()
public Map> getFormDataMap()
}
When you want to output multipart/form-data it is as simple as creating a MultipartFormDataOutput
object and calling addFormData() methods. RESTEasy will automatically find a MessageBodyWriter to marshall your entity objects. Like MultipartInput, sometimes you may have marshalling
which is sensitive to generic type metadata. In that case, use GenericType. Most of the time though
passing in an Object and its MediaType is enough. In the example below, we are sending back a
"multipart/form-data" format back to the calling client. The parts are Customer objects which are
JAXB annotated and will be marshalling into "application/xml".
@Path("/form")
public class MyService
{
@GET
@Produces("multipart/form-data")
public MultipartFormDataOutput get()
{
MultipartFormDataOutput output = new MultipartFormDataOutput();
output.addPart("bill",
new
Customer("bill"),
MediaType.APPLICATION_XML_TYPE);
output.addPart("monica",
new
Customer("monica"),
MediaType.APPLICATION_XML_TYPE);
return output;
}
}
When using form-data format the named content can be a list of OutputPart objects as long as
each object in the named list contains a uniform object and media type. In the example below,
121
Chapter 25. Multipart Providers
we are sending back a "multipart/form-data" format which consists of two named list of objects,
bill and monica.
@Path("/form")
public class MyService
{
@GET
@Produces("multipart/form-data")
public MultipartFormDataOutput get()
{
MultipartFormDataOutput output = new MultipartFormDataOutput();
output.addPart("smith", new Customer("Joe Smith"),
MediaType.APPLICATION_XML_TYPE);
output.addPart("monica",
new
Employee("monica"),
MediaType.APPLICATION_JSON_TYPE);
output.addPart("smith", new Customer("Deb Smith"),
MediaType.APPLICATION_XML_TYPE);
output.addPart("smith", new Customer("Buba Smith"),
MediaType.APPLICATION_XML_TYPE);
return output;
}
}
25.9. Multipart FormData Output with java.util.Map
If your body parts are uniform, you do not have to manually marshall each and every part or even
use a MultipartFormDataOutput object.. You can just provide a java.util.Map. It must have the
generic type it is marshalling with the generic parameter of the Map type declaration. You must
also annotate the method with the @PartType annotation to specify what media type each part
is. Here's an example of sending back a list of customers back to a client. The customers are
JAXB objects
@Path("/multipart")
public class MyService
{
@GET
@Produces("multipart/form-data")
@PartType("application/xml")
public Map get()
{
...
}
122
Output with multipart/related
}
25.10. Output with multipart/related
RESTEasy provides a simple API to output multipart/related.
package org.jboss.resteasy.plugins.providers.multipart;
public class MultipartRelatedOutput extends MultipartOutput
{
public OutputPart getRootPart()
public OutputPart addPart(Object entity, MediaType mediaType,
String contentId, String contentTransferEncoding)
public String getStartInfo()
public void setStartInfo(String startInfo)
}
When you want to output multipart/related it is as simple as creating a MultipartRelatedOutput
object and calling addPart() methods. The first added part will be used as the root part of the
multipart/related message. RESTEasy will automatically find a MessageBodyWriter to marshall
your entity objects. Like MultipartInput, sometimes you may have marshalling which is sensitive
to generic type metadata. In that case, use GenericType. Most of the time though passing in an
Object and its MediaType is enough. In the example below, we are sending back a "multipart/related" format back to the calling client. We are sending a html with 2 images.
@Path("/related")
public class MyService
{
@GET
@Produces("multipart/related")
public MultipartRelatedOutput get()
{
MultipartRelatedOutput output = new MultipartRelatedOutput();
output.setStartInfo("text/html");
Map mediaTypeParameters = new LinkedHashMap();
mediaTypeParameters.put("charset", "UTF-8");
mediaTypeParameters.put("type", "text/html");
output.addPart(
123
Chapter 25. Multipart Providers
"\n"
+ "This is me: \n"
+ " This is you: \n"
+ "",
new MediaType("text", "html", mediaTypeParameters),
"", "8bit");
output.addPart("// binary octets for me png",
new MediaType("image", "png"), "",
"binary");
output.addPart("// binary octets for you png", new MediaType(
"image", "png"),
"", "binary");
client.putRelated(output);
return output;
}
}
25.11. @MultipartForm and POJOs
If you have a exact knowledge of your multipart/form-data packets, you can
map them to and from a POJO class to and from multipart/form-data using the
@org.jboss.resteasy.annotations.providers.multipart.MultipartForm annotation and the JAX-RS
@FormParam annotation. You simple define a POJO with at least a default constructor and annotate its fields and/or properties with @FormParams. These @FormParams must also be annotated with @org.jboss.resteasy.annotations.providers.multipart.PartType if you are doing output.
For example:
public class CustomerProblemForm {
@FormParam("customer")
@PartType("application/xml")
private Customer customer;
@FormParam("problem")
@PartType("text/plain")
private String problem;
public
public
public
public
Customer getCustomer() { return customer; }
void setCustomer(Customer cust) { this.customer = cust; }
String getProblem() { return problem; }
void setProblem(String problem) { this.problem = problem; }
}
After defining your POJO class you can then use it to represent multipart/form-data. Here's an
example of sending a CustomerProblemForm using the RESTEasy client framework:
124
@MultipartForm and POJOs
@Path("portal")
public interface CustomerPortal {
@Path("issues/{id}")
@Consumes("multipart/form-data")
@PUT
public void putProblem(@MultipartForm CustomerProblemForm,
@PathParam("id") int id);
}
{
CustomerPortal portal = ProxyFactory.create(CustomerPortal.class, "http://
example.com");
CustomerProblemForm form = new CustomerProblemForm();
form.setCustomer(...);
form.setProblem(...);
portal.putProblem(form, 333);
}
You see that the @MultipartForm annotation was used to tell RESTEasy that the object has
@FormParam and that it should be marshalled from that. You can also use the same object to
receive multipart data. Here is an example of the server side counterpart of our customer portal.
@Path("portal")
public class CustomerPortalServer {
@Path("issues/{id})
@Consumes("multipart/form-data")
@PUT
public void putIssue(@MultipartForm CustoemrProblemForm,
@PathParam("id") int id) {
... write to database...
}
}
In addition to the XML data format, you can also use JSON formatted data to represent your POJO
classes. To achieve this goal, you need to plug in a JSON provider into your project. For example,
you can add RESTEasy Jackson2 Provider into your project's dependency scope:
125
Chapter 25. Multipart Providers
org.jboss.resteasy
resteasy-jackson2-provider
${resteasy.ver}
And then you can write an ordinary POJO class, which Jackson2 can automatically serialize/deserialize it in JSON format:
public class JsonUser {
private String name;
public JsonUser() {
}
public JsonUser(final String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The resource class can be written like this:
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import org.jboss.resteasy.annotations.providers.multipart.PartType;
import
import
import
import
javax.ws.rs.Consumes;
javax.ws.rs.FormParam;
javax.ws.rs.PUT;
javax.ws.rs.Path;
@Path("/")
public class JsonFormResource {
public JsonFormResource() {
}
public static class Form {
126
@MultipartForm and POJOs
@FormParam("user")
@PartType("application/json")
private JsonUser user;
public Form() {
}
public Form(final JsonUser user) {
this.user = user;
}
public JsonUser getUser() {
return user;
}
}
@PUT
@Path("form/class")
@Consumes("multipart/form-data")
public String putMultipartForm(@MultipartForm Form form) {
return form.getUser().getName();
}
}
As the code shown above, you can see the PartType of JsonUser is marked as "application/json",
and it's included in the "@MultipartForm Form" class instance.
To send request to the resource method, you need to send JSON formatted data that is corresponding with the JsonUser class. The easiest to do this is to use a proxy class that has the same
definition like the resource class. Here is the sample code of the proxy class that is corresponding
with the JsonFormResource class:
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
@Path("/")
public interface JsonForm {
@PUT
@Path("form/class")
@Consumes("multipart/form-data")
String putMultipartForm(@MultipartForm JsonFormResource.Form form);
127
Chapter 25. Multipart Providers
}
And then you can use the proxy class above to send request to the resource method correctly.
Here is the sample code:
ResteasyClient client = new ResteasyClientBuilder().build();
...
JsonForm
proxy
=
client.target("your_request_url_address").proxy(JsonForm.class);
String
name
=
proxy.putMultipartForm(new
JsonFormResource.Form(new
JsonUser("bill")));
...
And if your client side has Jackson2 provider included, your request will be marshaled correctly,
and your JsonUser data will be converted into JSON format and then send to the server side. You
can also use hand-crafted JSON data as your request and send it to server side, but you have to
make sure the request data is in correct form then.
25.12. XML-binary Optimized Packaging (Xop)
RESTEasy supports Xop messages packaged as multipart/related. What does this mean? If you
have a JAXB annotated POJO that also holds some binary content you may choose to send it in
such a way where the binary does not need to be encoded in any way (neither base64 neither
hex). This results in faster transport while still using the convenient POJO. More about Xop can
be read here: http://www.w3.org/TR/xop10/. Now lets see an example:
First we have a JAXB annotated POJO to work with. @XmlMimeType tells JAXB the mime type
of the binary content (its not required to do XOP packaging but it is recommended to be set if
you know the exact type):
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public static class Xop {
private Customer bill;
private Customer monica;
@XmlMimeType(MediaType.APPLICATION_OCTET_STREAM)
private byte[] myBinary;
@XmlMimeType(MediaType.APPLICATION_OCTET_STREAM)
private DataHandler myDataHandler;
128
XML-binary Optimized Packaging (Xop)
// methods, other fields ...
}
In the above POJO myBinary and myDataHandler will be processed as binary attachments while
the whole Xop object will be sent as xml (in the places of the binaries only their references will
be generated). javax.activation.DataHandler is the most general supported type so if you need an
java.io.InputStream or a javax.activation.DataSource you need to go with the DataHandler. Some
other special types are supported too: java.awt.Image and javax.xml.transform.Source. Let's assume that Customer is also JAXB friendly POJO in the above example (of course it can also have
binary parts). Now lets see a an example Java client that sends this:
// our client interface:
@Path("mime")
public static interface MultipartClient {
@Path("xop")
@PUT
@Consumes(MultipartConstants.MULTIPART_RELATED)
public void putXop(@XopWithMultipartRelated Xop bean);
}
// Somewhere using it:
{
MultipartClient client = ProxyFactory.create(MultipartClient.class,
"http://www.example.org");
Xop xop = new Xop(new Customer("bill"), new Customer("monica"),
"Hello Xop World!".getBytes("UTF-8"),
new
DataHandler(new
ByteArrayDataSource("Hello
World!".getBytes("UTF-8"),
MediaType.APPLICATION_OCTET_STREAM)));
client.putXop(xop);
}
Xop
We used @Consumes(MultipartConstants.MULTIPART_RELATED) to tell RESTEasy that we
want to send multipart/related packages (that's the container format that will hold our Xop message). We used @XopWithMultipartRelated to tell RESTEasy that we want to make Xop messages. So we have a POJO and a client service that is willing to send it. All we need now a server
that can read it:
@Path("/mime")
public class XopService {
@PUT
@Path("xop")
@Consumes(MultipartConstants.MULTIPART_RELATED)
129
Chapter 25. Multipart Providers
public void putXopWithMultipartRelated(@XopWithMultipartRelated Xop xop) {
// do very important things here
}
}
We used @Consumes(MultipartConstants.MULTIPART_RELATED) to tell RESTEasy that we
want to read multipart/related packages. We used @XopWithMultipartRelated to tell RESTEasy
that we want to read Xop messages. Of course we could also produce Xop return values but we
would than also need to annotate that and use a Produce annotation, too.
25.13. Note about multipart parsing and working with
other frameworks
There are a lot of frameworks doing multipart parsing automatically with the
help of filters and interceptors. Like org.jboss.seam.web.MultipartFilter in Seam or
org.springframework.web.multipart.MultipartResolver in Spring. However the incoming multipart
request stream can be parsed only once. RESTEasy users working with multipart should make
sure that nothing parses the stream before RESTEasy gets it.
25.14. Overwriting the default fallback content type for
multipart messages
By default if no Content-Type header is present in a part, "text/plain; charset=us-ascii" is used as
fallback. This is the value defined by the MIME RFC. However for example some web clients (like
most, if not all, web browsers) do not send Content-Type headers for all fields in a multipart/formdata request (only for the file parts). This can cause character encoding and unmarshalling errors
on the server side. To correct this there is an option to define an other, non-rfc compliant fallback
value. This can be done dynamically per request with the PreProcessInterceptor infrastructure of
RESTEasy. In the following example we will set "*/*; charset=UTF-8" as the new default fallback:
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
@Provider
@ServerInterceptor
public
class
ContentTypeSetterPreProcessorInterceptor
PreProcessInterceptor {
implements
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, "*/*;
charset=UTF-8");
return null;
}
130
Overwriting the content type for multipart messages
}
25.15. Overwriting the content type for multipart messages
Using an interceptor and the InputPart.DEFAULT_CONTENT_TYPE_PROPERTY attribute
allows
setting
a
default
Content-Type,
but
it
is
also
possible to override the Content-Type, if any, in any input part by calling
org.jboss.resteasy.plugins.providers.multipart.InputPart.setMediaType(). For example:
@POST
@Path("query")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response setMediaType(MultipartInput input) throws IOException
{
List parts = input.getParts();
InputPart part = parts.get(0);
part.setMediaType(MediaType.valueOf("application/foo+xml"));
String s = part.getBody(String.class, null);
...
}
25.16. Overwriting the default fallback charset for multipart messages
Sometimes, a part may have a Content-Type header with no charset parameter. If the InputPart.DEFAULT_CONTENT_TYPE_PROPERTY property is set and the value has a charset parameter, that value will be appended to an existing Content-Type header that has no charset parameter. It is also possible to specify a default charset using the constant InputPart.DEFAULT_CHARSET_PROPERTY (actual value
"resteasy.provider.multipart.inputpart.defaultCharset"):
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
@Provider
@ServerInterceptor
public
class
ContentTypeSetterPreProcessorInterceptor
PreProcessInterceptor {
implements
131
Chapter 25. Multipart Providers
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, "UTF-8");
return null;
}
}
If
both
InputPart.DEFAULT_CONTENT_TYPE_PROPERTY
are
set,
then
the
InputPart.DEFAULT_CHARSET_PROPERTY will override any charset in
InputPart.DEFAULT_CONTENT_TYPE_PROPERTY.
InputPart.DEFAULT_CHARSET_PROPERTY
132
and
value
of
the value of
Chapter 26.
Chapter 26. YAML Provider
RESTEasy comes with built in support for YAML using the SnakeYAML library. To enable YAML
support, you need to drop in the SnakeYaml 1.8 jar and the resteasy-yaml-provider.jar (whatever the current version is) in RestEASY's classpath. Then you need to manually register the
org.jboss.resteasy.plugins.providers.YamlProvider provider. Note this feature is currently deprecated due to security vulnerabilities and will likely be removed in the future.
SnakeYaml jar file can either be downloaded from Google code at http://code.google.com/p/
snakeyaml/downloads/list
Or if you use maven, the SnakeYaml jar is available through SonaType public repositories and
included using this dependency:
org.yaml
snakeyaml
1.8
When starting resteasy look out in the logs for a line stating that the YamlProvider has been added
- this indicates that resteasy has found the Jyaml jar:
2877 Main INFO org.jboss.resteasy.plugins.providers.RegisterBuiltin - Adding YamlProvider
The Yaml provider recognises three mime types:
• text/x-yaml
• text/yaml
• application/x-yaml
This is an example of how to use Yaml in a resource method.
import
import
import
import
javax.ws.rs.Consumes;
javax.ws.rs.GET;
javax.ws.rs.Path;
javax.ws.rs.Produces;
133
Chapter 26. YAML Provider
@Path("/yaml")
public class YamlResource
{
@GET
@Produces("text/x-yaml")
public MyObject getMyObject() {
return createMyObject();
}
...
}
134
Chapter 27.
Chapter 27. JAX-RS 2.1 Additions
JAX-RS 2.1 adds more asynchronous processing support in both the Client and the Server API.
The specification adds a Reactive programming style to the Client side and Server-Sent Events
(SSE) protocol support to both client and server.
27.1. CompletionStage support
The specification adds support for declaring asynchronous resource methods by returning a CompletionStage [184] instead of using the @Suspended annotation.
Note
RESTEasy supports more reactive types than the specification.
27.2. Reactive Clients API
The specification defines a new type of invoker named RxInvoker, and a default implementation
of this type named CompletionStageRxInvoker. CompletionStageRxInvoker implements Java 8's
interface CompletionStage. This interface declares a large number of methods dedicated to managing asynchronous computations.
There is also a new rx method which is used in a similar manner to async.
27.3. Server-Sent Events (SSE)
SSE is part of HTML standard, currently supported by many browsers. It is a server push technology, which provides a way to establish a one-way channel to continuously send data to clients. SSE
events are pushed to the client via a long-running HTTP connection. In case of lost connection,
clients can retrieve missed events by setting a "Last-Event-ID" HTTP header in a new request.
SSE stream has text/event-stream media type and contains multiple SSE events. SSE event is
a data structure encoded with UTF-8 and contains fields and comment. The field can be event,
data, id, retry and other kinds of field will be ignored.
From JAX-RS 2.1, Server-sent Events APIs are introduced to support sending, receiving and
broadcasting SSE events.
27.3.1. SSE Server
As shown in the following example, a SSE resource method has the text/event-stream produce
media type and an injected context parameter SseEventSink. The injected SseEventSink is the
connected SSE stream where events can be sent. Another injected context Sse is an entry point
135
Chapter 27. JAX-RS 2.1 Additions
for creating and broadcasting SSE events. Here is an example to demonstrate how to send SSE
events every 200ms and close the stream after a "done" event.
Example 27.1.
@GET
@Path("domains/{id}")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void startDomain(@PathParam("id") final String id, @Context SseEventSink
sink @Context Sse sse)
{
ExecutorService service = (ExecutorService) servletContext
.getAttribute(ExecutorServletContextListener.TEST_EXECUTOR);
service.execute(new Thread()
{
public void run()
{
try
{
sink.send(sse.newEventBuilder().name("domain-progress")
.data(String.class, "starting domain " + id + " ...").build());
Thread.sleep(200);
sink.send(sse.newEvent("domain-progress", "50%"));
Thread.sleep(200);
sink.send(sse.newEvent("domain-progress", "60%"));
Thread.sleep(200);
sink.send(sse.newEvent("domain-progress", "70%"));
Thread.sleep(200);
sink.send(sse.newEvent("domain-progress", "99%"));
Thread.sleep(200);
sink.send(sse.newEvent("domain-progress",
"Done.")).thenAccept((Object obj) -> {
sink.close();
});
}
catch (final InterruptedException e)
{
logger.error(e.getMessage(), e);
}
}
});
}
136
SSE Broadcasting
Note
RESTEasy supports sending SSE events via reactive types.
27.3.2. SSE Broadcasting
With SseBroadcaster, SSE events can be broadcasted to multiple clients simultaneously. It will
iterate over all registered SseEventSinks and send events to all requested SSE Stream. An application can create a SseBroadcaster from an injected context Sse. The broadcast method on a
SseBroadcaster is used to send SSE events to all registered clients. The following code snippet is
an example on how to create SseBroadcaster, subscribe and broadcast events to all subscribed
consumers.
Example 27.2.
@GET
@Path("/subscribe")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void subscribe(@Context SseEventSink sink) throws IOException
{
if (sink == null)
{
throw new IllegalStateException("No client connected.");
}
if (sseBroadcaster == null)
{
sseBroadcaster = sse.newBroadcaster();
}
sseBroadcaster.register(sink);
}
@POST
@Path("/broadcast")
public void broadcast(String message) throws IOException
{
if (sseBroadcaster == null)
{
sseBroadcaster = sse.newBroadcaster();
}
sseBroadcaster.broadcast(sse.newEvent(message));
}
137
Chapter 27. JAX-RS 2.1 Additions
27.3.3. SSE Client
SseEventSource is the entry point to read and process incoming SSE events. A SseEventSource
instance can be initialized with a WebTarget. Once SseEventSource is created and connected
to a server, registered event consumer will be invoked when an inbound event arrives. In case
of errors, an exception will be passed to a registered consumer so that it can be processed.
SseEventSource can automatically reconnect the server and continuously receive pushed events
after the connection has been lost. SseEventSource can send lastEventId to the server by default
when it is reconnected, and server may use this id to replay all missed events. But reply event
is really upon on SSE resource method implementation. If the server responds HTTP 503 with a
RETRY_AFTER header, SseEventSource will automatically schedule a reconnect task with this
RETRY_AFTER value. The following code snippet is to create a SseEventSource and print the
inbound event data value and error if it happens.
Example 27.3.
public void printEvent() throws Exception
{
WebTarget target = client.target("http://localhost:8080/service/serversent-events"));
SseEventSource msgEventSource = SseEventSource.target(target).build();
try (SseEventSource eventSource = msgEventSource)
{
eventSource.register(event -> {
System.out.println(event.readData(String.class));
}, ex -> {
ex.printStackTrace();
});
eventSource.open();
}
}
27.4. Java API for JSON Binding
RESTEasy supports both JSON-B and JSON-P. In accordance with the specification, entity
providers for JSON-B take precedence over those for JSON-P for all types except JsonValue and
its sub-types.
The support for JSON-B is provided by the JsonBindingProvider from resteasy-json-binding-provider module. To satisfy JAX-RS 2.1 requirements, JsonBindingProvider takes precedence over the other providers for dealing with JSON payloads, in particular the Jackson one. The
JSON outputs (for the same input) from Jackson and JSON-B reference implementation can be
138
Java API for JSON Binding
slightly different. As a consequence, in order to allow retaining backward compatibility, RESTEasy
offers a resteasy.preferJacksonOverJsonB context property that can be set to true to disable
JsonBindingProvider for the current deloyment.
WildFly 14 supports specifying the default value for the resteasy.preferJacksonOverJsonB
context property by setting a system property with the same name. Moreover, if no value is set
for the context and system properties, it scans JAX-RS deployments for Jackson annotations and
sets the property to true if any of those annotations is found.
139
140
Chapter 28.
Chapter 28. String marshalling for
String based @*Param
28.1. Simple conversion
Parameters and properties annotated with @CookieParam, @HeaderParam, @MatrixParam, @PathParam, or @QueryParam are represented as strings in a raw HTTP request. The specification says
that any of these injected parameters can be converted to an object if the object's class has a
valueOf(String) static method or a constructor that takes one Stringparameter. In the following, for example,
public static class Customer {
private String name;
public Customer(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
@Path("test")
public static class TestResource {
@GET
@Path("")
public Response test(@QueryParam("cust") Customer cust) {
return Response.ok(cust.getName()).build();
}
}
@Test
public void testQuery() throws Exception {
Invocation.Builder request = ClientBuilder.newClient().target("http://
localhost:8081/test?cust=Bill").request();
Response response = request.get();
...
}
141
Chapter 28. String marshallin...
the query "?cust=Bill" will be transformed automatically to an instance of Customer with name
== "Bill".
28.2. ParamConverter
What if you have a class where valueOf()or this string constructor don't exist or are inappropriate
for an HTTP request? JAX-RS 2.0 has the javax.ws.rs.ext.ParamConverterProvider to help
in this situation.
A ParamConverterProvider is a provider defined as follows:
public interface ParamConverterProvider {
public ParamConverter getConverter(Class rawType, Type genericType,
Annotation annotations[]);
}
where a ParamConverter is defined:
public interface ParamConverter {
...
public T fromString(String value);
public String toString(T value);
}
For example, consider DateParamConverterProvider and DateParamConverter:
@Provider
public class DateParamConverterProvider implements ParamConverterProvider {
@SuppressWarnings("unchecked")
@Override
public ParamConverter getConverter(Class rawType, Type genericType,
Annotation[] annotations) {
if (rawType.isAssignableFrom(Date.class)) {
return (ParamConverter) new DateParamConverter();
}
return null;
}
}
142
StringParameterUnmarshaller
public class DateParamConverter implements ParamConverter {
public static final String DATE_PATTERN = "yyyyMMdd";
@Override
public Date fromString(String param) {
try {
return new SimpleDateFormat(DATE_PATTERN).parse(param.trim());
} catch (ParseException e) {
throw new BadRequestException(e);
}
}
@Override
public String toString(Date date) {
return new SimpleDateFormat(DATE_PATTERN).format(date);
}
}
Sending a Date in the form of a query, e.g., "?date=20161217" will cause the string "20161217"
to be converted to a Date on the server.
28.3. StringParameterUnmarshaller
In addition to the JAX-RS javax.ws.rs.ext.ParamConverterProvider, RESTEasy also has its
own org.jboss.resteasy.StringParameterUnmarshaller, defined
public interface StringParameterUnmarshaller
{
void setAnnotations(Annotation[] annotations);
T fromString(String str);
}
It is similar to javax.ws.rs.ext.ParamConverter except that
• it converts only from Strings;
• it is configured with the annotations on the injected parameter, which allows for fine-grained
control over the injection; and
• it is bound to a given parameter by an annotation that is annotated with the meta-annotation
org.jboss.resteasy.annotations.StringParameterUnmarshallerBinder:
143
Chapter 28. String marshallin...
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface StringParameterUnmarshallerBinder
{
Class value();
}
For example,
@Retention(RetentionPolicy.RUNTIME)
@StringParameterUnmarshallerBinder(TestDateFormatter.class)
public @interface TestDateFormat {
String value();
}
public
static
class
StringParameterUnmarshaller {
private SimpleDateFormat formatter;
TestDateFormatter
implements
public void setAnnotations(Annotation[] annotations) {
TestDateFormat format = FindAnnotation.findAnnotation(annotations,
TestDateFormat.class);
formatter = new SimpleDateFormat(format.value());
}
public Date fromString(String str) {
try {
return formatter.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
@Path("/")
public static class TestResource {
@GET
@Produces("text/plain")
@Path("/datetest/{date}")
public String get(@PathParam("date") @TestDateFormat("MM-dd-yyyy") Date
date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
144
Collections
return date.toString();
}
}
Note that the annotation @StringParameterUnmarshallerBinder on the annotation @TestDateFormat binds the formatter TestDateFormatter to a parameter annotated with @TestDateFormat. In this example, TestDateFormatter is used to format the Date parameter. Note also that the parameter "MM-dd-yyyy" to @TestDateFormat is accessible from
TestDateFormatter.setAnnotations().
28.4. Collections
For parameters and properties annotated with @CookieParam, @HeaderParam, @MatrixParam,
@PathParam, or @QueryParam, the JAX-RS specification [https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html] allows conversion as defined in the Javadoc of the corresponding annotation. In general, the following types are supported:
1. Types for which a ParamConverter is available via a registered ParamConverterProvider.
See Javadoc for these classes for more information.
2. Primitive types.
3. Types that have a constructor that accepts a single String argument.
4. Types that have a static method named valueOf or fromString with a single String argument
that return an instance of the type. If both methods are present then valueOf MUST be used
unless the type is an enum in which case fromString MUST be used.
5. List, Set, or SortedSet, where T satisfies 3 or 4 above.
Items 1, 3, and 4 have been discussed above, and item 2 is obvious. Note that item 5 allows for
collections of parameters. How these collections are expressed in HTTP messages depends, by
default, on the particular kind of parameter. In most cases, the notation for collections is based
on convention rather than a specification.
28.4.1. @QueryParam
For example, a multivalued query parameter is conventionally expressed like this:
http://bluemonkeydiamond.com?q=1&q=2&q=3
In this case, there is a query with name "q" and value {1, 2, 3}. This notation is further supported
in JAX-RS by the method
145
Chapter 28. String marshallin...
public MultivaluedMap getQueryParameters();
in javax.ws.rs.core.UriInfo.
28.4.2. @MatrixParam
There is no specified syntax for collections derived from matrix parameters, but
1. matrix parameters in a URL segment are conventionally separated by ";", and
2. the method
MultivaluedMap getMatrixParameters();
in javax.ws.rs.core.PathSegment supports extraction of collections from matrix parameters.
RESTEasy adopts the convention that multiple instances of a matrix parameter with the same
name are treated as a collection. For example,
http://bluemonkeydiamond.com/sippycup;m=1;m=2;m=3
is interpreted as a matrix parameter on path segment "sippycup" with name "m" and value {1, 2, 3}.
28.4.3. @HeaderParam
The HTTP 1.1 specification doesn't exactly specify that multiple components of a header value
should be separated by commas, but commas are used in those headers that naturally use lists,
e.g. Accept and Allow. Also, note that the method
public MultivaluedMap getRequestHeaders();
in javax.ws.rs.core.HttpHeaders returns a MultivaluedMap. It is natural, then, for RESTEasy
to treat
146
@CookieParam
x-header: a, b, c
as mapping name "x-header" to set {a, b, c}.
28.4.4. @CookieParam
The syntax for cookies is specified, but, unfortunately, it is specified in multiple competing specifications. Typically, multiple name=value cookie pairs are separated by ";". However, unlike the
case with query and matrix parameters, there is no specified JAX-RS method that returns a collection of cookie values. Consequently, if two cookies with the same name are received on the
server and directed to a collection typed parameter, RESTEasy will inject only the second one.
Note, in fact, that the method
public Map getCookies();
in javax.ws.rs.core.HttpHeaders returns a Map rather than a MultivaluedMap.
28.4.5. @PathParam
Deriving a collection from path segments is somewhat less natural than it is for other parameters, but JAX-RS supports the injection of multiple javax.ws.rs.core.PathSegments. There are
a couple of ways of obtaining multiple PathSegments. One is through the use of multiple path
variables with the same name. For example, the result of calling testTwoSegmentsArray() and
testTwoSegmentsList() in
@Path("")
public static class TestResource {
@GET
@Path("{segment}/{other}/{segment}/array")
public Response getTwoSegmentsArray(@PathParam("segment")
segments) {
System.out.println("array segments: " + segments.length);
return Response.ok().build();
}
PathSegment[]
@GET
@Path("{segment}/{other}/{segment}/list")
147
Chapter 28. String marshallin...
public Response getTwoSegmentsList(@PathParam("segment") List
segments) {
System.out.println("list segments: " + segments.size());
return Response.ok().build();
}
}
...
@Test
public void testTwoSegmentsArray() throws Exception {
Invocation.Builder request = client.target("http://localhost:8081/a/b/c/
array").request();
Response response = request.get();
Assert.assertEquals(200, response.getStatus());
response.close();
}
@Test
public void testTwoSegmentsList() throws Exception {
Invocation.Builder request = client.target("http://localhost:8081/a/b/c/
list").request();
Response response = request.get();
Assert.assertEquals(200, response.getStatus());
response.close();
}
is
array segments: 2
list segments: 2
An alternative is to use a wildcard template parameter. For example, the output of calling testWildcardArray() and testWildcardList() in
@Path("")
public static class TestResource {
@GET
@Path("{segments:.*}/array")
public Response getWildcardArray(@PathParam("segments")
segments) {
148
PathSegment[]
Extension to ParamConverter semantics
System.out.println("array segments: " + segments.length);
return Response.ok().build();
}
@GET
@Path("{segments:.*}/list")
public Response getWildcardList(@PathParam("segments") List
segments) {
System.out.println("list segments: " + segments.size());
return Response.ok().build();
}
...
@Test
public void testWildcardArray() throws Exception {
Invocation.Builder request = client.target("http://localhost:8081/a/b/c/
array").request();
Response response = request.get();
response.close();
}
@Test
public void testWildcardList() throws Exception {
Invocation.Builder request = client.target("http://localhost:8081/a/b/c/
list").request();
Response response = request.get();
response.close();
}
is
array segments: 3
list segments: 3
28.5. Extension to ParamConverter semantics
In the JAX-RS semantics, a ParamConverter is supposed to convert a single String that represents an individual object. RESTEasy extends the semantics to allow a ParamConverter to parse
the String representation of multiple objects and generate a List, Set, SortedSet,
array, or, indeed, any multivalued data structure whatever. First, consider the resource
149
Chapter 28. String marshallin...
@Path("queryParam")
public static class TestResource {
@GET
@Path("")
public Response conversion(@QueryParam("q") List list) {
return Response.ok(stringify(list)).build();
}
}
private static String stringify(List list) {
StringBuffer sb = new StringBuffer();
for (T s : list) {
sb.append(s).append(',');
}
return sb.toString();
}
Calling TestResource as follows, using the standard notation,
@Test
public void testQueryParamStandard() throws Exception {
ResteasyClient client = new ResteasyClientBuilder().build();
Invocation.Builder request = client.target("http://localhost:8081/queryParam?
q=20161217&q=20161218&q=20161219").request();
Response response = request.get();
System.out.println("response: " + response.readEntity(String.class));
}
results in
response: 20161217,20161218,20161219,
Suppose, instead, that we want to use a comma separated notation. We can add
150
Extension to ParamConverter semantics
public
static
class
MultiValuedParamConverterProvider
implements
ParamConverterProvider
@SuppressWarnings("unchecked")
@Override
public ParamConverter getConverter(Class rawType, Type genericType,
Annotation[] annotations) {
if (List.class.isAssignableFrom(rawType)) {
return (ParamConverter) new MultiValuedParamConverter();
}
return null;
}
}
public static class MultiValuedParamConverter implements ParamConverter> {
@Override
public List fromString(String param) {
if (param == null || param.trim().isEmpty()) {
return null;
}
return parse(param.split(","));
}
@Override
public String toString(List list) {
if (list == null || list.isEmpty()) {
return null;
}
return stringify(list);
}
private static List parse(String[] params) {
List list = new ArrayList();
for (String param : params) {
list.add(param);
}
return list;
}
}
Now we can call
@Test
151
Chapter 28. String marshallin...
public void testQueryParamCustom() throws Exception {
ResteasyClient client = new ResteasyClientBuilder().build();
Invocation.Builder request = client.target("http://localhost:8081/queryParam?
q=20161217,20161218,20161219").request();
Response response = request.get();
System.out.println("response: " + response.readEntity(String.class));
}
and get
response: 20161217,20161218,20161219,
Note that in this case, MultiValuedParamConverter.fromString() creates and returns an ArrayList, so TestResource.conversion() could be rewritten
@Path("queryParam")
public static class TestResource {
@GET
@Path("")
public Response conversion(@QueryParam("q") ArrayList list) {
return Response.ok(stringify(list)).build();
}
}
On the other hand, MultiValuedParamConverter could be rewritten to return a LinkList and
the parameter list in TestResource.conversion() could be either a List or a LinkedList.
Finally, note that this extension works for arrays as well. For example,
public static class Foo {
private String foo;
public Foo(String foo) {this.foo = foo;}
public String getFoo() {return foo;}
}
public static class FooArrayParamConverter implements ParamConverter {
152
Extension to ParamConverter semantics
@Override
public Foo[] fromString(String value)
{
String[] ss = value.split(",");
Foo[] fs = new Foo[ss.length];
int i = 0;
for (String s : ss) {
fs[i++] = new Foo(s);
}
return fs;
}
@Override
public String toString(Foo[] values)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < values.length; i++) {
sb.append(values[i].getFoo()).append(",");
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
@Provider
public
static
ParamConverterProvider {
class
FooArrayParamConverterProvider
implements
@SuppressWarnings("unchecked")
@Override
public ParamConverter getConverter(Class rawType,
genericType, Annotation[] annotations) {
if (rawType.equals(Foo[].class));
return (ParamConverter) new FooArrayParamConverter();
}
}
Type
@Path("")
public static class ParamConverterResource {
@GET
@Path("test")
public Response test(@QueryParam("foos") Foo[] foos) {
return Response.ok(new FooArrayParamConverter().toString(foos)).build();
}
}
153
Chapter 28. String marshallin...
154
Chapter 29.
Chapter 29. Responses using
javax.ws.rs.core.Response
You can build custom responses using the javax.ws.rs.core.Response and ResponseBuilder
classes. If you want to do your own streaming, your entity response must be an implementation
of javax.ws.rs.core.StreamingOutput. See the java doc for more information.
155
156
Chapter 30.
Chapter 30. Exception Handling
30.1. Exception Mappers
ExceptionMappers are custom, application provided, components that can catch thrown application exceptions and write specific HTTP responses. They are classes annotated with @Provider
and that implement this interface
package javax.ws.rs.ext;
import javax.ws.rs.core.Response;
/**
* Contract for a provider that maps Java exceptions to
* {@link javax.ws.rs.core.Response}. An implementation of this interface
must
* be annotated with {@link Provider}.
*
* @see Provider
* @see javax.ws.rs.core.Response
*/
public interface ExceptionMapper
{
/**
* Map an exception to a {@link javax.ws.rs.core.Response}.
*
* @param exception the exception to map to a response
* @return a response mapped from the supplied exception
*/
Response toResponse(E exception);
}
When an application exception is thrown it will be caught by the JAX-RS runtime. JAX-RS will
then scan registered ExceptionMappers to see which one support marshalling the exception type
thrown. Here is an example of ExceptionMapper
@Provider
public
class
ExceptionMapper
{
EJBExceptionMapper
implements
157
Chapter 30. Exception Handling
public Response toResponse(EJBException exception) {
return Response.status(500).build();
}
}
You register ExceptionMappers the same way you do MessageBodyReader/Writers. By scanning,
through the resteasy provider context-param (if you're deploying via a WAR file), or programmatically through the ResteasyProviderFactory class.
30.2. RESTEasy Built-in Internally-Thrown Exceptions
RESTEasy has a set of built-in exceptions that are thrown by it when it encounters errors during
dispatching or marshalling. They all revolve around specific HTTP error codes. You can find them
in RESTEasy's javadoc under the package org.jboss.resteasy.spi. Here's a list of them:
Table 30.1.
Exception
HTTP Code
Description
ReaderException
400
All exceptions thrown from
MessageBodyReaders
are
wrapped within this exception. If there is no ExceptionMapper for the wrapped
exception or if the exception
isn't a WebApplicationException, then resteasy will return a
400 code by default.
WriterException
500
All
exceptions
thrown
from MessageBodyWriters are
wrapped within this exception. If there is no ExceptionMapper for the wrapped
exception or if the exception
isn't a WebApplicationException, then resteasy will return a
400 code by default.
o.j.r.plugins.providers.jaxb.JAXBUnmarshalException
400
The JAXB providers (XML
and Jettison) throw this exception on reads. They may
be wrapping JAXBExceptions.
This class extends ReaderException
158
Overriding RESTEasy Builtin Exceptions
Exception
HTTP Code
o.j.r.plugins.providers.jaxb.JAXBMarshalException
500
Description
The JAXB providers (XML
and Jettison) throw this exception on writes. They may
be wrapping JAXBExceptions.
This class extends WriterException
ApplicationException
N/A
This exception wraps all exceptions thrown from application code. It functions much in
the same way as InvocationTargetException. If there is an
ExceptionMapper for wrapped
exception, then that is used to
handle the request.
Failure
N/A
Internal
logged
RESTEasy.
Not
LoggableFailure
N/A
Internal
Logged
RESTEasy
DefaultOptionsMethodException
N/A
If the user invokes HTTP
OPTIONS and no JAX-RS
error.
method for it, RESTEasy provides a default behavior by
throwing this exception
UnrecognizedPropertyExceptionHandler
400
A Jackson provider throws this
exception when JSON data is
determine to be invalid.
30.3. Overriding RESTEasy Builtin Exceptions
You may override RESTEasy built-in exceptions by writing an ExceptionMapper for the exception.
For that matter, you can write an ExceptionMapper for any thrown exception including WebApplicationException
159
160
Chapter 31.
Chapter 31. Configuring Individual
JAX-RS Resource Beans
If you are scanning your path for JAX-RS annotated resource beans, your beans will be registered
in per-request mode. This means an instance will be created per HTTP request served. Generally,
you will need information from your environment. If you are running within a servlet container
using the WAR-file distribution, in 1.0.0.Beta-2 and lower, you can only use the JNDI lookups to
obtain references to Java EE resources and configuration information. In this case, define your EE
configuration (i.e. ejb-ref, env-entry, persistence-context-ref, etc...) within web.xml of the resteasy
WAR file. Then within your code do jndi lookups in the java:comp namespace. For example:
web.xml
ejb/foo
...
resource code:
@Path("/")
public class MyBean {
public Object getSomethingFromJndi() {
new InitialContext.lookup("java:comp/ejb/foo");
}
...
}
You can also manually configure and register your beans through the Registry. To do this in a
WAR-based deployment, you need to write a specific ServletContextListener to do this. Within the
listener, you can obtain a reference to the registry as follows:
public class MyManualConfig implements ServletContextListener
161
Chapter 31. Configuring Indiv...
{
public void contextInitialized(ServletContextEvent event)
{
Registry
registry
=
event.getServletContext().getAttribute(Registry.class.getName());
(Registry)
}
...
}
Please also take a look at our Spring Integration as well as the Embedded Container's Spring
Integration
162
Chapter 32.
Chapter 32. Content encoding
32.1. GZIP Compression/Decompression
RESTEasy supports (though not by default - see below) GZIP decompression. If properly configured, the client framework or a JAX-RS service, upon receiving a message body with a Content-Encoding of "gzip", will automatically decompress it. The client framework can (though not
by default - see below) automatically set the Accept-Encoding header to be "gzip, deflate" so you
do not have to set this header yourself.
RESTEasy also supports (though not by default - see below) automatic compression. If the
client framework is sending a request or the server is sending a response with the Content-Encoding header set to "gzip", RESTEasy will (if properly configured) do the compression. So that you do not have to set the Content-Encoding header directly, you can use the
@org.jboss.resteasy.annotation.GZIP annotation.
@Path("/")
public interface MyProxy {
@Consumes("application/xml")
@PUT
public void put(@GZIP Order order);
}
In the above example, we tag the outgoing message body, order, to be gzip compressed. You
can use the same annotation to tag server responses
@Path("/")
public class MyService {
@GET
@Produces("application/xml")
@GZIP
public String getData() {...}
}
32.1.1. Configuring GZIP compression / decompression
Note. Decompression carries a risk of attack from a bad actor that can package an entity that
will expand greatly. Consequently, RESTEasy disables GZIP compression / decompression by
default.
163
Chapter 32. Content encoding
There are three interceptors that are relevant to GZIP compression / decompression:
1. org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor: If the Content-Encoding header is present and has the value "gzip", GZIPDecodingInterceptor will install an
InputStream that decompresses the message body.
2. org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor: If the Content-Encoding header is present and has the value "gzip", GZIPEncodingInterceptor will install an
OutputStream that compresses the message body.
3. org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPFilter: If the Accept-Encoding header does not exist, AcceptEncodingGZIPFilter will add Accept-Encoding with the
value "gzip, deflate". If the Accept-Encoding header exists but does not contain "gzip", AcceptEncodingGZIPFilter will append ", gzip". Note that enabling GZIP compression / decompression does not depend on the presence of this interceptor.
If GZIP decompression is enabled, an upper limit is imposed on the number of bytes GZIPDecodingInterceptor will extract from a compressed message body. The default limit is 10,000,000,
but a different value can be configured. See below.
32.1.1.1. Server side configuration
The interceptors may be enabled by including their classnames in a META-INF/services/javax.ws.rs.ext.Providers file on the classpath. The upper limit on deflated files may be configured by setting the web application context parameter "resteasy.gzip.max.input". If the limit is
exceeded on the server side, GZIPDecodingInterceptor will return a Response with status 413
("Request Entity Too Large") and a message specifying the upper limit.
Note.
moved
As
from
of
release
3.1.0.Final,
the
GZIP
interceptors
have
package
org.jboss.resteasy.plugins.interceptors.encoding
to
org.jboss.resteasy.plugins.interceptors.
and
they
should
be
named
accordingly
in
javax.ws.rs.ext.Providers.
However,
they
continue
to
exist
in
org.jboss.resteasy.plugins.interceptors.encoding in module resteasy-legacy, so, if
resteasy-legacy is available, the original names can be used. See Chapter Migration to RESTEasy
3.1 for more information.
32.1.1.2. Client side configuration
The interceptors may be enabled by registering them with, for example, a Client or WebTarget.
For example,
Client client = new ResteasyClientBuilder() // Activate gzip compression on
client:
.register(AcceptEncodingGZIPFilter.class)
164
General content encoding
.register(GZIPDecodingInterceptor.class)
.register(GZIPEncodingInterceptor.class)
.build();
The upper limit on deflated files may configured by creating an instance of GZIPDecodingInterceptor with a specific value:
Client client = new ResteasyClientBuilder() // Activate gzip compression on
client:
.register(AcceptEncodingGZIPFilter.class)
.register(new GZIPDecodingInterceptor(256))
.register(GZIPEncodingInterceptor.class)
.build();
If the limit is exceeded on the client side, GZIPDecodingInterceptor will throw a ProcessingException with a message specifying the upper limit.
32.2. General content encoding
The designation of a compressible entity by the use of the @GZIP annotation is a built in, specific
instance of a more general facility supported by RESTEasy. There are three components to this
facility.
1. The annotation org.jboss.resteasy.annotations.ContentEncoding is a "meta-annotation" used on other annotations to indicate that they represent a Content-Encoding. For example, @GZIP is defined
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ContentEncoding("gzip")
public @interface GZIP
{
}
The value of @ContentEncoding indicates the represented Content-Encoding. For @GZIP it is
"gzip".
2. ClientContentEncodingAnnotationFeature and ServerContentEncodingAnnotationFeature, two DynamicFeatures in package org.jboss.resteasy.plugins.interceptors,
examine resource methods for annotations decorated with @ContentEncoding.
165
Chapter 32. Content encoding
3. For each value found in a @ContentEncoding decorated annotation on a resource method, an instance of ClientContentEncodingAnnotationFilter or ServerContentEncodingAnnotationFilter, javax.ws.rs.ext.WriterInterceptors in package
org.jboss.resteasy.plugins.interceptors, is registered. They are responsible for adding
an appropriate Content-Encoding header. For example, ClientContentEncodingAnnotationFilter is defined
@ConstrainedTo(RuntimeType.CLIENT)
@Priority(Priorities.HEADER_DECORATOR)
public
class
ClientContentEncodingAnnotationFilter
WriterInterceptor
{
protected String encoding;
implements
public ClientContentEncodingAnnotationFilter(String encoding)
{
this.encoding = encoding;
}
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws
IOException, WebApplicationException
{
context.getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, encoding);
context.proceed();
}
}
When it is created, ClientContentEncodingAnnotationFeature passes in the value to be
used for Content-Encoding headers.
The annotation @GZIP is built into RESTEasy, but ClientContentEncodingAnnotationFeature
and ServerContentEncodingAnnotationFeature will also recognize application defined annotations. For example,
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ContentEncoding("compress")
public @interface Compress
{
}
@Path("")
166
General content encoding
public static class TestResource {
@GET
@Path("a")
@Compress
public String a() {
return "a";
}
}
If TestResource.a() is invoked as follows
@Test
public void testCompress() throws Exception
{
ResteasyClient client = new ResteasyClientBuilder().build();
Invocation.Builder request = client.target("http://localhost:8081/
a").request();
request.acceptEncoding("gzip,compress");
Response response = request.get();
System.out.println("content-encoding: "+ response.getHeaderString("ContentEncoding"));
client.close();
}
the output will be
content-encoding: compress
167
168
Chapter 33.
Chapter 33. CORS
RESTEasy has a ContainerRequestFilter that can be used to handle CORS preflight and actual requests. org.jboss.resteasy.plugins.interceptors.CorsFilter. You must allocate this
and register it as a singleton provider from your Application class. See the javadoc or its various
settings.
CorsFilter filter = new CorsFilter();
filter.getAllowedOrigins().add("http://localhost");
169
170
Chapter 34.
Chapter 34. Content-Range Support
RESTEasy supports Range requests for java.io.File response entities.
@Path("/")
public class Resource {
@GET
@Path("file")
@Produces("text/plain")
public File getFile()
{
return file;
}
}
Response response = client.target(generateURL("/file")).request()
.header("Range", "1-4").get();
Assert.assertEquals(response.getStatus(), 206);
Assert.assertEquals(4, response.getLength());
System.out.println("Content-Range: " + response.getHeaderString("ContentRange"));
171
172
Chapter 35.
Chapter 35. RESTEasy Caching
Features
RESTEasy provides numerous annotations and facilities to support HTTP caching semantics.
Annotations to make setting Cache-Control headers easier and both server-side and client-side
in-memory caches are available.
35.1. @Cache and @NoCache Annotations
RESTEasy provides an extension to JAX-RS that allows you to automatically set Cache-Control
headers on a successful GET request. It can only be used on @GET annotated methods. A
successful @GET request is any request that returns 200 OK response.
package org.jboss.resteasy.annotations.cache;
public @interface Cache
{
int maxAge() default -1;
int sMaxAge() default -1;
boolean noStore() default false;
boolean noTransform() default false;
boolean mustRevalidate() default false;
boolean proxyRevalidate() default false;
boolean isPrivate() default false;
}
public @interface NoCache
{
String[] fields() default {};
}
While @Cache builds a complex Cache-Control header, @NoCache is a simplified notation to
say that you don't want anything cached i.e. Cache-Control: nocache.
These annotations can be put on the resource class or interface and specifies a default cache
value for each @GET resource method. Or they can be put individually on each @GET resource
method.
173
Chapter 35. RESTEasy Caching ...
35.2. Client "Browser" Cache
RESTEasy has the ability to set up a client-side, browser-like, cache. You can use it with the
Client Proxy Framework, or with raw ClientRequests. This cache looks for Cache-Control headers
sent back with a server response. If the Cache-Control headers specify that the client is allowed
to cache the response, RESTEasy caches it within local memory. The cache obeys max-age requirements and will also automatically do HTTP 1.1 cache revalidation if either or both the LastModified and/or ETag headers are sent back with the original response. See the HTTP 1.1 specification for details on how Cache-Control or cache revalidation works.
It is very simple to enable caching. Here's an example of using the client cache with the Client
Proxy Framework
@Path("/orders")
public interface OrderServiceClient {
@Path("{id}")
@GET
@Produces("application/xml")
public Order getOrder(@PathParam("id") String id);
}
To create a proxy for this interface and enable caching for that proxy requires only a few simple
steps:
import org.jboss.resteasy.client.ProxyFactory;
import org.jboss.resteasy.client.cache.CacheFactory;
import org.jboss.resteasy.client.cache.LightweightBrowserCache;
public static void main(String[] args) throws Exception
{
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
OrderServiceClient proxy = ProxyFactory.create(OrderServiceClient.class,
generateBaseUrl());
// This line enables caching
LightweightBrowserCache cache = CacheFactory.makeCacheable(proxy);
}
If you are using the ClientRequest class to make invocations rather than the proxy framework,
it is just as easy
174
Local Server-Side Response Cache
import org.jboss.resteasy.client.ProxyFactory;
import org.jboss.resteasy.client.cache.CacheFactory;
import org.jboss.resteasy.client.cache.LightweightBrowserCache;
public static void main(String[] args) throws Exception
{
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
// This line enables caching
LightweightBrowserCache cache = new LightweightBrowserCache();
ClientRequest request = new ClientRequest("http://example.com/orders/333");
CacheFactory.makeCacheable(request, cache);
}
The LightweightBrowserCache, by default, has a maximum 2 megabytes of caching space. You
can change this programmatically by callings its setMaxBytes() method. If the cache gets full, the
cache completely wipes itself of all cached data. This may seem a bit draconian, but the cache
was written to avoid unnecessary synchronizations in a concurrent environment where the cache
is shared between multiple threads. If you desire a more complex caching solution or if you want
to plug in a thirdparty cache please contact our resteasy-developers list and discuss it with the
community.
35.3. Local Server-Side Response Cache
RESTEasy has a server-side cache that can sit in front of your JAX-RS services. It automatically
caches marshalled responses from HTTP GET JAX-RS invocations if, and only if your JAX-RS
resource method sets a Cache-Control header. When a GET comes in, the RESTEasy Server
Cache checks to see if the URI is stored in the cache. If it does, it returns the already marshalled
response without invoking your JAX-RS method. Each cache entry has a max age to whatever
is specified in the Cache-Control header of the initial request. The cache also will automatically
generate an ETag using an MD5 hash on the response body. This allows the client to do HTTP 1.1
cache revalidation with the IF-NONE-MATCH header. The cache is also smart enough to perform
revalidation if there is no initial cache hit, but the jax-rs method still returns a body that has the
same ETag.
The cache is also automatically invalidated for a particular URI that has PUT, POST,
or DELETE invoked on it. You can also obtain a reference to the cache by injecting a
org.jboss.resteasy.plugins.cache.ServerCache via the @Context annotation
@Context
ServerCache cache;
175
Chapter 35. RESTEasy Caching ...
@GET
public String get(@Context ServerCache cache) {...}
To
set
up
the
server-side
cache
you
must
register
an
instance
of
org.jboss.resteasy.plugins.cache.server.ServerCacheFeature via your Application getSingletons() or getClasses() methods. The underlying cache is Infinispan. By default, RESTEasy will
create an Infinispan cache for you. Alternatively, you can create and pass in an instance of your
cache to the ServerCacheFeature constructor. You can also configure Infinispan by specifying
various context-param variables in your web.xml. First, if you are using Maven you must depend
on the resteasy-cache-core artifact:
org.jboss.resteasy
resteasy-cache-core
3.6.2.Final
The next thing you should probably do is set up the Infinispan configuration in your web.xml.
server.request.cache.infinispan.config.file
infinispan.xml
server.request.cache.infinispan.cache.name
MyCache
server.request.cache.infinispan.config.file can either be a classpath or a file path.
server.request.cache.infinispan.cache.name is the name of the cache you want to reference that
is declared in the config file.
176
HTTP preconditions
35.4. HTTP preconditions
JAX-RS provides an API for evaluating HTTP preconditions based on "If-Match", "If-NoneMatch", "If-Modified-Since" and "If-Unmodified-Since" headers.
Response.ResponseBuilder
request.evaluatePreconditions(lastModified, etag);
rb
=
By default RESTEasy will return status code 304 (Not modified) or 412 (Precondition failed) if any
of conditions fails. However it is not compliant with RFC 7232 which states that headers "IfMatch", "If-None-Match" MUST have higher precedence. You can enable RFC 7232 compatible
mode by setting resteasy.rfc7232preconditions context parameter to true
177
178
Chapter 36.
Chapter 36. Filters and Interceptors
JAX-RS 2.0 has two different concepts for interceptions: Filters and Interceptors. Filters are mainly
used to modify or process incoming and outgoing request headers or response headers. They
execute before and after request and response processing.
36.1. Server Side Filters
On the server-side you have two different types of filters. ContainerRequestFilters run before your
JAX-RS resource method is invoked. ContainerResponseFilters run after your JAX-RS resource
method is invoked. As an added caveat, ContainerRequestFilters come in two flavors: pre-match
and post-matching. Pre-matching ContainerRequestFilters are designated with the @PreMatching annotation and will execute before the JAX-RS resource method is matched with the incoming
HTTP request. Pre-matching filters often are used to modify request attributes to change how it
matches to a specific resource method (i.e. strip .xml and add an Accept header). ContainerRequestFilters can abort the request by calling ContainerRequestContext.abortWith(Response). A
filter might want to abort if it implements a custom authentication protocol.
After the resource class method is executed, JAX-RS will run all ContainerResponseFilters. These
filters allow you to modify the outgoing response before it is marshalling and sent to the client. So
given all that, here's some pseudo code to give some understanding of how things work.
// execute pre match filters
for (ContainerRequestFilter filter : preMatchFilters) {
filter.filter(requestContext);
if (isAborted(requestContext)) {
sendAbortionToClient(requestContext);
return;
}
}
// match the HTTP request to a resource class and method
JaxrsMethod method = matchMethod(requestContext);
// Execute post match filters
for (ContainerRequestFilter filter : postMatchFilters) {
filter.filter(requestContext);
if (isAborted(requestContext)) {
sendAbortionToClient(requestContext);
return;
}
}
// execute resource class method
method.execute(request);
179
Chapter 36. Filters and Inter...
// execute response filters
for (ContainerResponseFilter filter : responseFilters) {
filter.filter(requestContext, responseContext);
}
36.1.1. Asynchronous filters
It is possible to turn filters into asynchronous filters, if you need to suspend execution of your filter
until a certain resource has become available. This turns the request asynchronous, but requires
no change to your resource method declaration. In particular, synchronous and asynchronous
resource methods continue to work as specified, regardless of whether or not a filter turned the
request asynchronous. Similarly, one filter turning the request asynchronous requires no change
in the declaration of further filters.
In order to turn a filter's execution asynchronous, you need to cast the ContainerRequestContext
into a SuspendableContainerRequestContext (for pre/post request filters), or cast the ContainerResponseContext into a SuspendableContainerResponseContext (for response filters).
These context objects can turn the current filter's execution to asynchronous by calling the suspend() method. Once asynchronous, the filter chain is suspended, and will only resume after one
of the following method is called on the context object:
abortWith(Response)
Terminate the filter chain, return the given Response to the client (only for ContainerRequestFilter).
resume()
Resume execution of the filter chain by calling the next filter.
resume(Throwable)
Abort execution of the filter chain by throwing the given exception. This behaves as if the filter
were synchronous and threw the given exception.
36.2. Client Side Filters
On the client side you also have two types of filters: ClientRequestFilter and ClientResponseFilter.
ClientRequestFilters run before your HTTP request is sent over the wire to the server. ClientResponseFilters run after a response is received from the server, but before the response body
is unmarshalled. ClientRequestFilters are also allowed to abort the execute of the request and
provide a canned response without going over the wire to the server. ClientResponseFilters can
modfiy the Response object before it is handed back to application code. Here's some pseudo
code to illustrate things.
180
Reader and Writer Interceptors
// execute request filters
for (ClientRequestFilter filter : requestFilters) {
filter.filter(requestContext);
if (isAborted(requestContext)) {
return requestContext.getAbortedResponseObject();
}
}
// send request over the wire
response = sendRequest(request);
// execute response filters
for (ClientResponseFilter filter : responseFilters) {
filter.filter(requestContext, responseContext);
}
36.3. Reader and Writer Interceptors
While filters modify request or response headers, interceptors deal with message bodies. Interceptors are executed in the same call stack as their corresponding reader or writer. ReaderInterceptors wrap around the execution of MessageBodyReaders. WriterInterceptors wrap around the
execution of MessageBodyWriters. They can be used to implement a specific content-encoding.
They can be used to generate digital signatures or to post or pre-process a Java object model
before or after it is marshalled.
36.4. Per Resource Method Filters and Interceptors
Sometimes you want a filter or interceptor to only run for a specific resource method. You can do
this in two different ways: register an implementation of DynamicFeature or use the @NameBinding annotation. The DynamicFeature interface is executed at deployment time for each resource
method. You just use the Configurable interface to register the filters and interceptors you want
for the specific resource method. @NameBinding works a lot like CDI interceptors. You annotate
a custom annotation with @NameBinding and then apply that custom annotation to your filter
and resource method. The custom annotation must use @Retention(RetentionPolicy.RUNTIME)
in order for the attribute to be picked up by the RESTEasy runtime code when it is deployed.
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface DoIt {}
@DoIt
public class MyFilter implements ContainerRequestFilter {...}
@Path("/root")
181
Chapter 36. Filters and Inter...
public class MyResource {
@GET
@DoIt
public String get() {...}
}
36.5. Ordering
Ordering is accomplished by using the @BindingPriority annotation on your filter or interceptor
class.
182
Chapter 37.
Chapter 37. Asynchronous HTTP
Request Processing
Asynchronous HTTP Request Processing is a relatively new technique that allows you to process
a single HTTP request using non-blocking I/O and, if desired in separate threads. Some refer to
it as COMET capabilities. The primary use case for Asynchronous HTTP is in the case where the
client is polling the server for a delayed response. The usual example is an AJAX chat client where
you want to push/pull from both the client and the server. These scenarios have the client blocking
a long time on the server’s socket waiting for a new message. What happens in synchronous
HTTP where the server is blocking on incoming and outgoing I/O is that you end up having a thread
consumed per client connection. This eats up memory and valuable thread resources. Not such
a big deal in 90% of applications (in fact using asynchronous processing may actually hurt your
performance in most common scenarios), but when you start getting a lot of concurrent clients that
are blocking like this, there’s a lot of wasted resources and your server does not scale that well.
37.1. Using the @Suspended annotation
The JAX-RS 2.0 specification has added asynchronous HTTP support via two classes. The @Suspended annotation, and AsyncResponse interface.
Injecting an AsynchronousResponse as a parameter to your jax-rs methods tells RESTEasy that
the HTTP request/response should be detached from the currently executing thread and that the
current thread should not try to automatically process the response.
The AsyncResponse is the callback object. The act of calling one of the resume() methods will
cause a response to be sent back to the client and will also terminate the HTTP request. Here is
an example of asynchronous processing:
import javax.ws.rs.Suspend;
import javax.ws.rs.core.AsynchronousResponse;
@Path("/")
public class SimpleResource
{
@GET
@Path("basic")
@Produces("text/plain")
public void getBasic(@Suspended final AsyncResponse response) throws Exception
{
Thread t = new Thread()
{
@Override
183
Chapter 37. Asynchronous HTTP...
public void run()
{
try
{
Response
jaxrs
=
Response.ok("basic").type(MediaType.TEXT_PLAIN).build();
response.resume(jaxrs);
}
catch (Exception e)
{
response.resume(e);
}
}
};
t.start();
}
}
AsyncResponse also has other methods to cancel the execution. See javadoc for more details.
NOTE:
The
old
RESTEasy
proprietary
API
for
async
http
has
been
deprecated
and
may
be
removed
as
soon
as
RESTEasy
3.1.
In
particular,
the
RESTEasy
@Suspend
annotation
is
replaced
by
javax.ws.rs.container.Suspended, and org.jboss.resteasy.spi.AsynchronousResponse
is replaced by javax.ws.rs.container.AsyncResponse. Note that @Suspended does not have
a value field, which represented a timeout limit. Instead, AsyncResponse.setTimeout() may be
called.
37.2. Using Reactive return types
The JAX-RS 2.1 specification adds support for declaring asynchronous resource methods by returning a CompletionStage instead of using the @Suspended annotation.
Whenever a resource method returns a CompletionStage, it will be subscribed to, the request
will be suspended, and only resumed when the CompletionStage is resolved either to a value
(which is then treated as the return value for the method), or as an error case, in which case the
exception will be processed as if it were thrown by the resource method.
Here is an example of asynchronous processing using CompletionStage:
import javax.ws.rs.Suspend;
import javax.ws.rs.core.AsynchronousResponse;
@Path("/")
public class SimpleResource
184
Asynchronous filters
{
@GET
@Path("basic")
@Produces("text/plain")
public CompletionStage getBasic() throws Exception
{
final CompletableFuture response = new CompletableFuture<>();
Thread t = new Thread()
{
@Override
public void run()
{
try
{
Response
jaxrs
=
Response.ok("basic").type(MediaType.TEXT_PLAIN).build();
response.complete(jaxrs);
}
catch (Exception e)
{
response.completeExceptionally(e);
}
}
};
t.start();
return response;
}
}
Note
RESTEasy supports more reactive types for asynchronous programming.
37.3. Asynchronous filters
It is possible to write filters that also turn the request asynchronous. Whether or not filters turned
the request asynchronous before execution of your method makes absolutely no difference to
your method: it does not need to be declared asynchronous in order to function as specified.
Synchronous methods and asynchronous methods will work as specified by the spec.
185
186
Chapter 38.
Chapter 38. Asynchronous Job
Service
The RESTEasy Asynchronous Job Service is an implementation of the Asynchronous Job pattern
defined in O'Reilly's "Restful Web Services" book. The idea of it is to bring asynchronicity to a
synchronous protocol.
38.1. Using Async Jobs
While HTTP is a synchronous protocol it does have a faint idea of asynchronous invocations.
The HTTP 1.1 response code 202, "Accepted" means that the server has received and accepted
the response for processing, but the processing has not yet been completed. The RESTEasy
Asynchronous Job Service builds around this idea.
POST http://example.com/myservice?asynch=true
For example, if you make the above post with the asynch query parameter set to true, RESTEasy
will return a 202, "Accepted" response code and run the invocation in the background. It also
sends back a Location header with a URL pointing to where the response of the background
method is located.
HTTP/1.1 202 Accepted
Location: http://example.com/asynch/jobs/3332334
The URI will have the form of:
/asynch/jobs/{job-id}?wait={millisconds}|nowait=true
You can perform the GET, POST, and DELETE operations on this job URL. GET returns whatever
the JAX-RS resource method you invoked returned as a response if the job was completed. If
the job has not completed, this GET will return a response code of 202, Accepted. Invoking GET
does not remove the job, so you can call it multiple times. When RESTEasy's job queue gets full,
it will evict the least recently used job from memory. You can manually clean up after yourself by
calling DELETE on the URI. POST does a read of the JOB response and will remove the JOB
it has been completed.
187
Chapter 38. Asynchronous Job ...
Both GET and POST allow you to specify a maximum wait time in milliseconds, a "wait" query
parameter. Here's an example:
POST http://example.com/asynch/jobs/122?wait=3000
If you do not specify a "wait" parameter, the GET or POST will not wait at all if the job is not
complete.
NOTE!! While you can invoke GET, DELETE, and PUT methods asynchronously, this breaks the
HTTP 1.1 contract of these methods. While these invocations may not change the state of the
resource if invoked more than once, they do change the state of the server as new Job entries with
each invocation. If you want to be a purist, stick with only invoking POST methods asynchronously.
Security NOTE! RESTEasy role-based security (annotations) does not work with the Asynchronous Job Service. You must use XML declarative security within your web.xml file. Why? It is
impossible to implement role-based security portably. In the future, we may have specific JBoss
integration, but will not support other environments.
NOTE. A SecureRandom object is used to generate unique job ids. For security purposes, the
SecureRandom is periodically reseeded. By default, it is reseeded after 100 uses. This value may
be configured with the servlet init parameter "resteasy.secure.random.max.use".
38.2. Oneway: Fire and Forget
RESTEasy also supports the notion of fire and forget. This will also return a 202, Accepted response, but no Job will be created. This is as simple as using the oneway query parameter instead
of asynch. For example:
POST http://example.com/myservice?oneway=true
Security NOTE! RESTEasy role-based security (annotations) does not work with the Asynchronous Job Service. You must use XML declaritive security within your web.xml file. Why? It is impossible to implement role-based security portably. In the future, we may have specific JBoss
integration, but will not support other environments.
38.3. Setup and Configuration
You must enable the Asynchronous Job Service in your web.xml file as it is not turned on by
default.
188
Setup and Configuration
resteasy.async.job.service.enabled
true
resteasy.async.job.service.max.job.results
100
resteasy.async.job.service.max.wait
300000
resteasy.async.job.service.thread.pool.size
100
resteasy.async.job.service.base.path
/asynch/jobs
...
189
190
Chapter 39.
Chapter 39. Reactive programming
support
With version 2.1, the JAX-RS specification (https://jcp.org/en/jsr/detail?id=370) takes its first steps
into the world of Reactive Programming. There are many discussions of reactive programming
on the internet, and a general introduction is beyond the scope of this document, but there are a
few things worth discussing. Some primary aspects of reactive programming are the following:
• Reactive programming supports the declarative creation of rich computational structures. The
representations of these structures can be passed around as first class objects such as method
parameters and return values.
• Reactive programming supports both synchronous and asynchronous computation, but it is
particularly helpful in facilitating, at a relatively high level of expression, asynchronous computation. Conceptually, asynchronous computation in reactive program typically involves pushing
data from one entity to another, rather than polling for data.
39.1. CompletionStage
In java 1.8 and JAX-RS 2.1, the support for reactive programming is fairly limited. Java 1.8 introduces the interface java.util.concurrent.CompletionStage, and JAX-RS 2.1 mandates support for the javax.ws.rs.client.CompletionStageRxInvoker, which allows a client to obtain
a response in the form of a CompletionStage.
One implementation of CompletionStage is the java.util.concurrent.CompleteableFuture.
For example:
@Test
public void testCompletionStage() throws Exception {
CompletionStage stage = getCompletionStage();
log.info("result: " + stage.toCompletableFuture().get());
}
private CompletionStage getCompletionStage() {
CompletableFuture future = new CompletableFuture();
future.complete("foo");
return future;
}
Here, a CompleteableFuture is created with the value "foo", and its value is extracted by the
method CompletableFuture.get(). That's fine, but consider the altered version:
191
Chapter 39. Reactive programm...
@Test
public void testCompletionStageAsync() throws Exception {
log.info("start");
CompletionStage stage = getCompletionStageAsync();
String result = stage.toCompletableFuture().get();
log.info("do some work");
log.info("result: " + result);
}
private CompletionStage getCompletionStageAsync() {
CompletableFuture future = new CompletableFuture();
Executors.newCachedThreadPool().submit(()
->
{sleep(2000);
future.complete("foo");});
return future;
}
private void sleep(long l) {
try {
Thread.sleep(l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
with output something like:
3:10:51 PM INFO: start
3:10:53 PM INFO: do some work
3:10:53 PM INFO: result: foo
It also works, but it illustrates the fact that CompletableFuture.get() is a blocking call. The
CompletionStage is constructed and returned immediately, but the value isn't returned for two
seconds. A version that is more in the spirit of the reactive style is:
@Test
public void testCompletionStageAsyncAccept() throws Exception {
log.info("start");
CompletionStage stage = getCompletionStageAsync();
stage.thenAccept((String s) -> log.info("s: " + s));
log.info("do some work");
...
192
CompletionStage
}
In this case, the lambda (String s) -> log.info("s: " + s) is registered with the CompletionStage as
a "subscriber", and, when the CompletionStage eventually has a value, that value is passed to
the lambda. Note that the output is something like
3:23:05 INFO: start
3:23:05 INFO: do some work
3:23:07 INFO: s: foo
Executing CompletionStages asynchronously is so common that there are several supporting
convenience methods. For example:
@Test
public void testCompletionStageSupplyAsync() throws Exception {
CompletionStage stage = getCompletionStageSupplyAsync();;
stage.thenAccept((String s) -> log.info("s: " + s));
}
private CompletionStage getCompletionStageSupplyAsync() {
return CompletableFuture.supplyAsync(() -> "foo");
}
The static method ComputableFuture.supplyAsync() creates a ComputableFuture, the value
of which is supplied asynchronously by the lambda () -> "foo", running, by default, in the default
pool of java.util.concurrent.ForkJoinPool.
One final example illustrates a more complex computational structure:
@Test
public void testCompletionStageComplex() throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
CompletionStage stage1 = getCompletionStageSupplyAsync1("foo",
executor);
CompletionStage stage2 = getCompletionStageSupplyAsync1("bar",
executor);
CompletionStage stage3 = stage1.thenCombineAsync(stage2, (String s,
String t) -> s + t, executor);
stage3.thenAccept((String s) -> log.info("s: " + s));
}
193
Chapter 39. Reactive programm...
private
CompletionStage
getCompletionStageSupplyAsync1(String
s,
ExecutorService executor) {
return CompletableFuture.supplyAsync(() -> s, executor);
}
stage1 returns "foo", stage2 returns "bar", and stage3, which runs when both stage1 and stage2
have completed, returns the concatenation of "foo" and "bar". Note that, in this example, an explict
ExecutorService is provided for asynchronous processing.
39.2. CompletionStage in JAX-RS
On the client side, the JAX-RS 2.1 specification mandates an implementation of the interface
javax.ws.rs.client.CompletionStageRxInvoker:
public interface CompletionStageRxInvoker extends RxInvoker {
@Override
public CompletionStage get();
@Override
public CompletionStage get(Class responseType);
@Override
public CompletionStage get(GenericType responseType);
...
That is, there are invocation methods for the standard HTTP verbs, just as in the standard
javax.ws.rs.client.SyncInvoker. A CompletionStageRxInvoker is obtained by calling rx()
on a javax.ws.rs.client.Invocation.Builder, which extends SyncInvoker. For example,
Invocation.Builder
builder
=
client.target(generateURL("/get/
string")).request();
CompletionStageRxInvoker invoker = builder.rx(CompletionStageRxInvoker.class);
CompletionStage stage = invoker.get();
Response response = stage.toCompletableFuture().get();
log.info("result: " + response.readEntity(String.class));
or
194
CompletionStage in JAX-RS
CompletionStageRxInvoker
invoker
=
client.target(generateURL("/get/
string")).request().rx(CompletionStageRxInvoker.class);
CompletionStage stage = invoker.get(String.class);
String s = stage.toCompletableFuture().get();
log.info("result: " + s);
On the server side, the JAX-RS 2.1 specification requires support for resource methods with return
type CompletionStage. For example,
@GET
@Path("get/async")
public CompletionStage longRunningOpAsync() {
CompletableFuture cs = new CompletableFuture<>();
executor.submit(
new Runnable() {
public void run() {
executeLongRunningOp();
cs.complete("Hello async world!");
}
});
return cs;
}
The way to think about longRunningOpAsync() is that it is asynchronously creating and returning
a String. After cs.complete() is called, the server will return the String "Hello async world!"
to the client.
An important thing to understand is that the decision to produce a result asynchronously on the
server and the decision to retrieve the result asynchronously on the client are independent. Suppose that there is also a resource method
@GET
@Path("get/sync")
public String longRunningOpSync() {
return "Hello async world!";
}
Then all three of the following invocations are valid:
public void testGetStringAsyncAsync() throws Exception {
195
Chapter 39. Reactive programm...
CompletionStageRxInvoker
invoker
=
client.target(generateURL("/get/
async")).request().rx();
CompletionStage stage = invoker.get(String.class);
log.info("s: " + stage.toCompletableFuture().get());
}
public void testGetStringSyncAsync() throws Exception {
Builder request = client.target(generateURL("/get/async")).request();
String s = request.get(String.class);
log.info("s: " + s);
}
and
public void testGetStringAsyncSync() throws Exception {
CompletionStageRxInvoker invoker = client.target(generateURL("/get/
sync")).request().rx();
CompletionStage stage = invoker.get(String.class);
log.info("s: " + stage.toCompletableFuture().get());
}
Note
CompletionStage in JAX-RS is also discussed in the chapter Asynchronous HTTP
Request Processing.
Note
Since running code asynchronously is so common in this context, it is worth pointing out that objects obtained by way of the annotation @Context or by way of calling ResteasyProviderFactory.getContextData() are sensitive to the executing thread. For example, given resource method
@GET
@Path("test")
@Produces("text/plain")
public CompletionStage text(@Context HttpRequest request) {
System.out.println("request (inline): " + request);
196
CompletionStage in JAX-RS
System.out.println("application
(inline):
"
+
ResteasyProviderFactory.getContextData(Application.class));
CompletableFuture cs = new CompletableFuture<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(
new Runnable() {
public void run() {
try {
System.out.println("request (async): " + request);
System.out.println("application (async): " +
ResteasyProviderFactory.getContextData(Application.class));
cs.complete("hello");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return cs;
}
the output will look something like
application
(inline):
$TestApp@23c57474
request
(inline):
org.jboss.resteasy.plugins.server.servlet.Servlet3AsyncHttpRequest@2ce23138
application (async): null
org.jboss.resteasy.spi.LoggableFailure: RESTEASY003880: Unable to
find contextual data of type: org.jboss.resteasy.spi.HttpRequest
The point is that it is the developer's responsibility to extract information from these
context objects in advance. For example:
@GET
@Path("test")
@Produces("text/plain")
public CompletionStage text(@Context HttpRequest req) {
System.out.println("request (inline): " + request);
System.out.println("application
(inline):
"
+
ResteasyProviderFactory.getContextData(Application.class));
CompletableFuture cs = new CompletableFuture<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
final String httpMethodFinal = request.getHttpMethod();
197
Chapter 39. Reactive programm...
final
Map
mapFinal
=
ResteasyProviderFactory.getContextData(Application.class).getProperties();
executor.submit(
new Runnable() {
public void run() {
System.out.println("httpMethod (async): " +
httpMethodFinal);
System.out.println("map (async): " + mapFinal);
cs.complete("hello");
}
});
return cs;
}
39.3. Beyond CompletionStage
The picture becomes more complex and interesting when sequences are added. A CompletionStage holds no more than one potential value, but other reactive objects can hold multiple, even
unlimited, values. Currently, most Java implementations of reactive programming are based on
the project Reactive Streams (http://www.reactive-streams.org/), which defines a set of four interfaces and a specification, in the form of a set of rules, describing how they interact:
public interface Publisher {
public void subscribe(Subscriber s);
}
public interface Subscriber {
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}
public interface Subscription {
public void request(long n);
public void cancel();
}
public interface Processor extends Subscriber, Publisher {
}
A Producer pushes objects to a Subscriber, a Subscription mediates the relationship between
the two, and a Processor which is derived from both, helps to construct pipelines through which
objects pass.
198
Pluggable reactive types: RxJava 2 in RESTEasy
One important aspect of the specification is flow control, the ability of a Suscriber to control the
load it receives from a Producer by calling Suscription.request(). The general term in this
context for flow control is backpressure.
There are a number of implementations of Reactive Streams, including
1. RxJava: https://github.com/ReactiveX/RxJava (end of life, superceded by RxJava 2)
2. RxJava 2: https://github.com/ReactiveX/RxJava
3. Reactor: http://projectreactor.io/
4. Flow: https://community.oracle.com/docs/DOC-1006738/ [https://community.oracle.com/docs/
DOC-1006738]: (Java JDK 9+)
RESTEasy currently supports RxJava (deprecated) and RxJava2.
39.4. Pluggable reactive types: RxJava 2 in RESTEasy
JAX-RS 2.1 doesn't require support for any Reactive Streams implementations, but it does allow
for extensibility to support various reactive libraries. RESTEasy's optional modules resteasy-rxjava1 and resteasy-rxjava2 add support for RxJava 1 and 2 [https://github.com/ReactiveX/RxJava]. [Only resteasy-rxjava2 will be discussed here, since resteasy-rxjava1 is deprecated,
but the treatment of the two is quite similar.]
In particular, resteasy-rxjava2 contributes support for reactive types io.reactivex.Single,
io.reactivex.Flowable, and io.reactivex.Observable. Of these, Single is similar to
CompletionStage in that it holds at most one potential value. Flowable implements
io.reactivex.Publisher, and Observable is very similar to Flowable except that it doesn't
support backpressure. So, if you import resteasy-rxjava2, you can just start returning these reactive types from your resource methods on the server side and receiving them on the client side.
1. Server side
Given the class Thing, which can be represented in JSON:
public class Thing {
private String name;
public Thing() {
}
public Thing(String name) {
this.name = name;
}
...
199
Chapter 39. Reactive programm...
}
the method postThingList() in the following is a valid resource method:
...
@POST
@Path("post/thing/list")
@Produces(MediaType.APPLICATION_JSON)
@Stream
public Flowable> postThingList(String s) {
return buildFlowableThingList(s, 2, 3);
}
static Flowable> buildFlowableThingList(String s, int listSize, int
elementSize) {
return Flowable.create(
new FlowableOnSubscribe>() {
@Override
public void subscribe(FlowableEmitter> emitter) throws
Exception {
for (int i = 0; i < listSize; i++) {
List list = new ArrayList();
for (int j = 0; j < elementSize; j++) {
list.add(new Thing(s));
}
emitter.onNext(list);
}
emitter.onComplete();
}
},
BackpressureStrategy.BUFFER);
}
The somewhat imposing method buildFlowableThingList() probably deserves some explanation. First,
Flowable> Flowable.create(FlowableOnSubscribe> source,
BackpressureStrategy mode);
200
Server side
creates
a
by
subscribed
Flowable>
Flowable>
is
describing what should happen when the
to. FlowableEmitter> extends
io.reactivex.Emitter>:
/**
* Base interface for emitting signals in a push-fashion in various generatorlike source
* operators (create, generate).
*
* @param the value type emitted
*/
public interface Emitter {
/**
* Signal a normal value.
* @param value the value to signal, not null
*/
void onNext(@NonNull T value);
/**
* Signal a Throwable exception.
* @param error the Throwable to signal, not null
*/
void onError(@NonNull Throwable error);
/**
* Signal a completion.
*/
void onComplete();
}
and FlowableOnSubscribe uses a FlowableEmitter to send out values from the
Flowable>:
/**
* A functional interface that has a {@code subscribe()} method that receives
* an instance of a {@link FlowableEmitter} instance that allows pushing
* events in a backpressure-safe and cancellation-safe manner.
*
* @param the value type pushed
*/
public interface FlowableOnSubscribe {
/**
201
Chapter 39. Reactive programm...
* Called for each Subscriber that subscribes.
* @param e the safe emitter instance, never null
* @throws Exception on error
*/
void subscribe(@NonNull FlowableEmitter e) throws Exception;
}
So, what will happen when a subscription to the Flowable> is created is, the
FlowableEmitter.onNext() will be called, once for each > created, followed by a
call to FlowableEmitter.onComplete() to indicate that the sequence has ended. Under the covers, RESTEasy subscribes to the Flowable> and handles each element passed
in by way of onNext().
2. Client side
On the client side, JAX-RS 2.1 supports extensions for reactive classes by adding the method
/**
* Access a reactive invoker based on a {@link RxInvoker} subclass provider. Note
* that corresponding {@link RxInvokerProvider} must be registered in the client
runtime.
*
* This method is an extension point for JAX-RS implementations to support
other types
* representing asynchronous computations.
*
* @param clazz {@link RxInvoker} subclass.
* @return reactive invoker instance.
* @throws IllegalStateException when provider for given class is not registered.
* @see javax.ws.rs.client.Client#register(Class)
* @since 2.1
*/
public T rx(Class clazz);
to interface javax.ws.rs.client.Invocation.Builder. Resteasy module resteasy-rxjava2
adds support for classes:
1. org.jboss.resteasy.rxjava2.SingleRxInvoker,
2. org.jboss.resteasy.rxjava2.FlowableRxInvoker
3. org.jbosss.resteasy.rxjava2.ObservableRxInvoker
which allow accessing Singles, Observables, and Flowables on the client side.
202
Representation on the wire
For example, given the resource method postThingList() above, a Flowable>
can be retrieved from the server by calling
@SuppressWarnings("unchecked")
@Test
public void testPostThingList() throws Exception {
CountDownLatch latch = new CountdownLatch(1);
FlowableRxInvoker invoker = client.target(generateURL("/post/thing/
list")).request().rx(FlowableRxInvoker.class);
Flowable>
flowable
=
(Flowable>)
invoker.post(Entity.entity("a",
MediaType.TEXT_PLAIN_TYPE),
GenericType>() {});
flowable.subscribe(
(List l) -> thingListList.add(l),
(Throwable t) -> latch.countDown(),
() -> latch.countDown());
latch.await();
Assert.assertEquals(aThingListList, thingListList);
}
where aThingListList is
[[Thing[a], Thing[a], Thing[a]], [Thing[a], Thing[a], Thing[a]]]
Note the call to Flowable.suscribe(). On the server side, RESTEasy subscribes to a returning
Flowable in order to receive its elements and send them over the wire. On the client side, the user
subscribes to the Flowable in order to receive its elements and do whatever it wants to with them.
In this case, three lambdas determine what should happen 1) for each element, 2) if a Throwable
is thrown, and 3) when the Flowable is done passing elements.
3. Representation on the wire
Neither Reactive Streams nor JAX-RS have anything to say about representing reactive types
on the network. RESTEasy offers a number of representations, each suitable for different circumstances. The wire protocol is determined by 1) the presence or absence of the @Stream annotation
on the resource method, and 2) the value of the value field in the @Stream annotation:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Stream
{
203
new
Chapter 39. Reactive programm...
public enum MODE {RAW, GENERAL};
public String INCLUDE_STREAMING_PARAMETER = "streaming";
public MODE value() default MODE.GENERAL;
public boolean includeStreaming() default false;
}
Note
that
MODE.GENERAL
is
the
default
value,
so
@Stream
is
equivalent
to
@Stream(Stream.MODE.GENERAL).
No @Stream annotation on the resource method
Resteasy will collect every value until the stream is complete, then wrap them into a
java.util.List entity and send to the client.
@Stream(Stream.MODE.GENERAL)
This case uses a variant of the SSE format, modified to eliminate some restrictions inherent in SSE. (See the specification at https://html.spec.whatwg.org/multipage/server-sentevents.html [https://html.spec.whatwg.org/multipage/server-sent-events.html] for details.) In
particular, 1) SSE events are meant to hold text data, represented in character set UTF-8. In
the general streaming mode, certain delimiting characters in the data ('\r', '\n', and '\') are escaped so that arbitrary binary data can be transmitted. Also, 2) the SSE specification requires
the client to reconnect if it gets disconnected. If the stream is finite, reconnecting will induce
a repeat of the stream, so SSE is really meant for unlimited streams. In general streaming
mode, the client will close, rather than automatically reconnect, at the end of the stream. It
follows that this mode is suitable for finite streams.
Note. The Content-Type header in general streaming mode is set to
applicaton/x-stream-general;"element-type="
where is the media type of the data elements in the stream. The element
media type is derived from the @Produces annotation. For example,
@GET
@Path("flowable/thing")
@Stream
@Produces("application/json")
public Flowable getFlowable() { ... }
induces the media type
204
Representation on the wire
application/x-stream-general;"element-type=application/json"
which describes a stream of JSON elements.
@Stream(Stream.MODE.RAW)
In this case each value is written directly to the wire, without any formatting, as it becomes
available. This is most useful for values that can be cut in pieces, such as strings, bytes,
buffers, etc., and then re-concatenated on the client side. Note that without delimiters as in
general mode, it isn't possible to reconstruct something like List>.
Note. The Content-Type header in raw streaming mode is derived from the @Produces annotation. The @Stream annotation offers the possibility of an optional MediaType parameter
called "streaming". The point is to be able to suggest that the stream of data emanating from
the server is unbounded, i.e., that the client shouldn't try to read it all as a single byte array, for
example. The parameter is set by explicitly setting the @Stream parameter includeStreaming() to true. For example,
@GET
@Path("byte/default")
@Produces("application/octet-stream;x=y")
@Stream(Stream.MODE.RAW)
public Flowable aByteDefault() {
return Flowable.fromArray((byte) 0, (byte) 1, (byte) 2);
}
induces the MediaType "application/octet-stream;x=y", and
@GET
@Path("byte/true")
@Produces("application/octet-stream;x=y")
@Stream(value=Stream.MODE.RAW, includeStreaming=true)
public Flowable aByteTrue() {
return Flowable.fromArray((byte) 0, (byte) 1, (byte) 2);
}
induces the MediaType "application/octet-stream;x=y;streaming=true".
Note that browsers such as Firefox and Chrome seem to be comfortable with reading unlimited
streams without any additional hints.
205
Chapter 39. Reactive programm...
4. Examples.
Example 1.
@POST
@Path("post/thing/list")
@Produces(MediaType.APPLICATION_JSON)
@Stream(Stream.MODE.GENERAL)
public Flowable> postThingList(String s) {
return buildFlowableThingList(s, 2, 3);
}
...
@SuppressWarnings("unchecked")
@Test
public void testPostThingList() throws Exception {
CountDownLatch latch = new CountdownLatch(1);
FlowableRxInvoker invoker = client.target(generateURL("/post/thing/
list")).request().rx(FlowableRxInvoker.class);
Flowable>
flowable
=
(Flowable>)
invoker.post(Entity.entity("a",
MediaType.TEXT_PLAIN_TYPE),
GenericType>() {});
flowable.subscribe(
(List l) -> thingListList.add(l),
(Throwable t) -> latch.countDown(),
() -> latch.countDown());
latch.await();
Assert.assertEquals(aThingListList, thingListList);
}
This is the example given previously, except that the mode in the @Stream annotation
(which defaults to MODE.GENERAL) is given explicitly. In this scenario, the Flowable emits
> elements on the server, they are transmitted over the wire as SSE events:
data: [{"name":"a"},{"name":"a"},{"name":"a"}]
data: [{"name":"a"},{"name":"a"},{"name":"a"}]
and the FlowableRxInvoker reconstitutes a Flowable on the client side.
Example 2.
@POST
206
new
Examples.
@Path("post/thing/list")
@Produces(MediaType.APPLICATION_JSON)
public Flowable> postThingList(String s) {
return buildFlowableThingList(s, 2, 3);
}
...
@Test
public void testPostThingList() throws Exception {
Builder request = client.target(generateURL("/post/thing/list")).request();
List>
list
=
request.post(Entity.entity("a",
MediaType.TEXT_PLAIN_TYPE), new GenericType>>() {});
Assert.assertEquals(aThingListList, list);
}
In this scenario, in which the resource method has no @Stream annotation, the Flowable emits
stream elements which are accumulated by the server until the Flowable is done, at which point
the entire JSON list is transmitted over the wire:
[[{"name":"a"},{"name":"a"},{"name":"a"}],[{"name":"a"},{"name":"a"},
{"name":"a"}]]
and the list is reconstituted on the client side by an ordinary invoker.
Example 3.
@GET
@Path("get/bytes")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Stream(Stream.MODE.RAW)
public Flowable getBytes() {
return Flowable.create(
new FlowableOnSubscribe() {
@Override
public void subscribe(FlowableEmitter emitter) throws Exception {
for (int i = 0; i < 3; i++) {
byte[] b = new byte[10];
for (int j = 0; j < 10; j++) {
b[j] = (byte) (i + j);
}
emitter.onNext(b);
}
emitter.onComplete();
}
207
Chapter 39. Reactive programm...
},
BackpressureStrategy.BUFFER);
}
...
@Test
public void testGetBytes() throws Exception {
Builder request = client.target(generateURL("/get/bytes")).request();
InputStream is = request.get(InputStream.class);
int n = is.read();
while (n > -1) {
System.out.print(n);
n = is.read();
}
}
Here, the byte arrays are written to the network as they are created by the Flowable. On the
network, they are concatenated, so the client sees one stream of bytes.
Note
Given that asynchronous code is common in this context, it is worth looking at the
earlier Note.
5. Rx and SSE
Since general streaming mode and SSE share minor variants of the same wire protocol, they are,
modulo the SSE restriction to character data, interchangeable. That is, an SSE client can connect
to a resource method that returns a Flowable or an Observable, and a FlowableRxInvoker, for
example, can connect to an SSE resource method.
Note. SSE requires a @Produces("text/event-stream") annotation, so, unlike the cases of raw
and general streaming, the element media type cannot be derived from the @Produces annotation.
To solve this problem, Resteasy introduces the
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SseElementType
{
public String value();
}
annotation, from which the element media type is derived.
Example 1.
208
Rx and SSE
@GET
@Path("eventStream/thing")
@Produces("text/event-stream")
@SseElementType("application/json")
public void eventStreamThing(@Context SseEventSink eventSink, @Context Sse sse) {
new ScheduledThreadPoolExecutor(5).execute(() -> {
try (SseEventSink sink = eventSink) {
OutboundSseEvent.Builder builder = sse.newEventBuilder();
eventSink.send(builder.data(new Thing("e1")).build());
eventSink.send(builder.data(new Thing("e2")).build());
eventSink.send(builder.data(new Thing("e3")).build());
}
});
}
...
@SuppressWarnings("unchecked")
@Test
public void testFlowableToSse() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger errors = new AtomicInteger(0);
FlowableRxInvoker invoker = client.target(generateURL("/eventStream/
thing")).request().rx(FlowableRxInvoker.class);
Flowable flowable = (Flowable) invoker.get(Thing.class);
flowable.subscribe(
(Thing t) -> thingList.add(t),
(Throwable t) -> errors.incrementAndGet(),
() -> latch.countDown());
boolean waitResult = latch.await(30, TimeUnit.SECONDS);
Assert.assertTrue("Waiting for event to be delivered has timed out.",
waitResult);
Assert.assertEquals(0, errors.get());
Assert.assertEquals(eThingList, thingList);
}
Here, a FlowableRxInvoker is connecting to an SSE resource method. On the network, the data
looks like
data: {"name":"e1"}
data: {"name":"e2"}
data: {"name":"e3"}
Note that the character data is suitable for an SSE resource method.
Also, note that the eventStreamThing() method in this example induces the media type
209
Chapter 39. Reactive programm...
text/event-stream;element-type="application/json"
Example 2.
@GET
@Path("flowable/thing")
@Produces("text/event-stream")
@SseElementType("application/json")
public Flowable flowableSSE() {
return Flowable.create(
new FlowableOnSubscribe() {
@Override
public void subscribe(FlowableEmitter emitter) throws Exception {
emitter.onNext(new Thing("e1"));
emitter.onNext(new Thing("e2"));
emitter.onNext(new Thing("e3"));
emitter.onComplete();
}
},
BackpressureStrategy.BUFFER);
}
...
@Test
public void testSseToFlowable() throws Exception {
final CountDownLatch latch = new CountDownLatch(3);
final AtomicInteger errors = new AtomicInteger(0);
WebTarget target = client.target(generateURL("/flowable/thing"));
SseEventSource msgEventSource = SseEventSource.target(target).build();
try (SseEventSource eventSource = msgEventSource)
{
eventSource.register(
event
->
{thingList.add(event.readData(Thing.class,
MediaType.APPLICATION_JSON_TYPE)); latch.countDown();},
ex -> errors.incrementAndGet());
eventSource.open();
boolean waitResult = latch.await(30, TimeUnit.SECONDS);
Assert.assertTrue("Waiting for event to be delivered has timed out.",
waitResult);
Assert.assertEquals(0, errors.get());
Assert.assertEquals(eThingList, thingList);
}
}
210
To stream or not to stream
Here, an SSE client is connecting to a resource method that returns a Flowable. Again, the server
is sending character data, which is suitable for the SSE client, and the data looks the same on
the network.
6. To stream or not to stream
Whether or not it is appropriate to stream a list of values is a judgment call. Certainly, if the list is
unbounded, then it isn't practical, or even possible, perhaps, to collect the entire list and send it
at once. In other cases, the decision is less obvious.
Case 1. Suppose that all of the elements are producible quickly. Then the overhead of sending
them independently is probably not worth it.
Case 2. Suppose that the list is bounded but the elements will be produced over an extended
period of time. Then returning the initial elements when they become available might lead to a
better user experience.
Case 3. Suppose that the list is bounded and the elements can be produced in a relatively short span of time but only after some delay. Here is a situation that illustrates the fact
that asynchronous reactive processing and streaming over the network are independent concepts. In this case it's worth considering having the resource method return something like
CompletionStage> rather than Flowable>. This has the benefit of
creating the list asynchronously but, once it is available, sending it to the client in one piece.
39.5. Proxies
Proxies, discussed in RESTEasy Proxy Framework, are a RESTEasy extension that supports
a natural programming style in which generic JAX-RS invoker calls are replaced by application
specific interface calls. The proxy framework is extended to include both CompletionStage and
the RxJava2 types Single, Observable, and Flowable.
Example 1.
@Path("")
public interface RxCompletionStageResource {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage getString();
}
@Path("")
public class RxCompletionStageResourceImpl {
@GET
@Path("get/string")
211
Chapter 39. Reactive programm...
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage getString() { .... }
}
public class RxCompletionStageProxyTest {
private static ResteasyClient client;
private static RxCompletionStageResource proxy;
static {
client = new ResteasyClientBuilder().build();
proxy
client.target(generateURL("/")).proxy(RxCompletionStageResource.class);
}
@Test
public void testGet() throws Exception {
CompletionStage completionStage = proxy.getString();
Assert.assertEquals("x", completionStage.toCompletableFuture().get());
}
}
Example 2.
public interface Rx2FlowableResource {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
@Stream
public Flowable getFlowable();
}
@Path("")
public class Rx2FlowableResourceImpl {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
@Stream
public Flowable getFlowable() { ... }
}
public class Rx2FlowableProxyTest {
private static ResteasyClient client;
212
=
Adding extensions
private static Rx2FlowableResource proxy;
static {
client = new ResteasyClientBuilder().build();
proxy = client.target(generateURL("/")).proxy(Rx2FlowableResource.class);
}
@Test
public void testGet() throws Exception {
Flowable flowable = proxy.getFlowable();
flowable.subscribe(
(String o) -> stringList.add(o),
(Throwable t) -> errors.incrementAndGet(),
() -> latch.countDown());
boolean waitResult = latch.await(30, TimeUnit.SECONDS);
Assert.assertTrue("Waiting for event to be delivered has timed out.",
waitResult);
Assert.assertEquals(0, errors.get());
Assert.assertEquals(xStringList, stringList);
}
}
39.6. Adding extensions
RESTEasy implements a framework that supports extensions for additional reactive classes. To
understand the framework, it is necessary to understand the existing support for CompletionStage and other reactive classes.
Server
side.
pletionStage,
When
RESTEasy
a
resource
subscribes
to
method
it
returns
using
a
the
Com-
class
org.jboss.resteasy.core.AsyncResponseConsumer.CompletionStageResponseConsumer.
When the CompletionStage completes, it calls CompletionStageResponseConsumer.accept(),
which sends the result back to the client.
Support for CompletionStage is built in to RESTEasy, but it's not hard to extend that support to a class like Single by providing a mechanism for transforming a Single into a CompletionStage. In module resteasy-rxjava2, that mechanism is
supplied by org.jboss.resteasy.rxjava2.SingleProvider, which implements interface
org.jboss.resteasy.spi.AsyncResponseProvider>:
public interface AsyncResponseProvider {
public CompletionStage toCompletionStage(T asyncResponse);
}
213
Chapter 39. Reactive programm...
Given SingleProvider, RESTEasy can take a Single, transform it into a CompletionStage, and
then use CompletionStageResponseConsumer to handle the eventual value of the Single.
Similarly, when a resource method returns a streaming reactive class like Flowable, RESTEasy
subscribes to it, receives a stream of data elements, and sends them to the client. AsyncResponseConsumer has several supporting classes, each of which implements a different mode of streaming. For example, AsyncResponseConsumer.AsyncGeneralStreamingSseResponseConsumer
handles general streaming and SSE streaming. Subscribing is done by calling org.reactivestreams.Publisher.subscribe(), so a mechanism is needed
for turning, say, a Flowable into a Publisher. That is, an implementation of org.jboss.resteasy.spi.AsyncStreamProvider is called for, where
AsyncStreamProvider is defined:
public interface AsyncStreamProvider {
public Publisher toAsyncStream(T asyncResponse);
}
In module resteasy-rxjava2, org.jboss.resteasy.FlowableProvider provides that mechanism
for Flowable. [Actually, that's not too hard since, in rxjava2, a Flowable is a Provider.]
So, on the server side, adding support for other reactive types can be done by declaring a
@Provider for the interface AsyncStreamProvider (for streams) or AsyncResponseProvider (for
single values), which both have a single method to convert the new reactive type into (respectively) a Publisher (for streams) or a CompletionStage (for single values).
Client side. The JAX-RS specification version 2.1 imposes two requirements for support of reactive classes on the client side:
1. support for CompletionStage in the form of an implementation of the interface
javax.ws.rs.client.CompletionStageRxInvoker, and
2. extensibility in the form of support for registering providers that implement
public interface RxInvokerProvider {
public boolean isProviderFor(Class clazz);
public T getRxInvoker(SyncInvoker syncInvoker,
executorService);
}
ExecutorService
Once an RxInvokerProvider is registered, an RxInvoker can be requested by calling the
javax.ws.rs.client.Invocation.Builder method
214
Adding extensions
public T rx(Class