Modified: websites/production/cxf/content/docs/jax-rs-basics.html
==============================================================================
--- websites/production/cxf/content/docs/jax-rs-basics.html (original)
+++ websites/production/cxf/content/docs/jax-rs-basics.html Wed Sep 13 15:05:52 
2017
@@ -32,9 +32,9 @@
 <link type="text/css" rel="stylesheet" 
href="/resources/highlighter/styles/shThemeCXF.css">
 
 <script src='/resources/highlighter/scripts/shCore.js'></script>
-<script src='/resources/highlighter/scripts/shBrushJava.js'></script>
-<script src='/resources/highlighter/scripts/shBrushXml.js'></script>
 <script src='/resources/highlighter/scripts/shBrushBash.js'></script>
+<script src='/resources/highlighter/scripts/shBrushXml.js'></script>
+<script src='/resources/highlighter/scripts/shBrushJava.js'></script>
 <script>
   SyntaxHighlighter.defaults['toolbar'] = false;
   SyntaxHighlighter.all();
@@ -122,11 +122,11 @@ Apache CXF -- JAX-RS Basics
 
 
 &#160;</p><p>&#160;</p><p><style type="text/css">/*<![CDATA[*/
-div.rbtoc1505311213216 {padding: 0px;}
-div.rbtoc1505311213216 ul {list-style: disc;margin-left: 0px;}
-div.rbtoc1505311213216 li {margin-left: 0px;padding-left: 0px;}
+div.rbtoc1505314981880 {padding: 0px;}
+div.rbtoc1505314981880 ul {list-style: disc;margin-left: 0px;}
+div.rbtoc1505314981880 li {margin-left: 0px;padding-left: 0px;}
 
-/*]]>*/</style></p><div class="toc-macro rbtoc1505311213216">
+/*]]>*/</style></p><div class="toc-macro rbtoc1505314981880">
 <ul class="toc-indentation"><li><a shape="rect" 
href="#JAX-RSBasics-WhatisNewinJAX-RS2.1">What is New in JAX-RS 2.1</a>
 <ul class="toc-indentation"><li><a shape="rect" 
href="#JAX-RSBasics-ReactiveClientAPI">Reactive Client API</a>
 <ul class="toc-indentation"><li><a shape="rect" 
href="#JAX-RSBasics-CompletionStage">CompletionStage</a></li><li><a 
shape="rect" href="#JAX-RSBasics-RxJava">RxJava</a></li></ul>
@@ -153,7 +153,7 @@ div.rbtoc1505311213216 li {margin-left:
 <ul class="toc-indentation"><li><a shape="rect" 
href="#JAX-RSBasics-CustomMessageBodyProviders">Custom Message Body 
Providers</a></li><li><a shape="rect" 
href="#JAX-RSBasics-Registeringcustomproviders">Registering custom 
providers</a></li></ul>
 </li><li><a shape="rect" 
href="#JAX-RSBasics-Customizingmediatypesformessagebodyproviders">Customizing 
media types for message body providers</a></li><li><a shape="rect" 
href="#JAX-RSBasics-AdvancedHTTP">Advanced HTTP</a></li></ul>
 </div><h1 id="JAX-RSBasics-WhatisNewinJAX-RS2.1">What is New in JAX-RS 
2.1</h1><h2 id="JAX-RSBasics-ReactiveClientAPI">Reactive Client 
API</h2><p>JAX-RS 2.1 introduces <a shape="rect" class="external-link" 
href="https://github.com/jax-rs/api/blob/master/jaxrs-api/src/main/java/javax/ws/rs/client/RxInvoker.java";
 rel="nofollow">RxInvoker</a> which can help with removing <a shape="rect" 
class="external-link" 
href="https://github.com/jax-rs/api/blob/master/jaxrs-api/src/main/java/javax/ws/rs/client/InvocationCallback.java";
 rel="nofollow">InvocationCallback</a>s from the asynchronous client 
code.&#160;</p><h3 
id="JAX-RSBasics-CompletionStage">CompletionStage</h3><p>Default <a 
shape="rect" class="external-link" 
href="https://github.com/jax-rs/api/blob/master/jaxrs-api/src/main/java/javax/ws/rs/client/CompletionStageRxInvoker.java";
 rel="nofollow">CompletionStageRxInvoker</a> can be accessed via <a 
shape="rect" class="external-link" 
href="https://github.com/jax-rs/api/blob/master/jaxrs-api/
 src/main/java/javax/ws/rs/client/RxInvoker.java" 
rel="nofollow">Invocation.rx()</a>.</p><h3 
id="JAX-RSBasics-RxJava">RxJava</h3><p>Custom <a shape="rect" 
class="external-link" 
href="https://github.com/jax-rs/api/blob/master/jaxrs-api/src/main/java/javax/ws/rs/client/RxInvokerProvider.java";
 rel="nofollow">RxInvokerProvider</a> can be registered with the Client as a 
provider. CXF ships one three such custom 
providers,&#160;org.apache.cxf.jaxrs.rx.client.ObservableRxInvokerProvider 
(RxJava1),</p><p>org.apache.cxf.jaxrs.rx2.client.ObservableRxInvokerProvider 
(RxJava2) and org.apache.cxf.jaxrs.rx2.client.FlowableRxInvokerProvider 
(RxJava2).</p><p>Registering it with the Client allows for working with RxJava1 
Observable or RxJava2 Observable or Flowable by doing&#160;<a shape="rect" 
class="external-link" 
href="https://github.com/jax-rs/api/blob/master/jaxrs-api/src/main/java/javax/ws/rs/client/Invocation.java#L312";
 rel="nofollow">Invocation.rx(Class&lt;T&gt; clazz)</a>, example,</p><p>Inv
 ocation.rx(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvoker.class), 
etc.</p><p>Please see <a shape="rect" href="jax-rs-rxjava.html">JAX-RS 
RxJava</a> for more information.</p><h2 
id="JAX-RSBasics-CompletableFutureasamethodreturnvalue">CompletableFuture as a 
method return value</h2><p>In JAX-RS 2.1 one can return&#160;CompletableFuture 
(or CompletionStage) from a resource method without having to deal directly 
with JAX-RS AsyncResponse API.&#160;</p><p>Please see <a shape="rect" 
href="jax-rs-rxjava.html">JAX-RS RxJava</a> for more information about 
returning RxJava Observable.</p><h2 id="JAX-RSBasics-ServerSentEvents">Server 
Sent Events</h2><p>JAX-RS 2.1 provides a <a shape="rect" class="external-link" 
href="https://github.com/jax-rs/api/tree/master/examples/src/main/java/jaxrs/examples/sse";
 rel="nofollow">comprehensive support</a> for <a shape="rect" 
class="external-link" href="https://en.wikipedia.org/wiki/Server-sent_events"; 
rel="nofollow">SSE</a>.</p><p>org.apache.cxf/cxf-rt-rs-
 sse/3.2.0 dependency will need to be added. CXF SSE implementation currently 
depends on Atmosphere.</p><h2 
id="JAX-RSBasics-SubResourcesasClasses">SubResources as 
Classes</h2><p>Sometimes subresource may need to have the request context 
information available to them. One valid and simple approach is to pass these 
contexts to them from the parent class which instantiates a subresource - but 
sometimes this approach does not work.</p><p>In JAX-RS 2.0 one can use <a 
shape="rect" class="external-link" 
href="https://github.com/jax-rs/api/blob/master/jaxrs-api/src/main/java/javax/ws/rs/container/ResourceContext.java";
 rel="nofollow">ResourceContext</a> to instantiate a subresource instance with 
the runtime taking care of injecting the contexts if needed. JAX-RS 2.1 
introduces a shortcut where returning a subresource class from a subresource 
locator method, with the runtime istantiating the class and injecting the 
contexts if needed</p><h2 id="JAX-RSBasics-CXFNIOExtension">CXF NIO Extension<
 /h2><p>Please see <a shape="rect" href="jax-rs-nio.html">JAX-RS NIO</a> for 
more information about this CXF 3.2.0 extension which is based on the early 
JAX-RS 2.1 API prototype.</p><h1 id="JAX-RSBasics-WhatisNewinJAX-RS2.0">What is 
New in JAX-RS 2.0</h1><h2 id="JAX-RSBasics-Filters">Filters</h2><h3 
id="JAX-RSBasics-Server">Server</h3><p><a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/ContainerRequestFilter.html";
 rel="nofollow">ContainerRequestFilter</a> and <a shape="rect" 
class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/ContainerResponseFilter.html";
 rel="nofollow">ContainerResponseFilter</a> are new server-side request and 
response filters which can be used to customize various properties of a given 
request and response.</p><p>ContainerRequestFilter annotated with a <a 
shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/PreMatching.html";
 rel="
 nofollow">PreMatching</a> annotation will be run before the runtime has 
matched a request to a specific JAX-RS root resource and method. Prematching 
filters can be used to affect the matching process.</p><p>The request filters 
without the PreMatching annotation will run after the JAX-RS resource method 
has been selected.</p><p>ContainerRequestFilter can be used to <a shape="rect" 
class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/ContainerRequestContext.html#abortWith(javax.ws.rs.core.Response)"
 rel="nofollow">block</a> a request.</p><p>The filters can be bound to 
individual resource methods only with the help of custom <a shape="rect" 
class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/NameBinding.html"; 
rel="nofollow">NameBinding</a>s.</p><p>Multiple request and response filters 
can be executed in the specific order by using javax.annotation.Priority 
annotations. See <a shape="rect" class="external-link" href="https://jax
 -rs.github.io/apidocs/2.0/javax/ws/rs/Priorities.html" 
rel="nofollow">Priorities</a> for more information. Request filters are sorted 
in the ascending order, response filters - in the descending order.</p><h3 
id="JAX-RSBasics-Client">Client</h3><p><a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/client/ClientRequestFilter.html";
 rel="nofollow">ClientRequestFilter</a> and <a shape="rect" 
class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/client/ClientResponseFilter.html";
 rel="nofollow">ClientResponseFilter</a> are new client-side request and 
response filters which can be used to customize various properties of a given 
request and response.</p><p>ClientRequestFilter can be used to <a shape="rect" 
class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/client/ClientRequestContext.html#abortWith(javax.ws.rs.core.Response)"
 rel="nofollow">block</a> a request.</p><p>Request filters are sorted in the 
 ascending order, response filters - in the descending order. See <a 
shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/Priorities.html"; 
rel="nofollow">Priorities</a> for more information.</p><h2 
id="JAX-RSBasics-Interceptors">Interceptors</h2><p><a shape="rect" 
class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/ext/ReaderInterceptor.html";
 rel="nofollow">ReaderInterceptor</a> and <a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/ext/WriterInterceptor.html";
 rel="nofollow">WriterInterceptor</a> can be used in addition to filters or on 
its own to customize requests and responses on server and client 
sides.</p><p>Interceptors can be useful to customize the reading/writing 
process and block JAX-RS MessageBodyWriter or MessageBodyReader 
providers.</p><p>The interceptors used on the server side can be bound to 
individual resource methods only with the help of custom <a shape="rect" cl
 ass="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/NameBinding.html"; 
rel="nofollow">NameBinding</a>s.</p><p>All interceptors are sorted in the 
ascending order. See <a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/Priorities.html"; 
rel="nofollow">Priorities</a> for more information.</p><h2 
id="JAX-RSBasics-DynamicFeatures">Dynamic Features</h2><p><a shape="rect" 
class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/DynamicFeature.html";
 rel="nofollow">Dynamic Feature</a> is a server side feature that can be used 
to attach request and response filters as well as reader and writer 
interceptors to specific resource methods. It is an alternative approach to 
using the NameBindings and offer a finer-grained control over the binding 
process.</p><h2 id="JAX-RSBasics-Exceptions">Exceptions</h2><p>Dedicated 
exception classes representing various HTTP error or redirect conditions have 
been introdu
 ced, see the 'javax.ws.rs' Package <a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/package-frame.html"; 
rel="nofollow">Exceptions section</a>.</p><p>For example, instead of throwing a 
"new WebApplicationException(404)" one is better to do "new 
NotFoundException()". The finer-grained exception hierarchy allows for a 
finer-grained support of exception mappers. It also opens a way to check 
WebApplicationException and all of its subclasses when catching the HTTP 
exceptions on the client side.</p><p>Note that on the client side, 
ProcessingException can be used to catch client-related exceptions while 
ResponseProcessingException can be used to narrow down the client side 
exceptions specifically related to processing the response message.</p><h2 
id="JAX-RSBasics-Suspendedinvocations">Suspended invocations</h2><p>One of the 
best JAX-RS 2.0 features is the support for server-side asynchronous 
invocations. Please see the <a shape="rect" class="exter
 nal-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/AsyncResponse.html";
 rel="nofollow">AsyncResponse</a> documentation which provides a very good 
overview of this feature.</p><p>See also this <a shape="rect" 
class="external-link" 
href="https://github.com/apache/cxf/blob/master/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookContinuationStore.java";
 rel="nofollow">test resource</a>.</p><p>Typically, the resource method 
accepting AsyncResponse will either store it and start a new thread to finish 
the request, the method will return and the invocation will be suspended, then 
eventually another thread (either the one which initiated an internal job or 
some other thread) will resume the suspended call. Note in this case the 
invocation will be suspended indefinitely until it is resumed.</p><p>Another 
approach is to have AsyncResponse suspended for a limited period of time only 
and also register a <a shape="rect" class="external-link" href="https://jax-r
 s.github.io/apidocs/2.0/javax/ws/rs/container/TimeoutHandler.html" 
rel="nofollow">TimeoutHandler</a>. The latter will be invoked when the 
invocation is resumed by the container after the timeout has expired and the 
handler will either complete the invocation or suspend it again till it is 
ready to finish it.</p><p><a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/CompletionCallback.html";
 rel="nofollow">CompletionCallback</a> can be registered with AsyncResponse to 
receive the notifications when the async response has been sent back.</p><p><a 
shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/ConnectionCallback.html";
 rel="nofollow">ConnectionCallback</a> is supported starting from CXF 
3.0.0-milestone2.</p><p>This feature can help developers write very 
sophisticated asynchronous applications.</p><p>Please also see the page about 
CXF <a shape="rect" href="continuations.html">Continuati
 ons</a> API which JAX-RS 2.0 AsyncResponse implementation is based upon and 
<br clear="none"> <a shape="rect" 
href="http://cxf.apache.org/docs/servlet-transport.html";>how to configure</a> 
CXFServlet.</p><h2 id="JAX-RSBasics-Parameterconverters">Parameter 
converters</h2><p><a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/ext/ParamConverterProvider.html";
 rel="nofollow">ParamConverterProvider</a> can be used to manage the conversion 
of custom Objects to String and vice versa on the server and client sides, when 
processing JAX-RS parameters representing URI parts or headers or form elements 
and when a default conversion mechanism does not work. For example, 
java.util.Date constructor accepting a String may have to be replaced a custom 
ParamConverter.</p><h2 id="JAX-RSBasics-Beanparameters">Bean 
parameters</h2><p><a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/BeanParam.html"; 
rel="nofollow">BeanParam
 </a> can be used to get JAX-RS parameters representing URI parts or headers or 
form elements and also contexts injected into a single bean 
container.</p><p>Note the CXF extension supporting the injection of all the 
parameters of specific JAX-RS type (example, QueryParam("") MyBean) is 
different, it only allows to get all the query parameters injected, but it also 
does not require that bean properties are annotated with QueryParam/etc 
annotations.</p><h2 id="JAX-RSBasics-ResourceInfo">ResourceInfo</h2><p><a 
shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/ResourceInfo.html";
 rel="nofollow">ResourceInfo</a> is a new JAX-RS context which can be injected 
into filters and interceptors and checked which resource class and method are 
about to be invoked.</p><h2 
id="JAX-RSBasics-Injectionintosubresources">Injection into 
subresources</h2><p>Subresources can get JAX-RS contexts injected directly into 
their fields with the help of <a shape="rec
 t" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/container/ResourceContext.html";
 rel="nofollow">ResourceContext</a>.</p><p>When possible, having a parent 
resource injecting the contexts into a given subresource instance via a setter 
or constructor can offer a much simpler alternative.</p><h2 
id="JAX-RSBasics-Updatestothematchingalgorithm">Updates to the matching 
algorithm</h2><p>JAX-RS 2.0 supports a proper resource method selection in 
cases where multiple root resource classes have the same Path value, for 
example:</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/")
 public class Root1 {
    @Path("/1")
    @GET 
@@ -168,7 +168,7 @@ public class Root2 {
 }
 </pre>
 </div></div><p>In JAX-RS 1.1 a request with URI such as "/1" is not guaranteed 
to be matched and in CXF 2.7.x or earlier the use of CXF specific 
ResourceComparator is required to ensure Root1 and its get() method gets 
selected. In CXF 3.0.0 Root1 get() will always be correctly selected. Note 
ResourceComparator may still be of help in some cases even in CXF 3.0.0.</p><h2 
id="JAX-RSBasics-Link">Link</h2><p><a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/core/Link.html"; 
rel="nofollow">Link</a> is a utility class for building HTTP links as HTTP Link 
headers or application data links. <br clear="none"> UriInfo, UriBuilder, 
Response and ResponseBuilder classes have been enhanced to support Link.</p><h2 
id="JAX-RSBasics-ClientAPI">Client API</h2><p>JAX-RS 2.0 Client API has been 
completely implemented in CXF 3.0.0, please see the <a shape="rect" 
href="http://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-JAXRS2.0ClientAPI";>Client
 API
  page</a> for more information.</p><h1 
id="JAX-RSBasics-Resourceclass">Resource class</h1><p>A resource class is a 
Java class annotated with JAX-RS annotations to represent a Web resource. Two 
types of resource classes are available: root resource classes and subresource 
classes. A root resource class is annotated with at least a @Path annotation, 
while subresource classes typically have no root @Path values. A typical root 
resource class in JAX-RS looks like this below:</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">package demo.jaxrs.server;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">package demo.jaxrs.server;
 
 import java.util.HashMap;
 import java.util.Map;
@@ -224,7 +224,7 @@ public class CustomerService {
 }
 </pre>
 </div></div><p>Customer resource class can handle requests starting from 
/customerservice. When /customerservice requests are matched to this class, its 
getCustomers() method will be selected. updateCustomer(), deleteCustomer() and 
addCustomer() are used to serve POST, PUT and DELETE requests starting from 
/customerservice/customer, while getOrder() method delegates the handling of 
requests like /customerservice/orders/1 to a subresource locator 
Order.</p><p>The @Produces annotation is used to specify the format of the 
response. When not available on the resource method, it's inherited from a 
class, and if it's not available on the class then it's inherited from a 
corresponding message body writer, if any. Default value is */*, but it's 
recommended that some definite value is specified. The same applies to 
@Consumes, except that it's the message body <em>readers</em> that are checked 
as the last resort.</p><p>For example, getCustomers() method inherits @Produces 
annotation from its 
 class, while getCustomer() method overrides it with its own value.</p><h1 
id="JAX-RSBasics-@Path">@Path</h1><p>The @Path annotation is applied to 
resource classes or methods. The value of @Path annotation is a relative URI 
path and follows the URI Template format and may include arbitrary regular 
expressions. When not available on the resource method, it's inherited from a 
class. For example:</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customers/{id}")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customers/{id}")
 public class CustomerResource {
 
     @GET
@@ -250,7 +250,7 @@ public class CustomerResource {
 
 </pre>
 </div></div><p>This example is similar to the one above it, but it also shows 
that an {id} template variable specified as part of the root @Path expression 
is reused by resource methods and a custom regular expression is specified by a 
findItem() method (note that a variable name is separated by ':' from an actual 
expression).</p><p>In this example, a request like 'GET 
/customers/1/order/2/price/2000/weight/2' will be served by the findItem() 
method.<br clear="none"> List&lt;PathSegment&gt; can be used to get to all the 
path segments in 'price/2000/weight/2' captured by the regular 
expression.</p><p>More information about Path annotations can be found from <a 
shape="rect" class="external-link" href="http://jcp.org/en/jsr/detail?id=311"; 
rel="nofollow">JAX-RS spec </a> section 2.3.</p><h1 
id="JAX-RSBasics-HTTPMethod">HTTP Method</h1><p>The JAX-RS specification 
defines a number of annotations such as @GET, @PUT, @POST and @DELETE. Using an 
@HttpMethod designator, one can create a custo
 m annotation such as @Update or @Patch. For example :</p><div class="code 
panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">package org.apache.cxf.customverb;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">package org.apache.cxf.customverb;
 
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
@@ -264,7 +264,7 @@ public @interface PATCH {
 }
 </pre>
 </div></div><h2 id="JAX-RSBasics-DefaultHttpMethod">Default Http 
Method</h2><p>CXF 3.0.4 introduces a new extension, a 
org.apache.cxf.jaxrs.ext.DefaultMethod annotation. It can be used to match 
arbitrary HTTP methods on a single resource method. This can be used in some 
advanced scenarious for integrating the CXF JAX-RS runtime into non-JAX-RS 
environments as well as in cases where it is awkward/difficult to have every 
HTTP method listed for a given path segment. CXF users need to be aware using 
this option will lead to a non-portable JAX-RS code.</p><p>&#160;</p><h1 
id="JAX-RSBasics-Returntypes">Return types</h1><p>Either 
javax.ws.rs.core.Response or custom type can be returned. 
javax.ws.rs.core.Response can be used to set the HTTP response code, headers 
and entity. JAX-RS MessageBodyWriters (see below) are in charge of serializing 
the response entities, those which are returned directly or as part of 
javax.ws.rs.core.Response.</p><h1 id="JAX-RSBasics-ResponseStreaming">Response 
St
 reaming&#160;</h1><h2 id="JAX-RSBasics-JAX-RSStreamingOutput">JAX-RS 
StreamingOutput</h2><p><a shape="rect" class="external-link" 
href="https://jax-rs.github.io/apidocs/2.0/javax/ws/rs/core/StreamingOutput.html";
 rel="nofollow">StreamingOutput</a> can be used to stream the data to the 
client, for example:</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@GET
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@GET
 @Path("/books/pdf")
 @Produces("application/pdf")
 public StreamingOutput getPdf() {
@@ -276,7 +276,7 @@ public StreamingOutput getPdf() {
 }
 </pre>
 </div></div><h2 id="JAX-RSBasics-CXFStreamingResponse">CXF 
StreamingResponse</h2><p>CXF 3.0.0 introduces <a shape="rect" 
class="external-link" 
href="https://git-wip-us.apache.org/repos/asf?p=cxf.git;a=blob;f=rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/StreamingResponse.java";>StreamingResponse</a>
 extension. It can be used with the WebSocket transport or as a possible 
replacement for the code working with StreamingOutput.</p><p><a shape="rect" 
class="external-link" 
href="https://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/core/StreamingOutput.html";
 rel="nofollow">F</a>or example, consider that a number of resources need to be 
returned as they become available:</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@GET
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@GET
 @Path("/books")
 @Produces("application/xml")
 public StreamingResponse&lt;Book&gt; getBooks() {
@@ -291,7 +291,7 @@ public StreamingResponse&lt;Book&gt; get
 }
 </pre>
 </div></div><h1 id="JAX-RSBasics-Exceptionhandling">Exception 
handling</h1><p>One can either throw an unchecked WebApplicationException or 
return Response with a proper error code set.<br clear="none"> The former 
option may be a better one when no JAX-RS types can be added to method 
signatures.</p><p>For example :</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customerservice/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customerservice/")
 public class CustomerService {
 
     
@@ -310,18 +310,18 @@ public class CustomerService {
 }
 </pre>
 </div></div><p>Yet another option is to register an ExceptionMapper provider. 
Ex :</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">public BookExceptionMapper implements 
ExceptionMapper&lt;BookException&gt; {
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">public BookExceptionMapper implements 
ExceptionMapper&lt;BookException&gt; {
     public Response toResponse(BookException ex) {
         // convert to Response
     }
 }
 </pre>
 </div></div><p>This allows for throwing a checked or runtime exception from an 
application code and map it to an HTTP response in a registered 
provider.</p><p>Have a look please at <a shape="rect" class="external-link" 
href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/security/SecurityExceptionMapper.java";>this
 exception mapper</a> which converts Spring Security exceptions into HTTP 403 
error code for another example.</p><p>Note that when no mappers are found for 
custom exceptions, they are propagated to the underlying container as required 
by the specification where they will typically be wrapped in ServlerException, 
eventually resulting in HTTP 500 status being returned by default. Thus one 
option for intercepting the exceptions is to register a custom servlet filter 
which will catch ServletExceptions and handle the causes.</p><p>This 
propagation can be disabled by registering a boolean jaxrs property 
'org.apache.cxf.propagat
 e.exception' with a false value. If such property is set and no exception 
mapper can be found for a given exception then it will be wrapped into an xml 
error response by the CXF <a shape="rect" class="external-link" 
href="http://svn.apache.org/repos/asf/cxf/trunk/rt/bindings/xml/src/main/java/org/apache/cxf/binding/xml/interceptor/XMLFaultOutInterceptor.java";>XMLFaultOutInterceptor</a>.</p><p>One
 can also register a custom CXF out fault interceptor which can handle all the 
exceptions by writing directly to the HttpServletResponse stream or 
XMLStreamWriter (as XMLFaultOutInterceptor does). For example, see this <a 
shape="rect" class="external-link" 
href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/CustomOutFaultInterceptor.java";>test
 interceptor</a>.</p><h2 
id="JAX-RSBasics-MappingexceptionsthrownfromCXFinterceptors">Mapping exceptions 
thrown from CXF interceptors</h2><p>Starting from CXF 2.7.8 it is also possible 
to use registe
 red ExceptionMappers to map the exceptions thrown from CXF server in 
interceptors which are registered after JAXRSInInterceptor (Phase.UNMARSHAL) 
and out interceptors registered before JAXRSOutInterceptor (Phase.MARSHAL).<br 
clear="none"> In earlier CXF versions such exceptions are only possible to 
handle with CXF fault in interceptors.</p><p>In order to get the exceptions 
thrown from CXF in interceptors mapped, set a "map.cxf.interceptor.fault" 
contextual property to true - needed in CXF 2.7.8 to ensure existing in fault 
interceptors are not affected; the mapping is done by default starting from CXF 
3.0.0.</p><p>In order to get the exceptions thrown from CXF out interceptors 
mapped, add org.apache.cxf.jaxrs.interceptor.JAXRSOutExceptionMapperInterceptor 
to the list of out interceptors.</p><h2 
id="JAX-RSBasics-CustomizingdefaultWebApplicationExceptionmapper">Customizing 
default WebApplicationException mapper</h2><p>CXF ships a 
WebApplicationException mapper, org.apache.cxf.jaxrs.imp
 l.WebApplicationExceptionMapper. By default it logs a stack trace at a warning 
level and returns Response available in the captured exception.<br 
clear="none"> It can be configured to log a stack trace at a trace level, by 
setting a 'printStackTrace' property to 'false'. Alternatively, if 
org.apache.cxf.logging.FaultListener is registered (as a contextual property) 
and indicates that it handled a given exception, then no more logging is 
done.</p><p>A simple text error message can also be optionally reported, by 
setting an 'addMessageToResponse' property to 'true', example:</p><div 
class="code panel pdl" style="border-width: 1px;"><div class="codeContent 
panelContent pdl">
-<pre class="brush: xml; gutter: false; theme: Confluence" 
style="font-size:12px;">&lt;bean id="exceptionMapper" 
class="org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper"&gt;
+<pre class="brush: xml; gutter: false; theme: Default" 
style="font-size:12px;">&lt;bean id="exceptionMapper" 
class="org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper"&gt;
    &lt;property name="addMessageToResponse" value="true" /&gt;
 &lt;/bean&gt;</pre>
 </div></div><p><br clear="none"> Note that the custom WebApplicationException 
mapper, if registered, will be preferred to the default one.</p><h1 
id="JAX-RSBasics-DealingwithParameters">Dealing with 
Parameters</h1><p>PathParam annotation is used to map a given Path template 
variable to a method parameter.<br clear="none"> For example :</p><div 
class="code panel pdl" style="border-width: 1px;"><div class="codeContent 
panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customer/{id}")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customer/{id}")
 public class CustomerService {
 
     
@@ -333,7 +333,7 @@ public class CustomerService {
 }
 </pre>
 </div></div><p>In this case a template variable id available from a root class 
annotation is mapped to a parameter of type Long, while a name variable is 
mapped to a parameter of type String.</p><p>@QueryParam, @HeaderParam, 
@MatrixParam, @FormParam and @CookieParam annotations are also 
supported.</p><p>Note that the parameters, marked with @FormParam annotation, 
can take the values from the query parameters in case, if request body is 
already consumed. This is defined in JAX-RS specification due to the filters 
(Spring security, etc) consuming the body and thus JAX-RS form parameters 
becoming empty. User can optionally deactivate standard behavior through 
setting "set.form.parameters.from.http.parameters" message property to 
false.</p><p>Parameters can be of type String or of any type that have 
constructors accepting a String parameter or stat ic valueOf(String s) methods. 
<br clear="none"> Additionally CXF JAXRS checks for static fromString(String s) 
method, so types with no valueO
 f(String) factory methods can also be dealt with:</p><div class="code panel 
pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">public enum Gender {
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">public enum Gender {
    MALE,
    FEMALE;
 
@@ -359,7 +359,7 @@ public class Service {
 }
 </pre>
 </div></div><p>Note that on the trunk enums with fromValue() factory methods 
are also supported.</p><p>JAX-RS PathSegment is also supported. A sequence of 
identically named parameters (queries, headers, etc) can be mapped to List or 
Set or SortedSet.</p><p>CXF JAXRS supports ParameterHandler extensions which 
can be used to deal with method parameters annotated with one of the JAXRS 
parameter annotations :</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">public class MapHandler implements 
ParameterHandler&lt;Map&gt; {
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">public class MapHandler implements 
ParameterHandler&lt;Map&gt; {
     public Map fromString(String s) {...}
 }
 
@@ -375,15 +375,15 @@ public class Service {
 }
 </pre>
 </div></div><p>Note that ParameterHandlers can not be used to deal with 
parameters representing a message body, "byte[] byte" in this example. 
MessageBodyReaders have to deal with this task. That said, a given 
MessageBodyReader implementation can also implement 
ParameterHandler.</p><p>ParameterHandlers can be registered as providers either 
from Spring or programmatically.<br clear="none"> Note that by default the 
handlers are checked last after all the other options recommended by the JAX-RS 
specification have been tried.<br clear="none"> Starting from CXF 2.5.3 the 
handlers will always be checked first for java.util.Date and java.util.Locale 
parameters. Additionally, a "check.parameter.handlers.first" contextual 
property can be used to get the handlers checked first when the parameters of 
other types are processed.</p><p>All the parameters are automatically decoded. 
This can be disabled by using @Encoded annotation.<br clear="none"> Parameters 
can have a default value set using a D
 efaultValue annotation :</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">    public Response updateCustomer(@DefaultValue("123") 
@QueryParam("id") Long id, @PathParam("name") String name) { ... }
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">    public Response updateCustomer(@DefaultValue("123") 
@QueryParam("id") Long id, @PathParam("name") String name) { ... }
 
 </pre>
 </div></div><p>JAX-RS mandates that only a single method parameter which is 
not annotated with JAXRS annotations applicable to method parameters is allowed 
in a resource method. For example :</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">public Response do(@PathParam("id") String id, String 
body) {
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">public Response do(@PathParam("id") String id, String 
body) {
 }
 </pre>
 </div></div><p>Parameters like 'String body' are expected to represent the 
request body/input stream. It's the job of JAX-RS MessageBodyReaders to 
deserialize the request body into an object of the expected type.</p><p>It's 
also possible to inject all types of parameters into fields or through 
dedicated setters. For example, the first code fragment in this section can be 
rewritten like this:</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customer/{id}")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customer/{id}")
 public class CustomerService {
 
     @PathParam("id")
@@ -404,7 +404,7 @@ public class CustomerService {
 }
 </pre>
 </div></div><h2 id="JAX-RSBasics-Parameterbeans">Parameter 
beans</h2><p>There's a CXF extension which makes it possible to inject a 
sequence of @PathParam, @QueryParam, @FormParam or @MatrixParam parameters into 
a bean. For example:</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customer/{id}")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customer/{id}")
 public class CustomerService {
 
     
@@ -443,7 +443,7 @@ public class OrderBean {
 
 </pre>
 </div></div><p>Note that there's a single @PathParam with an empty value in 
updateCustomer() - this is an extension bit. The value for a template variable 
'id' is injected into Customer.setId(Long id), while the value for 'name' is 
injected into Customer.setName(String s). The setter methods should have a 
single parameter, the conversion from the actual value to the parameter 
instance follows the same procedure as outlined above.</p><p>Similarly, in 
getCustomerOrder(), OrderBean can be injected with corresponding values from a 
query string like ?id=1&amp;weight=2 or from matrix parameters set as part of 
one of the path segments : /customer/1/order;id=1;weight=2. Likewise, in 
addCustomerOrder(), FormParam("") can capture all the values submitted from an 
HTML form and inject them into OrderBean.</p><p>Nested beans are also 
supported, which among other things, makes it possible to formulate advanced 
search queries. For example, given the following bean definitions:</p><div 
class="code 
 panel pdl" style="border-width: 1px;"><div class="codeContent panelContent 
pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">class Name {
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">class Name {
     String first;
     String last;
 }
@@ -469,14 +469,14 @@ class MyService
 } 
 </pre>
 </div></div><p>a query like</p><p>&gt; 
/getPerson?sex=M&amp;legalName.first=John&amp;legalName.last=Doe&amp;homeAddr.city=Reno&amp;homeAddr.state=NV</p><p>will
 result in a Person bean being properly initialized and all the search criteria 
being captured and easily accessible. Note more enhancements are being planned 
in this area.</p><h1 id="JAX-RSBasics-Resourcelifecycles">Resource 
lifecycles</h1><p>The scopes which are supported by default are Singleton and 
Prototype(per-request).<br clear="none"> Note that JAXRS MessageBodyWriter and 
MessageBodyReader providers are always singletons.</p><p>Classes with prototype 
scopes can get JAXRS contexts or parameters injected at construction 
time:</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/")
 public class PerRequestResourceClass {
 
    public PerRequestResourceClass(@Context HttpHeaders headers, 
@QueryParam("id") Long id) {}
 }
 </pre>
 </div></div><p>Classes with singleton scopes can only have contexts injected 
at the construction time and it is only a CXFNonSpringJaxrsServlet which can do 
it. In most cases you can have contexts injected as bean properties right after 
construction time.</p><p>See the "Lifecycle management" section for more 
details.</p><h1 id="JAX-RSBasics-Overviewoftheselectionalgorithm.">Overview of 
the selection algorithm.</h1><p>The JAX-RS Selection algorithm is used to 
select root resource classes, resource methods and subresource locators.</p><h2 
id="JAX-RSBasics-Selectingbetweenmultipleresourceclasses">Selecting between 
multiple resource classes</h2><p>When multiple resource classes match a given 
URI request, the following algorithm is used :<br clear="none"> 1. Prefer the 
resource class which has more literal characters in its @Path 
annotation.</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/bar/{id}")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/bar/{id}")
 public class Test1 {}
 @Path("/bar/{id}/baz")
 public class Test2 {}
@@ -486,19 +486,19 @@ public class Test3 {}
 public class Test4 {}
 </pre>
 </div></div><p>Both classes match /bar/1/baz requests but Test2 will be 
selected as it has 9 Path literal characters compared to 5 in Test1. Similarly, 
Test4 wins against Test3 when a /foo/ request arrives.</p><p>2. Prefer the 
resource class which has more capturing groups in its @Path annotation.</p><div 
class="code panel pdl" style="border-width: 1px;"><div class="codeContent 
panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/bar/{id}/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/bar/{id}/")
 public class Test1 {}
 @Path("/bar/{id}/{id2}")
 public class Test2 {}
 </pre>
 </div></div><p>Both classes match /bar/1/2 requests and both have the same 
number of literal characters but Test2 will be selected as it has 2 Path 
capturing groups (id and id1) as opposed to 1 in Test1.</p><p>3. Prefer the 
resource class which has more capturing groups with arbitrary regular 
expressions in its @Path annotation.</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/bar/{id:.+}/baz/{id2}")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/bar/{id:.+}/baz/{id2}")
 public class Test1 {}
 @Path("/bar/{id}/bar/{id2}")
 public class Test2 {}
 </pre>
 </div></div><p>Both classes match /bar/1/baz/2 requests and both have the same 
number of literal characters and capturing groups but Test1 will be selected as 
it has 1 Path capturing groups with the arbitrary regular expression (id) as 
opposed to 0 in Test2.</p><h2 
id="JAX-RSBasics-Selectingbetweenmultipleresourcemethods">Selecting between 
multiple resource methods</h2><p>Once the resource class has been selected, the 
next step is to choose a resource method. If multiple methods can be matched 
then the same rules which are used for selecting resource classes are applied. 
Additionally, one more rule is used.</p><p>4. Prefer a resource method to a 
subresource locator method</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/")
 public class Test1 {
 
  @Path("/bar")
@@ -518,7 +518,7 @@ public class Order {
 }
 </pre>
 </div></div><p>Both getOrderFromSubresource() and getOrder() methods can be 
used to serve a /bar request. However, getOrder() wins.</p><h2 
id="JAX-RSBasics-Resourcemethodsandmediatypes">Resource methods and media 
types</h2><p>Consider this resource class with 2 resource methods :</p><div 
class="code panel pdl" style="border-width: 1px;"><div class="codeContent 
panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/")
 public class Test1 {
 
  @Path("/bar")
@@ -536,7 +536,7 @@ public class Test1 {
 }
 </pre>
 </div></div><p>Both methods match /bar requests. If in a given request both 
Content-Type and Accept are set to application/xml then getOrderXML will be 
selected. If both Content-Type and Accept are set to application/json then 
getOrderJSON will be chosen instead.</p><p>For this specific example, in both 
cases either JAXB or JSON message body readers and writers will be selected to 
deserialize the input stream into OrderDetails and serialize Order into the 
output stream. Message body providers can have @Produces and @Consumes set too, 
and they have to match those on a chosen resource method.</p><p>The above code 
can be replaced with this one :</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/")
 public class Test1 {
 
  @Path("/bar")
@@ -548,7 +548,7 @@ public class Test1 {
 }
 </pre>
 </div></div><h2 
id="JAX-RSBasics-Customselectionbetweenmultipleresourcesoroperations">Custom 
selection between multiple resources or operations</h2><p>The JAX-RS selection 
algorithm has been designed with a lot of attention being paid to various 
possible cases, as far as the selection between multiple matching resource 
classes or methods is concerned.</p><p>However, in some cases, users have 
reported the algorithm being somewhat restrictive in the way multiple resource 
classes are selected. For example, by default, after a given resource class has 
been matched and if this class has no matching resource method, then the 
algorithm stops executing, without attempting to check the remaining matching 
resource classes.</p><p>Starting from CXF 2.2.5 it is possible to register a 
custom <a shape="rect" class="external-link" 
href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ResourceComparator.java";>ResourceComparator</a>
 implementation us
 ing a jaxrs:server/jaxrs:resourceComparator element, example:</p><div 
class="code panel pdl" style="border-width: 1px;"><div class="codeContent 
panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">&lt;!-- JAX-RS endpoint declaration fragment --&gt;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">&lt;!-- JAX-RS endpoint declaration fragment --&gt;
 &lt;jaxrs:server address="/"&gt;
 &lt;!-- Usual elements, like serviceBeans or providers, etc --&gt;
 
@@ -560,7 +560,7 @@ public class Test1 {
 
 </pre>
 </div></div><p>Custom implementations can check the names of the resource 
classes or methods being compared and given the current request URI they can 
make sure that the required class or method is chosen by returning either -1 or 
1, as needed. If 0 is returned then the runtime will proceed with executing the 
default selection algorithm. At the moment the easiest way to get to the 
details such as the current request URI is to create an instance of the CXF 
JAXRS UriInfoImpl using a constructor accepting a Message.</p><p>Note that by 
the time a custom ResourceComparator is called the provided resource classes or 
methods have already been successfully matched by the runtime.</p><p>For 
example, the optional HTTP request and URI parameters (query, matrix, headers, 
cookies) and form parameters do not affect the selection algorithm.<br 
clear="none"> A custom ResourceComparator can be used when this limitation is 
considered to be problematic. For example, the following shows one such implem
 entation:</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">import java.io.UnsupportedEncodingException;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.util.HashSet;
 import java.util.List;
@@ -665,7 +665,7 @@ public class QueryResourceInfoComperator
 } 
 </pre>
 </div></div><p>Now consider this code:</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/paramTest")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/paramTest")
 public class MySimpleService {
 
       @GET
@@ -683,7 +683,7 @@ public class MySimpleService {
 } 
 </pre>
 </div></div><p>Using the custom comparator will lead to getFoo() method 
accepting a single query parameter selected when a request URI has only one 
query parameter, and getFoo() method accepting multiple query parameters 
selected when a request URI has at least two query parameters. Further 
customizations may also be possible.</p><h1 
id="JAX-RSBasics-Contextannotations">Context annotations</h1><p>A number of 
context types can be injected as parameters, in fields or through dedicated 
methods.<br clear="none"> UriInfo, SecurityContext, HttpHeaders, Providers, 
Request, ContextResolver, Servlet types (HttpServletRequest, 
HttpServletResponse, ServletContext, ServletConfig) can be injected.</p><p>A 
CXF-specific composite context interface, <a shape="rect" class="external-link" 
href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/MessageContext.java";>MessageContext</a>
 is also supported which makes it easier to deal with all the supported
  JAX-RS contexts (and indeed with future ones) and also lets us check the 
current message's properties.</p><p>Example:</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customer")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customer")
 public class CustomerService {
     
     @Context 
@@ -705,7 +705,7 @@ public class CustomerService {
 
 </pre>
 </div></div><p>Note that all types of supported JAX-RS providers such as 
MessageBodyWriter, MessageBodyReader, ExceptionMapper and ContextResolver, as 
well as the list of body providers which can be provided by Providers can have 
contexts injected too. The only exception is that no parameter level injection 
is supported for providers due to methods of JAXRS providers being 
fixed.</p><p>Note that Providers and ContextResolver are likely to be of 
interest to message body providers rather than to the actual application code. 
You can also inject all the context types into @Resource annotated 
fields.</p><h2 id="JAX-RSBasics-CustomContexts">Custom 
Contexts</h2><p>Registering a custom <a shape="rect" class="external-link" 
href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ContextProvider.java";>ContextProvider</a>
 implementation such as <a shape="rect" class="external-link" 
href="http://svn.apache.org/repos/asf/cxf/trunk/rt/rs/extensions
 
/search/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchContextProvider.java">SearchContextProvider</a>
 lets attach Context annotations to arbitrary classes which can be helpful when 
some of the information representing the current request needs to be optimized 
or specialized, example:</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">package resources;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">package resources;
 import org.apache.cxf.jaxrs.ext.search.SearchContext;
 @Path("/")
 public class RootResource {
@@ -715,7 +715,7 @@ public class RootResource {
 }
 </pre>
 </div></div><p>and</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">&lt;jaxrs:server&gt;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">&lt;jaxrs:server&gt;
   &lt;serviceBeans&gt;
     &lt;bean class="resources.RootResource"/&gt;
   &lt;/serviceBeans&gt;
@@ -725,7 +725,7 @@ public class RootResource {
 &lt;/jaxrs:server&gt;
 </pre>
 </div></div><p>Custom Context implementations may get all the information 
about the HTTP request from the current CXF message.</p><h1 
id="JAX-RSBasics-URIcalculationusingUriInfoandUriBuilder">URI calculation using 
UriInfo and UriBuilder</h1><p>Mapping of a particular URI to a service that 
returns some resource is straightforward using the @Path annotation. However 
RESTful services are often connected: one service returns data that is used as 
the key in another service. Listing entities and accessing a particular entity 
is a typical example:</p><div class="code panel pdl" style="border-width: 
1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customers")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customers")
 public class CustomerService {
 
     @GET
@@ -742,7 +742,7 @@ public class CustomerService {
 }
 </pre>
 </div></div><p>For this service we can assume that the returned list of 
customers exposes only basic attributes and more details is returned using the 
second method which uses the customer id as the key. Something like 
this:</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">GET http://foobar.com/api/customers
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">GET http://foobar.com/api/customers
 
 &lt;customers&gt;
     &lt;customer id="1005"&gt;John Doe&lt;/customer&gt;
@@ -759,7 +759,7 @@ GET http://foobar.com/api/customers/1005
 &lt;/customer&gt;
 </pre>
 </div></div><p>How does a client of this service know how to get from list of 
customers to given customer? A trivial approach would be to expect the client 
to compute the proper URI. But wouldn't it be better to have the services 
provide full URIs in the response that can be used directly? This way the 
client would be more decoupled from the service itself (which may change URI 
format over time). A client could be provided the following on response, for 
example:</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">GET http://foobar.com/api/customers
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">GET http://foobar.com/api/customers
 
 &lt;customers-list&gt;
     &lt;customer id="1005" url="http://foobar.com/api/customers/1005"&gt;John 
Doe&lt;/customer&gt;
@@ -768,7 +768,7 @@ GET http://foobar.com/api/customers/1005
 &lt;/customers-list&gt;
 </pre>
 </div></div><p>The problem for the service is how to determine these URIs when 
the paths come from @Path annotations. It gets more complicated as we consider 
paths with templates (variables) on multiple levels or sub-resources 
introducing dynamic routing to different URIs.</p><p>The core part of the 
solution is to inject the <a shape="rect" class="external-link" 
href="https://jsr311.dev.java.net/nonav/javadoc/javax/ws/rs/core/UriInfo.html"; 
rel="nofollow">UriInfo</a> object into method "getCustomers". This helper 
object allows for extracting useful information about the current URI context, 
but more importantly allows for getting the <a shape="rect" 
class="external-link" 
href="https://jsr311.dev.java.net/nonav/javadoc/javax/ws/rs/core/UriBuilder.html";
 rel="nofollow">UriBuilder</a> object. UriBuilder has multiple appender methods 
for building the URI for each object; in our case to the stem URI we can append 
path in multiple ways, providing it as a string (which we actually want to av
 oid here) or a resource (class or method) to extract the @Path value. Finally 
UriBuilder must have values bound to its template variables to render the 
actual URI. This case in action looks like this:</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customers")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customers")
 public class CustomerService {
 
     @GET
@@ -793,7 +793,7 @@ public class CustomerService {
 }
 </pre>
 </div></div><h1 id="JAX-RSBasics-Annotationinheritance">Annotation 
inheritance</h1><p>Most of the JAX-RS annotations can be inherited from either 
an interface or a superclass. For example:</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">public interface CustomerService {
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">public interface CustomerService {
 
     @PUT
     @Path("/customers/{id}")
@@ -820,7 +820,7 @@ public class Customers implements Custom
 }
 </pre>
 </div></div><p>Similarly, annotations can be inherited from super-classes. In 
CXF, the resource class will inherit the class-level annotations from both its 
implemented interfaces and any class it extends.</p><h1 
id="JAX-RSBasics-Sub-resourcelocators.">Sub-resource locators.</h1><p>A method 
of a resource class that is annotated with @Path becomes a sub-resource locator 
when no annotation with an HttpMethod designator like @GET is present. 
Sub-resource locators are used to further resolve the object that will handle 
the request. They can delegate to other sub-resource locators, including 
themselves.</p><p>In the example below, getOrder method is a sub-resource 
locator:</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customerservice/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customerservice/")
 public class CustomerService {
 
     @Path("/orders/{orderId}/")
@@ -861,7 +861,7 @@ public class Order {
 }
 </pre>
 </div></div><p>A HTTP GET request to <a shape="rect" class="external-link" 
href="http://localhost:9000/customerservice/orders/223/products/323"; 
rel="nofollow">http://localhost:9000/customerservice/orders/223/products/323</a>
 is dispatched to getOrder method first. If the Order resource whose id is 223 
is found, the Order 223 will be used to further resolve Product resource. 
Eventually, a Product 323 that belongs to Order 223 will be returned. 
Similarly, the request to <a shape="rect" class="external-link" 
href="http://localhost:9000/customerservice/orders/223/products/323/items"; 
rel="nofollow">http://localhost:9000/customerservice/orders/223/products/323/items</a>
 will be delivered to the getItems(productId) method.</p><p>Note that a 
subresource class like Order often has no root @Path annotations which means 
that they're delegated to dynamically at runtime, in other words, they can not 
be invoked upon before one of the root resource classes is invoked first. A 
root resource class (
 which has a root @\Path annotation) can become a subresource too if one of its 
subresource locator methods delegates to it, similar to 
Order.getItems(productId) above.</p><p>Note that a given subresource can be 
represented as an interface or some base class resolved to an actual class at 
runtime. In this case any resource methods which have to be invoked on an 
actual subresource instance are discovered dynamically at runtime:</p><div 
class="code panel pdl" style="border-width: 1px;"><div class="codeContent 
panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Path("/customerservice/")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Path("/customerservice/")
 public class CustomerService {
 
     @Path("/orders/{orderId}/")
@@ -895,14 +895,14 @@ public class OrderImpl2 implements Order
 
 </pre>
 </div></div><h2 id="JAX-RSBasics-Staticresolutionofsubresources">Static 
resolution of subresources</h2><p>By default, subresources are resolved 
dynamically at runtime. This is a slower procedure, partly due to the fact that 
a concrete subresource implementation may introduce some JAXRS annotations in 
addition to those which might be available at the interface typed by a 
subresource locator method and different to those available on another 
subresource instance implementing the same interface.</p><p>If you know that 
all the JAXRS annotations are available on a given subresource type (or one of 
its superclasses or interfaces) returned by a subresource locator method then 
you may want to disable the dynamic resolution :</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">&lt;beans&gt;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">&lt;beans&gt;
 &lt;jaxrs:server staticSubresourceResolution="true"&gt;
 &lt;!-- more configuration --&gt;
 &lt;/jaxrs:server&gt;
 &lt;/beans&gt;
 </pre>
 </div></div><p>Note - starting from CXF 2.7.2 the injection of JAX-RS contexts 
and parameters will also be supported if this property has been enabled.</p><h1 
id="JAX-RSBasics-MessageBodyProviders">Message Body Providers</h1><p>JAX-RS 
relies on MessageBodyReader and MessageBodyWriter implementations to serialize 
and de-serialize Java types. JAX-RS requires that certain types has to be 
supported out of the box. <br clear="none"> By default, CXF supports String, 
byte[], InputStream, Reader, File, JAXP Source, JAX-RS StreamingOutput, 
JAXB-annotated types with application/xml, text/xml and application/json 
formats as well as JAXBElement (see below). JAX-RS MultivaluedMap is also 
supported for form contents.</p><p>See also the "Support for data bindings" 
section below.</p><h2 id="JAX-RSBasics-CustomMessageBodyProviders">Custom 
Message Body Providers</h2><p>It's likely that a given application may need to 
deal with types that are not supported by default. Alternatively, developers 
may wan
 t to provide a more efficient implementation for handling default types such 
as InputStream.</p><p>Here's an example of a custom MessageBodyReader for 
InputStream:</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Consumes("application/octet-stream")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Consumes("application/octet-stream")
 @Provider
 public class InputStreamProvider implements 
MessageBodyReader&lt;InputStream&gt; {
 
@@ -925,7 +925,7 @@ public class InputStreamProvider impleme
 
 </pre>
 </div></div><p>and here's an example of a custom MessageBodyWriter for Long 
objects:</p><div class="code panel pdl" style="border-width: 1px;"><div 
class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">@Produces("text/plain")
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">@Produces("text/plain")
 @Provider
 public class LongProvider implements MessageBodyWriter&lt;Long&gt; {
 
@@ -946,7 +946,7 @@ public class LongProvider implements Mes
 
 </pre>
 </div></div><p>CXF ships some custom providers too, for dealing with Atom 
(based on Apache Abdera) and XMLObjects. CXF also supports primitive types and 
their Number friends when text/plain media type is used, either on input or 
output.</p><h2 id="JAX-RSBasics-Registeringcustomproviders">Registering custom 
providers</h2><p>Putting @Provider annotation on the provider class is 
something that should lead to your provider being registered with the runtime. 
CXF does not support this feature yet.</p><p>One can easily register a provider 
either from Spring configuration or programmatically:</p><div class="code panel 
pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">&lt;beans&gt;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">&lt;beans&gt;
 &lt;jaxrs:server id="customerService" address="/"&gt;
     &lt;jaxrs:serviceBeans&gt;
       &lt;bean class="org.CustomerService" /&gt;
@@ -962,7 +962,7 @@ public class LongProvider implements Mes
 &lt;/beans&gt;
 </pre>
 </div></div><p>Note that instead of the older &lt;jaxrs:entityProviders&gt; 
it's now &lt;jaxrs:providers&gt;. JAX-RS supports different types of providers 
and having a single &lt;jaxrs:providers&gt; container is in line with the way 
other JAX-RS implementations discover providers by checking for @Provider 
annotations only.</p><p>See below for a more complete beans.xml 
definition.</p><p>While having @Provider-annotated providers automatically 
registered is a handy feature indeed, sometimes it might actually be 
problematic. For example, in a large project user providers from different 
libraries might clash.</p><p>When using the custom configuration (as shown 
above) provider instances of different types (handling the same format of 
request/response bodies) or differently configured instances of the same type 
can be registered with a different jaxrs:server instance. Yet another 
requirement might be to have only a given jaxrs:server endpoint among multiple 
available ones to handle reques
 ts with a given media type:</p><div class="code panel pdl" 
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<pre class="brush: bash; gutter: false; theme: Confluence" 
style="font-size:12px;">&lt;beans&gt;
+<pre class="brush: java; gutter: false; theme: Default" 
style="font-size:12px;">&lt;beans&gt;
 &lt;jaxrs:server id="customerService1" address="/1"&gt;
    &lt;bean id="serviceBean" class="org.CustomerService" /&gt; 
 


Reply via email to