cxf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache CXF Documentation > JAX-RS
Date Thu, 15 Oct 2009 09:41:00 GMT
<html>
<head>
    <base href="http://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/1519/1/1/_/styles/combined.css?spaceKey=CXF20DOC&amp;forWysiwyg=true" type="text/css">
    </head>
<body style="background-color: white" bgcolor="white">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
     <h2><a href="http://cwiki.apache.org/confluence/display/CXF20DOC/JAX-RS">JAX-RS</a></h2>
     <h4>Page <b>edited</b> by             <a href="http://cwiki.apache.org/confluence/display/~sergey_beryozkin">Sergey Beryozkin</a>
    </h4>
     
          <br/>
     <div class="notificationGreySide">
         <span style="font-size:2em;font-weight:bold"> JAX-RS (JSR-311) </span>

<div>
<ul>
    <li><a href='#JAX-RS-Introduction'>Introduction</a></li>
    <li><a href='#JAX-RS-Migratingfrom0.8to1.0'>Migrating from 0.8 to 1.0</a></li>
    <li><a href='#JAX-RS-Mavendependencies'>Maven dependencies</a></li>
    <li><a href='#JAX-RS-SettinguptheclasspathinEclipseorAnt'>Setting up the classpath in Eclipse or Ant</a></li>
    <li><a href='#JAX-RS-CXFJAXRSbundle'>CXF JAX-RS bundle</a></li>
    <li><a href='#JAX-RS-Understandingthebasics'>Understanding the basics</a></li>
<ul>
    <li><a href='#JAX-RS-Resourceclass'>Resource class</a></li>
    <li><a href='#JAX-RS-@Path'>@Path</a></li>
    <li><a href='#JAX-RS-HTTPMethod'>HTTP Method</a></li>
    <li><a href='#JAX-RS-Returntypes'>Return types</a></li>
<ul>
    <li><a href='#JAX-RS-Exceptionhandling'>Exception handling</a></li>
</ul>
    <li><a href='#JAX-RS-DealingwithParameters'>Dealing with Parameters</a></li>
<ul>
    <li><a href='#JAX-RS-Parameterbeans'>Parameter beans</a></li>
</ul>
    <li><a href='#JAX-RS-Resourcelifecycles'>Resource lifecycles</a></li>
    <li><a href='#JAX-RS-Overviewoftheselectionalgorithm.'>Overview of the selection algorithm.</a></li>
<ul>
    <li><a href='#JAX-RS-Selectingbetweenmultipleresourceclasses'>Selecting between multiple resource classes</a></li>
    <li><a href='#JAX-RS-Selectingbetweenmultipleresourcemethods'>Selecting between multiple resource methods</a></li>
    <li><a href='#JAX-RS-Resourcemethodsandmediatypes'>Resource methods and media types</a></li>
</ul>
    <li><a href='#JAX-RS-Contextannotations'>Context annotations</a></li>
<ul>
    <li><a href='#JAX-RS-URIscalculationusingUriInfoandUriBuilder'>URIs calculation using UriInfo and UriBuilder</a></li>
</ul>
    <li><a href='#JAX-RS-Annotationinheritance'>Annotation inheritance</a></li>
    <li><a href='#JAX-RS-Subresourcelocators.'>Sub-resource locators.</a></li>
<ul>
    <li><a href='#JAX-RS-Staticresolutionofsubresources'>Static resolution of subresources</a></li>
</ul>
    <li><a href='#JAX-RS-MessageBodyProviders'>Message Body Providers</a></li>
<ul>
    <li><a href='#JAX-RS-CustomMessageBodyProviders'>Custom Message Body Providers</a></li>
    <li><a href='#JAX-RS-Registeringcustomproviders'>Registering custom providers</a></li>
</ul>
    <li><a href='#JAX-RS-Customizingmediatypesformessagebodyproviders'>Customizing media types for message body providers</a></li>
</ul>
    <li><a href='#JAX-RS-Supportfordatabindings'>Support for data bindings</a></li>
<ul>
    <li><a href='#JAX-RS-JAXBsupport'>JAXB support</a></li>
<ul>
    <li><a href='#JAX-RS-ConfiguringJAXBprovider'>Configuring JAXB provider</a></li>
</ul>
    <li><a href='#JAX-RS-JSONsupport'>JSON support</a></li>
<ul>
    <li><a href='#JAX-RS-ConfiguringJSONprovider'>Configuring JSON provider</a></li>
    <li><a href='#JAX-RS-DealingwithJSONarrayserializationissues'>Dealing with JSON array serialization issues</a></li>
    <li><a href='#JAX-RS-WrappingandUnwrappingJSONsequences'>Wrapping and Unwrapping JSON sequences</a></li>
</ul>
    <li><a href='#JAX-RS-AutomaticJAXBElementconversionduringserialization'>Automatic JAXBElement conversion during serialization</a></li>
    <li><a href='#JAX-RS-HandlingJAXBbeanswithoutXmlRootElementannotations'>Handling JAXB beans without XmlRootElement annotations</a></li>
    <li><a href='#JAX-RS-Handlingexplicitcollections'>Handling explicit collections</a></li>
</ul>
    <li><a href='#JAX-RS-Debugging'>Debugging</a></li>
    <li><a href='#JAX-RS-Logging'>Logging</a></li>
    <li><a href='#JAX-RS-Filters'>Filters</a></li>
<ul>
    <li><a href='#JAX-RS-DifferencebetweenJAXRSfiltersandCXFinterceptors'>Difference between JAXRS filters and CXF interceptors</a></li>
    <li><a href='#JAX-RS-Overridingrequestandresponseproperties'>Overriding request and response properties</a></li>
<ul>
    <li><a href='#JAX-RS-OverridingHTTPmethod'>Overriding HTTP method</a></li>
    <li><a href='#JAX-RS-OverridingrequestURI'>Overriding request URI</a></li>
    <li><a href='#JAX-RS-Overridingresponsestatuscodeandheaders'>Overriding response status code and headers</a></li>
</ul>
    <li><a href='#JAX-RS-IgnoringJAXRSMessageBodyWriters'>Ignoring JAXRS MessageBodyWriters</a></li>
</ul>
    <li><a href='#JAX-RS-Custominvokers'>Custom invokers</a></li>
    <li><a href='#JAX-RS-AdvancedHTTP'>Advanced HTTP</a></li>
    <li><a href='#JAX-RS-SupportforContinuations'>Support for Continuations</a></li>
    <li><a href='#JAX-RS-SecureJAXRSservices'>Secure JAX-RS services</a></li>
<ul>
    <li><a href='#JAX-RS-CheckingHTTPsecurityheaders'>Checking HTTP security headers</a></li>
    <li><a href='#JAX-RS-SecurityManagerandIllegalAccessExceptions'>SecurityManager and IllegalAccessExceptions</a></li>
</ul>
    <li><a href='#JAX-RS-ClientAPI'>Client API</a></li>
<ul>
    <li><a href='#JAX-RS-ProxybasedAPI'>Proxy-based API</a></li>
<ul>
    <li><a href='#JAX-RS-Customizingproxies'>Customizing proxies</a></li>
    <li><a href='#JAX-RS-ConvertingproxiestoWebClientsandviceversa'>Converting proxies to Web Clients and vice versa</a></li>
    <li><a href='#JAX-RS-Handlingexceptions'>Handling exceptions</a></li>
    <li><a href='#JAX-RS-ConfiguringproxiesinSpring'>Configuring proxies in Spring</a></li>
    <li><a href='#JAX-RS-Injectingproxies'>Injecting proxies</a></li>
    <li><a href='#JAX-RS-Limitations'>Limitations</a></li>
</ul>
    <li><a href='#JAX-RS-HTTPcentricclients'>HTTP-centric clients</a></li>
<ul>
    <li><a href='#JAX-RS-Handlingexceptions'>Handling exceptions</a></li>
    <li><a href='#JAX-RS-ConfiguringHTTPclientsinSpring'>Configuring HTTP clients in Spring</a></li>
</ul>
    <li><a href='#JAX-RS-XMLcentricclients'>XML-centric clients</a></li>
    <li><a href='#JAX-RS-ConfiguringClientsatRuntime'>Configuring Clients at Runtime</a></li>
    <li><a href='#JAX-RS-ConfiguringHTTPConduitfromSpring'>Configuring HTTP Conduit from Spring</a></li>
</ul>
    <li><a href='#JAX-RS-XPathandXSLT'>XPath and XSLT</a></li>
<ul>
    <li><a href='#JAX-RS-XPathsupport'>XPath support</a></li>
    <li><a href='#JAX-RS-XSLTsupport'>XSLT support</a></li>
</ul>
    <li><a href='#JAX-RS-ModelViewControllersupport'>Model-View-Controller support</a></li>
    <li><a href='#JAX-RS-SupportforMultiparts'>Support for Multiparts</a></li>
<ul>
    <li><a href='#JAX-RS-Readingattachments'>Reading attachments</a></li>
    <li><a href='#JAX-RS-Writingattachments'>Writing attachments</a></li>
    <li><a href='#JAX-RS-Uploadingfiles'>Uploading files</a></li>
    <li><a href='#JAX-RS-Readinglargeattachments'>Reading large attachments</a></li>
</ul>
    <li><a href='#JAX-RS-ServicelistingsandWADLsupport'>Service listings and WADL support</a></li>
    <li><a href='#JAX-RS-ConfiguringJAXRSservices'>Configuring JAX-RS services</a></li>
<ul>
    <li><a href='#JAX-RS-ConfiguringJAXRSservicesprogrammaticallycancreateaJAXRSRESTfulservicebyusingJAXRSServerFactoryBean'>Configuring JAX-RS services programmatically can create a JAX-RS RESTful service by using JAXRSServerFactoryBean from the <em>cxf-rt-frontend-jaxrs</em> package:</a></li>
    <li><a href='#JAX-RS-ConfiguringJAXRSendpointsprogrammaticallywithoutSpring'>Configuring JAX-RS endpoints programmatically without Spring</a></li>
    <li><a href='#JAX-RS-ConfiguringJAXRSclientsprogrammaticallywithoutSpring'>Configuring JAX-RS clients programmatically without Spring</a></li>
    <li><a href='#JAX-RS-ConfiguringJAXRSservicesincontainerwithSpringconfigurationfile.'>Configuring JAX-RS services in container with Spring configuration file.</a></li>
<ul>
    <li><a href='#JAX-RS-web.xml'>web.xml</a></li>
<ul>
    <li><a href='#JAX-RS-UsingSpringContextLoaderListener'>Using Spring ContextLoaderListener</a></li>
    <li><a href='#JAX-RS-UsingCXFServletinitparameters'>Using CXFServlet init parameters</a></li>
</ul>
    <li><a href='#JAX-RS-beans.xml'>beans.xml</a></li>
</ul>
    <li><a href='#JAX-RS-ConfiguringJAXRSservicesincontainerwithoutSpring'>Configuring JAX-RS services in container without Spring</a></li>
<ul>
    <li><a href='#JAX-RS-AttachingJAXRSendpointstoanexistingJettyserver'>Attaching JAXRS endpoints to an existing Jetty server</a></li>
</ul>
    <li><a href='#JAX-RS-ConfiguringJAXRSservicesprogrammaticallywithSpringconfigurationfile.'>Configuring JAX-RS services programmatically with Spring configuration file.</a></li>
    <li><a href='#JAX-RS-Lifecyclemanagement'>Lifecycle management</a></li>
<ul>
    <li><a href='#JAX-RS-FromSpring'>From Spring</a></li>
    <li><a href='#JAX-RS-WithCXFNonSpringJaxrsServlet'>With CXFNonSpringJaxrsServlet</a></li>
    <li><a href='#JAX-RS-Programmatically'>Programmatically</a></li>
    <li><a href='#JAX-RS-PostConstructandPreDestroy'>PostConstruct and PreDestroy</a></li>
</ul>
    <li><a href='#JAX-RS-Locatingcustomresourcesinwebapplications'>Locating custom resources in web applications</a></li>
    <li><a href='#JAX-RS-Multipleendpointsandresourceclasses'>Multiple endpoints and resource classes</a></li>
    <li><a href='#JAX-RS-HowtherequestURIismatchedagainstagivenjaxrsendpoint'>How the request URI is matched against a given jaxrs endpoint</a></li>
    <li><a href='#JAX-RS-CombiningJAXWSandJAXRS'>Combining JAX-WS and JAX-RS</a></li>
<ul>
    <li><a href='#JAX-RS-Dealingwithcontexts'>Dealing with contexts</a></li>
</ul>
    <li><a href='#JAX-RS-JAXRSandSpringAOP'>JAX-RS and Spring AOP</a></li>
</ul>
    <li><a href='#JAX-RS-RESTfulserviceswithoutannotations'>RESTful services without annotations</a></li>
<ul>
    <li><a href='#JAX-RS-Configuration'>Configuration</a></li>
</ul>
    <li><a href='#JAX-RS-IntegrationwithDistributedOSGi'>Integration with Distributed OSGi</a></li>
    <li><a href='#JAX-RS-Howtocontribute'>How to contribute</a></li>
</ul></div>

<h1><a name="JAX-RS-Introduction"></a>Introduction</h1>

<p>CXF supports JAX-RS (JSR-311), Java API for RESTful Web Services. JAX-RS provides a more standard way to build RESTful services in Java. CXF 2.2.x supports the <a href="https://jsr311.dev.java.net/nonav/releases/1.0/index.html" rel="nofollow">final version of JSR-311 API </a> while CXF 2.1.x supports the <a href="https://jsr311.dev.java.net/nonav/releases/0.8/index.html" rel="nofollow">0.8 version of JSR-311 API </a>. </p>

<p>JAX-RS related demos are located under samples/jax_rs directory (CXF 2.2 and CXF 2.1 only).<br/>
This documentation will refer to <a href="https://jsr311.dev.java.net/nonav/releases/1.0/index.html" rel="nofollow">JSR-311 API 1.0 </a>.</p>

<h1><a name="JAX-RS-Migratingfrom0.8to1.0"></a>Migrating from 0.8 to 1.0</h1>

<p>The following major changes in 1.0 will most likely affect users migrating from 0.8</p>

<ul class="alternate" type="square">
	<li>@ProduceMime and @ConsumeMime have been replaced with @Produces and @Consumes respectively</li>
	<li>HttpHeaders has had some of its methods returning a string representation of Locale updated to return Locale instead</li>
</ul>


<p>As JAX-RS API 1.0 is currently supported in CXF 2.2.x, it's also worth noting of the following changes in dependencies :</p>

<ul class="alternate" type="square">
	<li>Spring version have changed from 2.0.8 in 2.1.x to 2.5.6</li>
	<li>jaxb-api version has changed to javax.xml.bind/jaxb-api/2.1</li>
	<li>jaxb-impl version has changed to com.sun.xml.bind/jaxb-impl/2.1.7</li>
</ul>


<p>Additionally, org.apache.cxf/cxf-rt-databinding-aegis/2.2.x compile-time dependency has been added</p>

<h1><a name="JAX-RS-Mavendependencies"></a>Maven dependencies</h1>

<p>To incorporate JAX-RS, you will need:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;dependency&gt;</span>
      <span class="code-tag">&lt;groupId&gt;</span>org.apache.cxf<span class="code-tag">&lt;/groupId&gt;</span>
      <span class="code-tag">&lt;artifactId&gt;</span>cxf-rt-frontend-jaxrs<span class="code-tag">&lt;/artifactId&gt;</span>
      <span class="code-tag">&lt;version&gt;</span>2.2.3<span class="code-tag">&lt;/version&gt;</span>
   <span class="code-tag">&lt;/dependency&gt;</span>
</pre>
</div></div>

<p>This will in turn pull in <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/pom.xml" rel="nofollow">the following 3rd-party dependencies</a> are used when building CXF JAX-RS implementation :</p>

<p>1. javax.ws.rs/jsr311-api/1.0</p>

<p>available from either </p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;repository&gt;</span>
    <span class="code-tag">&lt;id&gt;</span>java.net.2<span class="code-tag">&lt;/id&gt;</span>
    <span class="code-tag">&lt;name&gt;</span>Java Net 2 Repository<span class="code-tag">&lt;/name&gt;</span>
    <span class="code-tag">&lt;url&gt;</span>http://download.java.net/maven/2<span class="code-tag">&lt;/url&gt;</span>
<span class="code-tag">&lt;/repository&gt;</span>
</pre>
</div></div>


<p>or from a central maven repository</p>

<p>2. org.apache.abdera groupId : abdera-core, abdera-parser and abdera-extensions-json artifacts, version 0.4.0-incubating. It's a compile time dependency. Available from </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">

<span class="code-tag">&lt;repository&gt;</span>
    <span class="code-tag">&lt;id&gt;</span>apache.incubating<span class="code-tag">&lt;/id&gt;</span>
    <span class="code-tag">&lt;name&gt;</span>Apache Incubating Repository<span class="code-tag">&lt;/name&gt;</span>
    <span class="code-tag">&lt;url&gt;</span>http://people.apache.org/repo/m2-incubating-repository<span class="code-tag">&lt;/url&gt;</span>
<span class="code-tag">&lt;/repository&gt;</span>
</pre>
</div></div>

<p>3. org.springframework/spring-core/2.5.6</p>

<p>4. org.codehaus.jettison/jettison/1.1</p>

<p>5. org.apache.xmlbeans/xmlbeans/2.3.0 - compile time</p>

<p>Please check <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/pom.xml" rel="nofollow">the pom.xml</a> for the list of cxf components used by the JAX-RS implementation. Snapshots are available from <a href="http://repository.apache.org/snapshots/org/apache/cxf/apache-cxf/" rel="nofollow">http://repository.apache.org/snapshots/org/apache/cxf/apache-cxf/</a></p>

<h1><a name="JAX-RS-SettinguptheclasspathinEclipseorAnt"></a>Setting up the classpath in Eclipse or Ant</h1>

<p>If no Maven is used then the following jars need to be available at the runtime classpath :</p>

<ul class="alternate" type="square">
	<li>cxf-2.3.0-SNAPSHOT.jar</li>
	<li>jsr311-api-1.0.jar</li>
	<li>jaxb-impl-2.1.12.jar</li>
	<li>jaxb-api-2.1.jar</li>
</ul>


<ul class="alternate" type="square">
	<li>geronimo-annotation_1.0_spec-1.1.1.jar</li>
	<li>geronimo-activation_1.1_spec-1.0.2.jar</li>
	<li>geronimo-servlet_2.5_spec-1.2.jar</li>
	<li>commons-logging-1.1.1.jar</li>
</ul>


<ul class="alternate" type="square">
	<li>geronimo-stax_api_1.0_spec-1.0.1.jar</li>
	<li>woodstox-core-asl-4.0.3.jar</li>
	<li>stax2-api-3.0.1.jar</li>
</ul>


<ul class="alternate" type="square">
	<li>geronimo-jaxws_2.1_spec-1.0.jar</li>
	<li>wsdl4j-1.6.2.jar</li>
	<li>XmlSchema-1.4.5.jar</li>
	<li>neethi-2.0.4.jar</li>
</ul>


<p>For CXF 2.2.3 (2.2.4-SNAPSHOT) :</p>

<ul class="alternate" type="square">
	<li>add cxf-2.2.3.jar (or cxf-2.2.4-SNAPSHOT.jar) instead of cxf-2.3.0-SNAPSHOT.jar</li>
	<li>do not add stax2-api-3.0.1.jar</li>
	<li>add wstx-asl-3.2.8.jar instead of woodstox-core-asl-4.0.3.jar</li>
	<li>add saaj-api-1.3.jar</li>
</ul>


<p>If Spring configuration is used then add spring.jar from the Spring distribution or the spring jars available in the CXF distribution. When creating client proxies from concrete classes the cglib-nodep-2.1_3.jar needs to be added. You do not need to add JAXB libraries if you do not use JAXB. If you depend on Jetty then you will also need to add two jetty jars shipped with CXF.</p>

<p>We will work on reducing the set of required dependencies.<br/>
Please see the configuration sections below on how a spring dependency can be dropped.</p>

<h1><a name="JAX-RS-CXFJAXRSbundle"></a>CXF JAX-RS bundle</h1>

<p>A standalone <a href="http://svn.apache.org/repos/asf/cxf/trunk/distribution/bundle/jaxrs/pom.xml" rel="nofollow">JAX-RS bundle</a> is now available which may be of interest to users doing JAX-RS work only.</p>

<h1><a name="JAX-RS-Understandingthebasics"></a>Understanding the basics</h1>

<p>You are encouraged to read <a href="http://jcp.org/en/jsr/detail?id=311" rel="nofollow">JAX-RS spec </a> to find out information not covered by this documentation.</p>

<h2><a name="JAX-RS-Resourceclass"></a>Resource class</h2>

<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 at least with 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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">package</span> demo.jaxrs.server;

java.util.HashMap;
<span class="code-keyword">import</span> java.util.Map;

<span class="code-keyword">import</span> javax.ws.rs.GET;
<span class="code-keyword">import</span> javax.ws.rs.Path;
<span class="code-keyword">import</span> javax.ws.rs.PathParam;
<span class="code-keyword">import</span> javax.ws.rs.Produces;
<span class="code-keyword">import</span> javax.ws.rs.core.Response;

@Path(<span class="code-quote">"/customerservice/"</span>)
@Produces(<span class="code-quote">"application/xml"</span>)
<span class="code-keyword">public</span> class CustomerService {

    <span class="code-keyword">public</span> CustomerService() {
    }

    @GET
    <span class="code-keyword">public</span> Customers getCustomers() {
        ......
    }

    @GET
    @Path(<span class="code-quote">"/customers/{id}"</span>)
    @Produces(<span class="code-quote">"application/json"</span>)
    <span class="code-keyword">public</span> Customer getCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">String</span> id) {
        ......
    }

    @PUT
    @Path(<span class="code-quote">"/customers/{id}"</span>)
    @Consumes(<span class="code-quote">"application/xml"</span>)
    <span class="code-keyword">public</span> Response updateCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> id, Customer customer) {
        ......
    }

    @POST
    @Path(<span class="code-quote">"/customers"</span>)
    <span class="code-keyword">public</span> Response addCustomer(Customer customer) {
        ......
    }

    @DELETE
    @Path(<span class="code-quote">"/customers/{id}/"</span>)
    <span class="code-keyword">public</span> Response deleteCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">String</span> id) {
        ......
    }

    @Path(<span class="code-quote">"/orders/{orderId}/"</span>)
    <span class="code-keyword">public</span> Order getOrder(@PathParam(<span class="code-quote">"orderId"</span>) <span class="code-object">String</span> orderId) {
       ......
    }
}
</pre>
</div></div>

<p>Customer resource class can handle requests starting from /customerservice. When /customerservice request is 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>&#64;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 &#42;/&#42;, but it's recommended that some definite value is specified. The same applies to &#64;Consumes, only it's message body readers that are checked as the last resort.</p>

<p>For example, getCustomers() method inherits &#64;Produces annotation from its class, while getCustomer() method overrides it with its own value.  </p>

<h2><a name="JAX-RS-@Path"></a>@Path</h2>

<p>@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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customers/{id}"</span>)
<span class="code-keyword">public</span> class CustomerResource {

    @GET
    <span class="code-keyword">public</span> Customer getCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> id) {
        ......
    }

    @GET
    @Path(<span class="code-quote">"/order/{orderid}"</span>)
    <span class="code-keyword">public</span> Order getOrder(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> customerId, @PathParam(<span class="code-quote">"orderid"</span>) <span class="code-object">Long</span> orderId) {
        ......
    }

    @GET
    @Path(<span class="code-quote">"/order/{orderid}/{search:.*}"</span>)
    <span class="code-keyword">public</span> Item findItem(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> customerId, 
                         @PathParam(<span class="code-quote">"orderid"</span>) <span class="code-object">Long</span> orderId,
                         @PathParam(<span class="code-quote">"search"</span>) <span class="code-object">String</span> searchString,
                         @PathParam(<span class="code-quote">"search"</span>) List&lt;PathSegment&gt; searchList) {
        ......
    }
}

</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 &#64;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/>
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 href="http://jcp.org/en/jsr/detail?id=311" rel="nofollow">JAX-RS spec </a> section 2.3. </p>

<h2><a name="JAX-RS-HTTPMethod"></a>HTTP Method</h2>

<p>JAX-RS specification defines a number of annotations such as @GET, @PUT, @POST and @DELETE. Using an @HttpMethod designator, one can create a custom annotation such as @Update or @Patch. For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">package</span> org.apache.cxf.customverb;

<span class="code-keyword">import</span> java.lang.annotation.ElementType;
<span class="code-keyword">import</span> java.lang.annotation.Retention;
<span class="code-keyword">import</span> java.lang.annotation.RetentionPolicy;
<span class="code-keyword">import</span> java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod(<span class="code-quote">"PATCH"</span>)
<span class="code-keyword">public</span> @<span class="code-keyword">interface</span> PATCH { 
}
</pre>
</div></div>

<h2><a name="JAX-RS-Returntypes"></a>Return types</h2>

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

<h3><a name="JAX-RS-Exceptionhandling"></a>Exception handling</h3>

<p>One can either throw an unchecked WebApplicationException or return Response with a proper error code set.<br/>
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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customerservice/"</span>)
<span class="code-keyword">public</span> class CustomerService {

    
    @PUT
    @Path(<span class="code-quote">"/customers/{id}"</span>)
    <span class="code-keyword">public</span> Response updateCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> id, Customer customer) {
        <span class="code-keyword">return</span> Response.status(errorCode).build();
    }

    @POST
    @Path(<span class="code-quote">"/customers"</span>)
    <span class="code-keyword">public</span> Customer addCustomer(Customer customer) {
        <span class="code-keyword">throw</span> <span class="code-keyword">new</span> WebApplicationException(errorCode);
    }

}
</pre>
</div></div>

<p>Yet another option is to register an ExceptionMapper provider. Ex :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> BookExceptionMapper <span class="code-keyword">implements</span> ExceptionMapper&lt;BookException&gt; {
    <span class="code-keyword">public</span> Response toResponse(BookException ex) {
        <span class="code-comment">// convert to Response
</span>    }
}
</pre>
</div></div>

<p>This allows to throw a checked or runtime exception from an application code and map it to an HTTP response in a registered provider.</p>

<p>Note that when no mappers are found for custom exceptions, they are propogated (wrapped in ServletException) to the underlying container as required by the specification. If no custom servlet filter which can handle it JSONis available then most likely only 500 error status will be reported. This propogation can be disabled by registering a boolean jaxrs property 'org.apache.cxf.propogate.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 a xml error response by CXF XMLBinding which the JAXRS runtime is based upon. </p>

<h2><a name="JAX-RS-DealingwithParameters"></a>Dealing with Parameters</h2>

<p>PathParam annotation is used to map a given Path template variable to a method parameter.<br/>
For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

@Path(<span class="code-quote">"/customer/{id}"</span>)
<span class="code-keyword">public</span> class CustomerService {

    
    @PUT
    @Path(<span class="code-quote">"{name}"</span>)
    <span class="code-keyword">public</span> Response updateCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> id, @PathParam(<span class="code-quote">"name"</span>) <span class="code-object">String</span> name) {
        ...
    }
}
</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>&#64;QueryParam, &#64;HttpHeader, &#64;MatrixParam, &#64;FormParam and &#64;CookieParam annotations are also supported.<br/>
Parameters can be of type String or of any type that have constructors accepting a String parameter or static valueOf(String s) methods. <br/>
Additionally CXF JAXRS checks for static fromString(String s) method, so types with no valueOf(String) factory methods can also be dealt with :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

<span class="code-keyword">public</span> <span class="code-keyword">enum</span> Gender {
   MALE,
   FEMALE;

   <span class="code-keyword">public</span> <span class="code-keyword">static</span> fromString(<span class="code-object">String</span> s) {
       <span class="code-keyword">if</span> (<span class="code-quote">"1"</span>.equals(s)) {
           <span class="code-keyword">return</span> FEMALE;
       } <span class="code-keyword">else</span> <span class="code-keyword">if</span> (<span class="code-quote">"1"</span>.equals(s)) {
           <span class="code-keyword">return</span> MALE;
       }  
       <span class="code-keyword">return</span> valueOf(s); 
   }
}

@Path(<span class="code-quote">"/{g}"</span>)
<span class="code-keyword">public</span> class Service {

    
    @PUT
    @Path(<span class="code-quote">"{id}"</span>)
    <span class="code-keyword">public</span> Response update(@PathParam(<span class="code-quote">"g"</span>) Gender g, @PathParam(<span class="code-quote">"id"</span>) UUID u) {
        ...
    }
}
</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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class MapHandler <span class="code-keyword">implements</span> ParameterHandler&lt;Map&gt; {
    <span class="code-keyword">public</span> Map fromString(<span class="code-object">String</span> s) {...}
}

@Path(<span class="code-quote">"/map"</span>)
<span class="code-keyword">public</span> class Service {

    
    @PUT
    @Path(<span class="code-quote">"/{mapvalue:(.)+}"</span>)
    <span class="code-keyword">public</span> Response update(@PathParam(<span class="code-quote">"mapvalue"</span>) Map m, <span class="code-object">byte</span>[] bytes) {
        ...
    }
}
</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.</p>

<p>All the parameters are automatically decoded. This can be disabled by using @Encoded annotation.<br/>
Parameters can have a default value set using a DefaultValue annotation :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

    <span class="code-keyword">public</span> Response updateCustomer(@DefaultValue(<span class="code-quote">"123"</span>) @QueryParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> id, @PathParam(<span class="code-quote">"name"</span>) <span class="code-object">String</span> 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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> Response <span class="code-keyword">do</span>(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">String</span> id, <span class="code-object">String</span> 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>Starting from JAX-RS 0.8, it's also possible to inject all types of parameters into fields or through dedicated setters. For ex, the first code fragment in this section can be rewritten like this  :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customer/{id}"</span>)
<span class="code-keyword">public</span> class CustomerService {

    @PathParam(<span class="code-quote">"id"</span>)
    <span class="code-keyword">private</span> <span class="code-object">Long</span> id; 
    
    <span class="code-keyword">private</span> <span class="code-object">String</span> name;

    @PathParam(<span class="code-quote">"name"</span>)
    <span class="code-keyword">public</span> setName(<span class="code-object">String</span> name) {
        <span class="code-keyword">this</span>.name = name;
    } 

    @PUT
    @Path(<span class="code-quote">"{name}"</span>)
    <span class="code-keyword">public</span> Response updateCustomer() {
        <span class="code-comment">// use id and name
</span>    }
}
</pre>
</div></div>

<h3><a name="JAX-RS-Parameterbeans"></a>Parameter beans</h3>

<p>There's a CXF extension which makes it possible to inject a sequence of &#64;PathParam, &#64;QueryParam, &#64;FormParam or @MatrixParam parameters into a bean. For ex :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

@Path(<span class="code-quote">"/customer/{id}"</span>)
<span class="code-keyword">public</span> class CustomerService {

    
    @PUT
    @Path(<span class="code-quote">"{name}"</span>)
    <span class="code-keyword">public</span> Response updateCustomer(@PathParam("") Customer customer) {
        ...
    }

    @GET
    @Path(<span class="code-quote">"/order"</span>)
    <span class="code-keyword">public</span> Response getCustomerOrder(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">int</span> customerId, 
                                     @QueryParam("") OrderBean bean,
                                     @MatrixParam("") OrderBean bean) {
        ...
    }

    @POST
    <span class="code-keyword">public</span> Response addCustomerOrder(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">int</span> customerId,
                                     @FormParam("") OrderBean bean) {
        ...
    }
}

<span class="code-keyword">public</span> class Customer {
   <span class="code-keyword">public</span> void setId(<span class="code-object">Long</span> id) {...}
   <span class="code-keyword">public</span> void setName(<span class="code-object">String</span> s) {...}  
}

<span class="code-keyword">public</span> class OrderBean {
   <span class="code-keyword">public</span> void setId(<span class="code-object">Long</span> id) {...}
   <span class="code-keyword">public</span> void setWeight(<span class="code-object">int</span> w) {...}  
}



</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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
class Name {
    <span class="code-object">String</span> first;
    <span class="code-object">String</span> last;
}

class Address {
    <span class="code-object">String</span> city;
    <span class="code-object">String</span> state;
}

class Person {
    Name legalName;
    Address homeAddr;
    <span class="code-object">String</span> race;
    <span class="code-object">String</span> sex;
    Date birthDate;
}

class MyService
{
    @GET
    @Path(<span class="code-quote">"/getPerson"</span>)
    Person getPerson(@QueryParam("") Person person);
} 
</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>

<h2><a name="JAX-RS-Resourcelifecycles"></a>Resource lifecycles</h2>

<p>The scopes which are supported by default are Singleton and Prototype(per-request).<br/>
Note that JAXRS MessageBodyWriter and MessageBodyReader providers are always singletons. </p>

<p>Classes with prototype scopes can get JAXRS contexts or parameters injected at the construction time :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/"</span>)
<span class="code-keyword">public</span> class PerRequestResourceClass {

   <span class="code-keyword">public</span> PerRequestResourceClass(@Context HttpHeaders headers, @QueryParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> 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 straight after the construction time </p>

<p>See the "Lifecycle management" section for more details.</p>

<h2><a name="JAX-RS-Overviewoftheselectionalgorithm."></a>Overview of the selection algorithm.</h2>

<p>The JAX-RS Selection algorithm is used to select root resource classes, resource methods and subresource locators.</p>

<h3><a name="JAX-RS-Selectingbetweenmultipleresourceclasses"></a>Selecting between multiple resource classes</h3>

<p>When multiple resource classes match a given URI request, the following algorithm is used :<br/>
1. Prefer the resource class which has more literal characters in its &#64;Path annotation.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/bar/{id}"</span>)
<span class="code-keyword">public</span> class Test1 {}
@Path(<span class="code-quote">"/bar/{id}/baz"</span>)
<span class="code-keyword">public</span> class Test2 {}
@Path(<span class="code-quote">"/foo"</span>)
<span class="code-keyword">public</span> class Test3 {}
@Path(<span class="code-quote">"/foo/"</span>)
<span class="code-keyword">public</span> 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 &#64;Path annotation.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/bar/{id}/"</span>)
<span class="code-keyword">public</span> class Test1 {}
@Path(<span class="code-quote">"/bar/{id}/{id2}"</span>)
<span class="code-keyword">public</span> 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 &#64;Path annotation.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/bar/{id:.+}/baz/{id2}"</span>)
<span class="code-keyword">public</span> class Test1 {}
@Path(<span class="code-quote">"/bar/{id}/{bar}/{id2}"</span>)
<span class="code-keyword">public</span> 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>

<h3><a name="JAX-RS-Selectingbetweenmultipleresourcemethods"></a>Selecting between multiple resource methods</h3>

<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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/"</span>)
<span class="code-keyword">public</span> class Test1 {

 @Path(<span class="code-quote">"/bar"</span>)
 @GET
 <span class="code-keyword">public</span> Order getOrder() {...}

 @Path(<span class="code-quote">"/bar"</span>)
 <span class="code-keyword">public</span> Order getOrderFromSubresource() {...}
}

<span class="code-keyword">public</span> class Order {

 @Path(<span class="code-quote">"/"</span>)
 @GET
 <span class="code-keyword">public</span> Order getOrder() { <span class="code-keyword">return</span> <span class="code-keyword">this</span>; }

}
</pre>
</div></div>

<p>Both getOrderFromSubresource() and getOrder() methods can be used to serve a /bar request. However, getOrder() wins. </p>

<h3><a name="JAX-RS-Resourcemethodsandmediatypes"></a>Resource methods and media types</h3>

<p>Consider this resource class with 2 resource methods :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/"</span>)
<span class="code-keyword">public</span> class Test1 {

 @Path(<span class="code-quote">"/bar"</span>)
 @POST 
 @Consumes(<span class="code-quote">"application/json"</span>)
 @Produces(<span class="code-quote">"application/json"</span>)
 <span class="code-keyword">public</span> Order addOrderJSON(OrderDetails details) {...}

 @Path(<span class="code-quote">"/bar"</span>)
 @POST
 @Consumes(<span class="code-quote">"application/xml"</span>)
 @Produces(<span class="code-quote">"application/xml"</span>)
 <span class="code-keyword">public</span> Order getOrderXML(OrderDetails details) {...}
 
}
</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 <br/>
getOrderXML will be selected. If both Content-Type and Accept are set to application/json then <br/>
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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/"</span>)
<span class="code-keyword">public</span> class Test1 {

 @Path(<span class="code-quote">"/bar"</span>)
 @POST 
 @Consumes({<span class="code-quote">"application/json"</span>, <span class="code-quote">"application/xml"</span>})
 @Produces({<span class="code-quote">"application/json"</span>, <span class="code-quote">"application/xml"</span>})
 <span class="code-keyword">public</span> Order addOrder(OrderDetails details) {...}

}
</pre>
</div></div>


<p>TODO : more info</p>

<h2><a name="JAX-RS-Contextannotations"></a>Context annotations</h2>

<p>A number of context types can be injected as parameters, in fields or through dedicated methods.<br/>
UriInfo, SecurityContext, HttpHeaders, Providers, Request, ContextResolver, Servlet types (HttpServletRequest, HttpServletResponse, ServletContext, ServletConfig) can be injected.</p>

<p>A CXF-specific composite context interface, <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/MessageContext.java" rel="nofollow">MessageContext</a> is also supported which makes it easier to deal with all the supported JAX-RS contexts (and indeed with the future ones) and also lets check the current message's properties.</p>

<p>Example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customer"</span>)
<span class="code-keyword">public</span> class CustomerService {
    
    @Context 
    <span class="code-keyword">private</span> org.apache.cxf.jaxrs.ext.MessageContext mc; 
    @Context 
    <span class="code-keyword">private</span> ServletContext sc;
    <span class="code-keyword">private</span> UriInfo ui;
    
    @Context
    <span class="code-keyword">public</span> void setUriInfo(UriInfo ui) {
        <span class="code-keyword">this</span>.ui = ui;
    }

    @PUT
    <span class="code-keyword">public</span> Response updateCustomer(@Context HttpHeaders h, Customer c) {
        mc.getHttpHeaders();
    }
}

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

<h3><a name="JAX-RS-URIscalculationusingUriInfoandUriBuilder"></a>URIs calculation using UriInfo and UriBuilder</h3>

<p>Mapping of particular URI to service that returns some resource is straightforward using @Path annotation. However RESTful services are often connected: one service returns data that is used as key in another service. Listing entities and accessing particular entity is typical example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customers"</span>)
<span class="code-keyword">public</span> class CustomerService {

    @GET
    <span class="code-keyword">public</span> Customers getCustomers() {
        ......
    }

    @GET
    @Path(<span class="code-quote">"/{id}"</span>)
    <span class="code-keyword">public</span> Customer getCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">String</span> id) {
        ......
    }

}
</pre>
</div></div>

<p>For this service we can assume that returned list is brief of customers exposing only basic attributes and more details is returned referring to second URL, using customer id as key. Something like this:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
GET http:<span class="code-comment">//foobar.com/api/customers
</span>
&lt;customers&gt;
    &lt;customer id=<span class="code-quote">"1005"</span>&gt;John Doe&lt;/customer&gt;
    &lt;customer id=<span class="code-quote">"1006"</span>&gt;Jane Doe&lt;/customer&gt;
    ...
&lt;/customers&gt;
    
GET http:<span class="code-comment">//foobar.com/api/customers/1005
</span>
&lt;customer id=<span class="code-quote">"1005"</span>&gt;
    &lt;first-name&gt;John&lt;/first-name&gt;
    &lt;last-name&gt;Doe&lt;/last-name&gt;
    ...
&lt;/customer&gt;
</pre>
</div></div>

<p>How does client of this service know how to get from list of customers to given customer? Trivial approach is to expect client to compute proper URI. Wouldn't be better to ease flow through services attaching full URLs that can be used directly? This way client is more decoupled from service itself (that may evolve changing URLs). This way want get something like this:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
GET http:<span class="code-comment">//foobar.com/api/customers
</span>
&lt;customers-list&gt;
    &lt;customer id=<span class="code-quote">"1005"</span> url=<span class="code-quote">"http:<span class="code-comment">//foobar.com/api/customers/1005"</span>&gt;John Doe&lt;/customer&gt;
</span>    &lt;customer id=<span class="code-quote">"1006"</span> url=<span class="code-quote">"http:<span class="code-comment">//foobar.com/api/customers/1006"</span>&gt;Jane Doe&lt;/customer&gt;
</span>    ...
&lt;/customers-list&gt;
</pre>
</div></div>

<p>The problem is how to compute URIs when paths come from @Path annotations. It complicates when we consider paths with templates (variables) on multiple levels or sub-resources introducing dynamic routing to different URIs.</p>

<p>The core part of solution is to use injected <a href="https://jsr311.dev.java.net/nonav/javadoc/javax/ws/rs/core/UriInfo.html" rel="nofollow">UriInfo</a> object. Method "getCustomers" has to have UriInfo object injected. This helper object allows to extract some useful information about current URI context, but what's more important, allow to get <a href="https://jsr311.dev.java.net/nonav/javadoc/javax/ws/rs/core/UriBuilder.html" rel="nofollow">UriBuilder</a> object. UriBuilder has multiple appender methods that extends final URI it can build; in our case to current URI we can append path in multiple ways, providing it as string (which we actually want to avoid here) or providing resource (class or method) to extract @Path value. Finally UriBuilder that is composed of paths with templates (variables) must have variables bound to values to render URI. This case in action looks like this:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customers"</span>)
<span class="code-keyword">public</span> class CustomerService {

    @GET
    <span class="code-keyword">public</span> Customers getCustomers(@Context UriInfo ui) {
        ......
        <span class="code-comment">// builder starts with current URI and has appended path of getCustomer method
</span>        UriBuilder ub = ui.getAbsolutePathBuilder().path(<span class="code-keyword">this</span>.getClass(), <span class="code-quote">"getCustomer"</span>);
        <span class="code-keyword">for</span> (Customer customer: customers) {
            <span class="code-comment">// builder has {id} variable that must be filled in <span class="code-keyword">for</span> each customer
</span>            URI uri = ub.build(customer.getId());
            c.setUrl(uri);
        }
        <span class="code-keyword">return</span> customers;
    }

    @GET
    @Path(<span class="code-quote">"/{id}"</span>)
    <span class="code-keyword">public</span> Customer getCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">String</span> id) {
        ......
    }

}
</pre>
</div></div>


<h2><a name="JAX-RS-Annotationinheritance"></a>Annotation inheritance</h2>

<p>Most of the JAX-RS annotations can be inherited from either an interface or a superclass. For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

<span class="code-keyword">public</span> <span class="code-keyword">interface</span> CustomerService {

    @PUT
    @Path(<span class="code-quote">"/customers/{id}"</span>)
    Response updateCustomer(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> id, Customer customer);

    @POST
    @Path(<span class="code-quote">"/customers"</span>)
    Customer addCustomer(Customer customer);

}

@Path(<span class="code-quote">"/customerservice/"</span>)
<span class="code-keyword">public</span> class Customers <span class="code-keyword">implements</span> CustomerService {

    
    <span class="code-keyword">public</span> Response updateCustomer(<span class="code-object">Long</span> id, Customer customer) {
        <span class="code-keyword">return</span> Response.status(errorCode).build();
    }

    <span class="code-keyword">public</span> Customer addCustomer(Customer customer) {
        <span class="code-keyword">throw</span> <span class="code-keyword">new</span> WebApplicationException(errorCode);
    }

}
</pre>
</div></div>

<p>Similarly, annotations can be inherited from super-classes. In CXF, the resource class can also inherit the class-level annotations from either one of its implemented interfaces or its superclass.    </p>


<h2><a name="JAX-RS-Subresourcelocators."></a>Sub-resource locators.</h2>

<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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customerservice/"</span>)
<span class="code-keyword">public</span> class CustomerService {

    @Path(<span class="code-quote">"/orders/{orderId}/"</span>)
    <span class="code-keyword">public</span> Order getOrder(@PathParam(<span class="code-quote">"orderId"</span>) <span class="code-object">String</span> orderId) {
       ......
    }
}

@XmlRootElement(name = <span class="code-quote">"Order"</span>)
<span class="code-keyword">public</span> class Order {
    <span class="code-keyword">private</span> <span class="code-object">long</span> id;
    <span class="code-keyword">private</span> Items items;

    <span class="code-keyword">public</span> Order() {
    }

    <span class="code-keyword">public</span> <span class="code-object">long</span> getId() {
        <span class="code-keyword">return</span> id;
    }


    @GET
    @Path(<span class="code-quote">"products/{productId}/"</span>)
    <span class="code-keyword">public</span> Product getProduct(@PathParam(<span class="code-quote">"productId"</span>)<span class="code-object">int</span> productId) {
       ......
    }

    @Path(<span class="code-quote">"products/{productId}/items"</span>)
    <span class="code-keyword">public</span> Order getItems(@PathParam(<span class="code-quote">"productId"</span>) <span class="code-object">int</span> productId) {
       <span class="code-keyword">return</span> <span class="code-keyword">this</span>;
    }

    @GET
    <span class="code-keyword">public</span> Items getItems() {
       ......
    }

}
</pre>
</div></div>
<p>A HTTP GET request to <a 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 is returned.<br/>
The request to <a 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 getItems() method which in turn will delegate to an overloaded getItems().</p>

<p>Note that a subresource class like Order is often has no root &#64;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, similarly to Order.getItems() 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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customerservice/"</span>)
<span class="code-keyword">public</span> class CustomerService {

    @Path(<span class="code-quote">"/orders/{orderId}/"</span>)
    <span class="code-keyword">public</span> Order getOrder(@PathParam(<span class="code-quote">"orderId"</span>) <span class="code-object">String</span> orderId) {
       ......
    }
}

<span class="code-keyword">public</span> <span class="code-keyword">interface</span> Order {
    @GET
    @Path(<span class="code-quote">"products/{productId}/"</span>)
    Product getProduct(@PathParam(<span class="code-quote">"productId"</span>)<span class="code-object">int</span> productId);
}

@XmlRootElement(name = <span class="code-quote">"Order"</span>)
<span class="code-keyword">public</span> class OrderImpl <span class="code-keyword">implements</span> Order {
    
    <span class="code-keyword">public</span> Product getProduct(<span class="code-object">int</span> productId) {
       ......
    }
}

@XmlRootElement(name = <span class="code-quote">"Order"</span>)
<span class="code-keyword">public</span> class OrderImpl2 <span class="code-keyword">implements</span> Order {
    
    <span class="code-comment">// overrides JAXRS annotations
</span>    @GET
    @Path(<span class="code-quote">"theproducts/{productId}/"</span>)
    Product getProduct(@PathParam(<span class="code-quote">"id"</span>)<span class="code-object">int</span> productId) {...}
}

</pre>
</div></div>

<h3><a name="JAX-RS-Staticresolutionofsubresources"></a>Static resolution of subresources</h3>

<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" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;beans&gt;</span>
<span class="code-tag">&lt;jaxrs:server staticSubresourceResolution=<span class="code-quote">"true"</span>&gt;</span>
<span class="code-tag"><span class="code-comment">&lt;!-- more configuration --&gt;</span></span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>
<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>


<h2><a name="JAX-RS-MessageBodyProviders"></a>Message Body Providers</h2>

<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/>
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 a "Support for data bindings" section below.</p>

<h3><a name="JAX-RS-CustomMessageBodyProviders"></a>Custom Message Body Providers          </h3>

<p>It's likely that a given application may need to deal with types which are not supported by default.<br/>
Alternatively, developers may want to provide a more efficient support for handling default types such as InputStream.</p>

<p>Here's an example of a custom MessageBodyReader for InputStream :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

@Consumes(<span class="code-quote">"application/octet-stream"</span>)
@Provider
<span class="code-keyword">public</span> class InputStreamProvider <span class="code-keyword">implements</span> MessageBodyReader&lt;InputStream&gt; {

    
    <span class="code-keyword">public</span> <span class="code-object">boolean</span> isReadable(<span class="code-object">Class</span>&lt;InputStream&gt; type, Type genericType, Annotation[] annotations, MediaType mt) {
        <span class="code-keyword">return</span> InputStream.class.isAssignableFrom(type);
    }

    <span class="code-keyword">public</span> InputStream readFrom(<span class="code-object">Class</span>&lt;InputStream&gt; clazz, Type t, Annotation[] a, MediaType mt, 
                         MultivaluedMap&lt;<span class="code-object">String</span>, <span class="code-object">String</span>&gt; headers, InputStream is) 
        <span class="code-keyword">throws</span> IOException {
        <span class="code-keyword">return</span> <span class="code-keyword">new</span> FilterInputStream(is) {
             @Override
             <span class="code-keyword">public</span> <span class="code-object">int</span> read(<span class="code-object">byte</span>[] b) <span class="code-keyword">throws</span> IOException {
                 <span class="code-comment">// filter out some bytes
</span>             }              
        }     
    }
}

</pre>
</div></div>

<p>and here's an example of a custom MessageBodyWriter for Long :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

@ProduceMime(<span class="code-quote">"text/plain"</span>)
@Provider
<span class="code-keyword">public</span> class LongProvider <span class="code-keyword">implements</span> MessageBodyWriter&lt;<span class="code-object">Long</span>&gt; {

    <span class="code-keyword">public</span> <span class="code-object">long</span> getSize(<span class="code-object">Long</span> l, <span class="code-object">Class</span>&lt;?&gt; type, Type genericType, Annotation[] annotations, MediaType mt) {
        <span class="code-keyword">return</span> -1;
    }

    <span class="code-keyword">public</span> <span class="code-object">boolean</span> isWriteable(<span class="code-object">Class</span>&lt;?&gt; type, Type genericType, Annotation[] annotations, MediaType mt) {
        <span class="code-keyword">return</span> <span class="code-object">long</span>.class.isAssignableFrom(type) || <span class="code-object">Long</span>.class.isAssignableFrom(type);
    }

    <span class="code-keyword">public</span> void writeTo(<span class="code-object">Long</span> l, <span class="code-object">Class</span>&lt;?&gt; clazz, Type type, Annotation[] a, 
                        MediaType mt, MultivaluedMap&lt;<span class="code-object">String</span>, <span class="code-object">Object</span>&gt; headers, OutputStream os) 
        <span class="code-keyword">throws</span> IOException {
        os.write(l.toString().getBytes());
        
    }

</pre>
</div></div>

<p>CXF ships some custom providers too. These are providers for dealing with Atom (based on Apache Abdera) and XMLObjects.<br/>
CXF also supports primitive types and their Number friends when text/plain media type is used, either on input or output.   </p>

<h3><a name="JAX-RS-Registeringcustomproviders"></a>Registering custom providers  </h3>


<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 the Spring configuration or programmatically :   </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">

<span class="code-tag">&lt;beans&gt;</span>
<span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService"</span> address=<span class="code-quote">"/"</span>&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;bean class=<span class="code-quote">"org.CustomerService"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>

    <span class="code-tag">&lt;jaxrs:providers&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"isProvider"</span> /&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"longProvider"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:providers&gt;</span>
    <span class="code-tag">&lt;bean id=<span class="code-quote">"isProvider"</span> class=<span class="code-quote">"com.bar.providers.InputStreamProvider"</span>/&gt;</span>
    <span class="code-tag">&lt;bean id=<span class="code-quote">"longProvider"</span> class=<span class="code-quote">"com.bar.providers.LongProvider"</span>/&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>
<span class="code-tag">&lt;/beans&gt;</span>
</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 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 ex, 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 requests with a given media type :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">

<span class="code-tag">&lt;beans&gt;</span>
<span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService1"</span> address=<span class="code-quote">"/1"</span>&gt;</span>
   <span class="code-tag">&lt;bean id=<span class="code-quote">"serviceBean"</span> class=<span class="code-quote">"org.CustomerService"</span> /&gt;</span> 

   <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"serviceBean"</span>/&gt;</span>
   <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>

   <span class="code-tag">&lt;jaxrs:providers&gt;</span>
      <span class="code-tag">&lt;bean class=<span class="code-quote">"com.bar.providers.InputStreamProvider"</span>/&gt;</span>
   <span class="code-tag">&lt;/jaxrs:providers&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>
<span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService2"</span> address=<span class="code-quote">"/2"</span>&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"serviceBean"</span>/&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>

    <span class="code-tag">&lt;jaxrs:providers&gt;</span>
      <span class="code-tag">&lt;bean id=<span class="code-quote">"isProvider"</span> class=<span class="code-quote">"baz.foo.jaxrsproviders.InputStreamProvider"</span>/&gt;</span>
    <span class="code-tag">&lt;/jaxrs:providers&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>

<span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService3"</span> address=<span class="code-quote">"/3"</span>&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"serviceBean"</span>/&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>

    <span class="code-tag">&lt;jaxrs:providers&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"isProvider"</span>/&gt;</span>
    <span class="code-tag">&lt;/jaxrs:providers&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>


<span class="code-tag">&lt;bean id=<span class="code-quote">"isProvider"</span> class=<span class="code-quote">"com.bar.providers.InputStreamProvider"</span>&gt;</span>
   <span class="code-tag">&lt;property name=<span class="code-quote">"limit"</span> value=<span class="code-quote">"5"</span>/&gt;</span>
<span class="code-tag">&lt;/bean&gt;</span>

<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>

<p>In this example a single service bean can be accessed through 3 different paths, /1, /2 and /3. InputStream provider is available on all the 3 paths. com.bar.providers.InputStreamProvider is used in 2 cases, while a special InputStream handler baz.foo.jaxrsproviders.InputStreamProvider from another library is also involved in one case.</p>


<h2><a name="JAX-RS-Customizingmediatypesformessagebodyproviders"></a>Customizing media types for message body providers</h2>

<p>As explained above, message body providers can play a major part in affecting the way target resource methods are matched. If a method returns a custom type Foo and a MessageBodyWriter&lt;Foo&gt; is available then it will be used only if one of the media types specified in a given request's HTTP Accept header matches or intersects with one of the media types specified by &#64;Produces annotation in a MessageBodyWriter&lt;Foo&gt; implementation. The same applies if a method accepts a custom type Foo, but this time the value of &#64;Consumes in MessageBodyReader&lt;Foo&gt; will be matched against a request's ContentType value.    </p>

<p>Sometimes users would like to experiment with media types different to those statically supported by a given message body reader/writer. For example, application/xml might seem a bit too general in some cases and people may want to try some custom/xml type and still use a default JAXB provider. </p>

<p>In such cases it's possible to override the default @Produces and/or @Consumes types supported by a given provider. It only currently works for JAXBElementProvider and JSONProvider, but any custom provider can avail of this support by simply having setter/getter pairs for either produce and/or consume types and the JAXRS runtime will use them instead.<br/>
See <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs/WEB-INF/beans.xml" rel="nofollow">this example</a> on how to provide custom media types from Spring.</p>

<h1><a name="JAX-RS-Supportfordatabindings"></a>Support for data bindings</h1>

<h2><a name="JAX-RS-JAXBsupport"></a>JAXB support</h2>

<p>The request and response can be marshalled and unmarshalled to/from Java object using JAXB. </p>

<p>There's a number of ways to tell to the JAXB provider how objects can be serialized. The simplest way is to mark a given type with @XmlRootElement annotation. </p>


<p>For example:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@XmlRootElement(name = <span class="code-quote">"Customer"</span>)
<span class="code-keyword">public</span> class Customer {
    <span class="code-keyword">private</span> <span class="code-object">String</span> name;
    <span class="code-keyword">private</span> <span class="code-object">long</span> id;

    <span class="code-keyword">public</span> Customer() {
    }

    <span class="code-keyword">public</span> void setName(<span class="code-object">String</span> n) {
        name = n;
    }

    <span class="code-keyword">public</span> <span class="code-object">String</span> getName() {
        <span class="code-keyword">return</span> name;
    }

    <span class="code-keyword">public</span> void setId(<span class="code-object">long</span> i) {
        id = i;
    }

    <span class="code-keyword">public</span> <span class="code-object">long</span> getId() {
        <span class="code-keyword">return</span> id;
    }
}
</pre>
</div></div>
<p>In the example below, the Customer object returned by getCustomer is marshaled using JAXB data binding:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customerservice/"</span>)
<span class="code-keyword">public</span> class CustomerService {
    @GET
    @Path(<span class="code-quote">"/customers/{customerId}/"</span>)
    <span class="code-keyword">public</span> Customer getCustomer(@PathParam(<span class="code-quote">"customerId"</span>) <span class="code-object">String</span> id) {
        ....
    }
}
</pre>
</div></div>
<p>The wire representation of Customer object is:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;Customer&gt;</span>
    <span class="code-tag">&lt;id&gt;</span>123<span class="code-tag">&lt;/id&gt;</span>
    <span class="code-tag">&lt;name&gt;</span>John<span class="code-tag">&lt;/name&gt;</span>
<span class="code-tag">&lt;/Customer&gt;</span>
</pre>
</div></div>

<p>The simplest way to work with the collections is to define a type representing a collection. For example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@XmlRootElement(name = <span class="code-quote">"Customers"</span>)
<span class="code-keyword">public</span> class Customers {
    <span class="code-keyword">private</span> Collection&lt;Customer&gt; customers;

    <span class="code-keyword">public</span> Collection&lt;Customer&gt; getCustomer() {
        <span class="code-keyword">return</span> customers;
    }

    <span class="code-keyword">public</span> void setCustomer(Collection&lt;Customer&gt; c) {
        <span class="code-keyword">this</span>.customers = c;
    }
}
@Path(<span class="code-quote">"/customerservice/"</span>)
<span class="code-keyword">public</span> class CustomerService {
    @GET
    @Path(<span class="code-quote">"/customers/"</span>)
    <span class="code-keyword">public</span> Customers getCustomers() {
        ....
    }
}
</pre>
</div></div>

<p>Alternatively to using @XmlRootElement and Collection wrappers, one can provide an Object factory which will tell JAXB how to <br/>
marshal a given type (in case of Collections - its template type). Another option is to return/accept a JAXBElement directly from/in <br/>
a given method.</p>

<p>Another option is to register one or more JAX-RS ContextResolver providers capable of creating JAXBContexts for a number of different types. The default JAXBElementProvider will check these resolvers first before attempting to create a JAXBContext on its own.   </p>

<p>Finally, JAXBProvider provides a support for serializing response types and deserializing parameters of methods annotated with @XmlJavaTypeAdapter annotations.     </p>

<h3><a name="JAX-RS-ConfiguringJAXBprovider"></a>Configuring JAXB provider</h3>

<p>The default JAXB provider can be configured in a number of ways. For example, here's how to set up marshall properties :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;beans <span class="code-keyword">xmlns:util</span>=<span class="code-quote">"http://www.springframework.org/schema/util"</span>&gt;</span>
<span class="code-tag">&lt;bean id=<span class="code-quote">"jaxbProvider"</span> class=<span class="code-quote">"org.apache.cxf.jaxrs.provider.JAXBElementProvider"</span>&gt;</span>
<span class="code-tag">&lt;property name=<span class="code-quote">"marshallerProperties"</span> ref=<span class="code-quote">"propertiesMap"</span>/&gt;</span>
<span class="code-tag">&lt;/bean&gt;</span>
<span class="code-tag">&lt;util:map id=<span class="code-quote">"propertiesMap"</span> map-class=<span class="code-quote">"java.util.Hashtable"</span>&gt;</span>
<span class="code-tag">&lt;entry key=<span class="code-quote">"jaxb.formatted.output"</span> value=<span class="code-quote">"true"</span>/&gt;</span>
<span class="code-tag">&lt;/util:map&gt;</span>
/<span class="code-tag">&lt;beans&gt;</span>
</pre>
</div></div>

<p>Individual marshal properties can be injected as simple properties. At the moment, Marshaller.JAXB_SCHEMA_LOCATION can be injected as "schemaLocation" property. Schema validation can be enabled and custom &#64;Consume and &#64;Produce media types can be injected, see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs/WEB-INF/beans.xml" rel="nofollow">this example</a> and "Customizing media types for message body providers" and "Schema Validation Support" sections for more information. </p>

<p>One issue which one may need to be aware of it is that an exception may occur during the JAXB serialization process, after some content has already been processed and written to the output stream. By default, the output goes directly to the output HTTP stream so if an exception occurs midway through the process then the output will likely be malformed. If you set 'enableBuffering' property to 'true' then a JAXB provider will write to the efficient CXF CachedOutputStream instead and if an exception occurs then no text which has already been written will make it to the outside world and it will be only this exception that will be reported to the client.  </p>

<p>When enabling buffering, you can also control how the data being serialized will be buffered. By default, an instance of CXF CachedOutputStream will be used. If you set an "enableStreaming" property on the JAXBElementProvider then it will be a CXF CachingXMLEventWriter that will cache the serialization events.</p>

<p>If you would like your own custom provider to write to a cached stream then you can either set an "org.apache.cxf.output.buffering" property to 'true' on a jaxrs endpoint or "enableBuffering" property on the provider. If this provider deals with XML and has a "getEnableStreaming" method returning 'true' then CachingXMLEventWriter will be used, in all other cases CachedOutputStream will be used.</p>

<p>Please note that if you don't have wrapper types for your methods and the classloader you are using does not allow you to call defineClass(), you may need to set '-Dcom.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize'</p>

<h2><a name="JAX-RS-JSONsupport"></a>JSON support</h2>

<p>Default JSON provider relies on Jettison 1.0.1 and it expects the types it deals with to follow the same techniques as described above in the JAXB support section for them to be handled properly. </p>

<p>Following code returns a Customer object that is marshaled to JSON format:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customerservice/"</span>)
<span class="code-keyword">public</span> class CustomerService {
    @Produces(<span class="code-quote">"application/json"</span>)
    @GET
    @Path(<span class="code-quote">"/customers/{customerId}/"</span>)
    <span class="code-keyword">public</span> Customer getCustomer(@PathParam(<span class="code-quote">"customerId"</span>) <span class="code-object">String</span> id) {
        ....
    }
</pre>
</div></div>

<h3><a name="JAX-RS-ConfiguringJSONprovider"></a>Configuring JSON provider</h3>

<p>The default JSON provider can be configured in a number of ways. For example, here's how to set up namespace-to-prefix mappings :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;beans <span class="code-keyword">xmlns:util</span>=<span class="code-quote">"http://www.springframework.org/schema/util"</span>&gt;</span>
<span class="code-tag">&lt;bean id=<span class="code-quote">"jaxbProvider"</span> class=<span class="code-quote">"org.apache.cxf.jaxrs.provider.JSONProvider"</span>&gt;</span>
<span class="code-tag">&lt;property name=<span class="code-quote">"namespaceMap"</span> ref=<span class="code-quote">"jsonNamespaceMap"</span>/&gt;</span>
<span class="code-tag">&lt;/bean&gt;</span>
<span class="code-tag">&lt;util:map id=<span class="code-quote">"jsonNamespaceMap"</span> map-class=<span class="code-quote">"java.util.Hashtable"</span>&gt;</span>
<span class="code-tag">&lt;entry key=<span class="code-quote">"http://www.example.org/books"</span> value=<span class="code-quote">"b"</span>/&gt;</span>
<span class="code-tag">&lt;/util:map&gt;</span>
/<span class="code-tag">&lt;beans&gt;</span>
</pre>
</div></div>

<p>Schema validation can be enabled and custom &#64;Consume and &#64;Produce media types can be injected, see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs/WEB-INF/beans.xml" rel="nofollow">this example</a> and "Customizing media types for message body providers" and "Schema Validation Support" sections for more information. </p>

<h3><a name="JAX-RS-DealingwithJSONarrayserializationissues"></a>Dealing with JSON array serialization issues </h3>

<p>There is a well known problem in the JSON community which shows itself in the wrong serialization of List objects containing a single value only. To work around this issue, one needs to enable a 'serializeAsArray' feature on a JSONProvider, with the additional option of specifying the individual fields which needs to be processed accordingly using an 'arrayKeys' property. Please see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs/WEB-INF/beans.xml" rel="nofollow">this example</a> for more information. </p>

<p>Note that 'serializeAsArray' and 'arrayKeys' can be combined to produce so called natural convention sequences. For example, given the following two class definitions :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@XmlRootElement()
@XmlType(name = <span class="code-quote">"", propOrder = {"</span>title<span class="code-quote">", "</span>comments" })
<span class="code-keyword">public</span> <span class="code-keyword">static</span> class Post {
    <span class="code-keyword">private</span> <span class="code-object">String</span> title;
    <span class="code-keyword">private</span> List&lt;Comment&gt; comments = <span class="code-keyword">new</span> ArrayList&lt;Comment&gt;();
    <span class="code-keyword">public</span> void setTitle(<span class="code-object">String</span> title) {
        <span class="code-keyword">this</span>.title = title;
    }
    <span class="code-keyword">public</span> <span class="code-object">String</span> getTitle() {
        <span class="code-keyword">return</span> title;
    }
    <span class="code-keyword">public</span> void setComments(List&lt;Comment&gt; comments) {
        <span class="code-keyword">this</span>.comments = comments;
    }
    <span class="code-keyword">public</span> List&lt;Comment&gt; getComments() {
        <span class="code-keyword">return</span> comments;
    }
}
   
<span class="code-keyword">public</span> <span class="code-keyword">static</span> class Comment {
     <span class="code-keyword">private</span> <span class="code-object">String</span> title;

     <span class="code-keyword">public</span> void setTitle(<span class="code-object">String</span> title) {
        <span class="code-keyword">this</span>.title = title;
     }

     <span class="code-keyword">public</span> <span class="code-object">String</span> getTitle() {
         <span class="code-keyword">return</span> title;
     }
} 
</pre>
</div></div>

<p>an instance of Post class can be serialized like this if a JSONProvider has had its 'serializeAsArray' property set to 'true' and 'arrayKeys' list property set to contain 'comments' value :</p>

<p>&gt; {"post":{"title":"post","comments":[{"title":"comment1"},{"title":"comment2"}]}} </p>

<p>One other property which might help during the serialization is a boolean "ignoreMixedContent" property which lets to bypass a Jettison issue to do with outputting '$' properties when dealing with empty strings typically encountered in mixed content trees.</p>

<p>You may request that JSONProvider ignores an 'xsi:type' attribute which is serialized in some cases by setting a "writeXsiType" boolean property with a 'false' value.</p>

<p>You may also request that JSONProvider ignores all the namespaces during the serialization process by setting an "ignoreNamespaces" boolean property with a 'true' value. </p>

<h3><a name="JAX-RS-WrappingandUnwrappingJSONsequences"></a>Wrapping and Unwrapping JSON sequences</h3>

<p>A "wrapperName" string property can be used to append a dropped root element name to an incoming JSON sequence for it to be deserialized properly. A "wrapperMap" map property can be used to nominate wrapper names for individual class names.</p>

<p>A boolean "dropRootName" property can be used to tell JSONProvider that a root element needs to be dropped.  </p>

<h2><a name="JAX-RS-AutomaticJAXBElementconversionduringserialization"></a>Automatic JAXBElement conversion during serialization</h2>

<p>In some cases, wrapping object instances into JAXBElements may affect the way XML is produced. For example, given Base and Derived classes, returning an instance of Derived class, with Base one being a method response type, would produce an additional xsi:type attribute if this instance is wrapped into JAXBElement. One can set a "jaxbElementClassNames" list property which can contain class names like "org.foo.Base", etc.</p>

<p>Note that this property is supported for both JAXB and JSON providers.</p>

<h2><a name="JAX-RS-HandlingJAXBbeanswithoutXmlRootElementannotations"></a>Handling JAXB beans without XmlRootElement annotations</h2>

<p>A "jaxbElementClassNames" list property mentioned in the previous section can affect the serialization of objects of types with XmlRootElement annotations.<br/>
In some cases no XmlRootElement annotations are available on types and adding them manually may not be an option; likewise having explicit JAXBElements in method signatures may also be seen as too intrusive. </p>

<p>In such cases, one might want to use a "jaxbElementClassMap" map property which contains class name to simple or expanded QName pairs. This will also lead to the automatic JAXBElement conversion durring the serialization. Finally, 'marshalAsJaxbElement' boolean property can be used when all the instances need to be wrapped - provided that simple class names of these instances can be used as element names.</p>

<p>When deserializing, one can either update an existing ObjectFactory with methods returning JAXBElements or simply set an 'unmarshalFromJaxbElement' property on either JAXB or JSON provider. </p>

<h2><a name="JAX-RS-Handlingexplicitcollections"></a>Handling explicit collections</h2>

<p>JAXB and JSON providers can handle explicit collections like List, Set or base Collection.<br/>
By default they will try to deduce the name of the collection root element from a collection member class. For example, given a Book.class whose @XmlRootElement value is 'Book', the name of the collection name will be 'Books'.<br/>
One can override it by setting a 'collectionWrapperName' string property, like 'Books' or '{<a href="http://books" rel="nofollow">http://books</a>}Book'. </p>

<p>There's also a 'collectionWrapperMap' property available for use in more advanced cases, when collections of different types are used, for example, when mixed collections of objects descended from abstract classes having no @XmlRootElement tags are returned :</p>
<div class="error"><span class="error">Unknown macro: {code.xml}</span> </div>

<p>&lt;!-- Configure JAXB Provider --&gt;<br/>
&lt;bean id="jaxbProvider"<br/>
class="org.apache.cxf.jaxrs.provider.JAXBElementProvider"&gt;<br/>
  &lt;property name="collectionWrapperMap"&gt;<br/>
  &lt;map&gt;<br/>
    &lt;entry&gt;<br/>
      &lt;key&gt;&lt;value&gt;com.foo.bar.MyObject&lt;/value&gt;&lt;/key&gt;<br/>
      &lt;value&gt;MyObjects&lt;/value&gt;<br/>
    &lt;/entry&gt;<br/>
   &lt;/map&gt;<br/>
   &lt;/property&gt;<br/>
&lt;/bean&gt; </p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

JSONProvider can only serialize explicit collections at the moment. If needed, it can be told to drop a collection element name using a <span class="code-object">boolean</span> 'dropCollectionWrapperElementName'.

h2. Aegis Data Binding

Use org.apache.cxf.provider.AegisElementProvider to start doing Aegis with JAX-RS
org.apache.cxf.provider.AegisJSONProvider can be used to output JSON with the help of Aegis.
Similarly to the <span class="code-keyword">default</span> JSONProvider <span class="code-keyword">this</span> Aegis-based JSON provider can have <span class="code-quote">"namespaceMap"</span>, <span class="code-quote">"serializeAsArray"</span>, <span class="code-quote">"arrayKeys"</span>, <span class="code-quote">"dropRootElement"</span> and <span class="code-quote">"writeXsiType"</span> properties set.

h2. XMLBeans

Use org.apache.cxf.provider.XmlBeansElementProvider to start doing XmlBeans with JAX-RS

h2. Support <span class="code-keyword">for</span> CXF DataBindings

Starting from CXF 2.2.3 it is now possible to register a CXF DataBinding bean using a jaxrs:databinding element and it will be wrappped as a JAXRS MessageBodyReader/Writer [DataBindingProvider|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/DataBindingProvider.java] capable of dealing with XML-based content. It can be of special interest to users combining JAX-RS and JAXWS. Thus CXF JAXB, Aegis, SDO and XMLBeans databindings can be easily plugged in.
</span>JSON support is also provided <span class="code-keyword">for</span> all these databindings by [DataBindingJSONProvider|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/DataBindingJSONProvider.java].
</span>Please see [<span class="code-keyword">this</span> configuration file|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_databinding/WEB-INF/beans.xml] <span class="code-keyword">for</span> some examples.
</span>
Similarly to the <span class="code-keyword">default</span> JSONProvider the DataBindingJSONProvider JSON provider can have <span class="code-quote">"namespaceMap"</span>, <span class="code-quote">"serializeAsArray"</span>, <span class="code-quote">"arrayKeys"</span>, <span class="code-quote">"dropRootElement"</span> and <span class="code-quote">"writeXsiType"</span> properties set. Additionally it may also have an <span class="code-quote">"ignoreMixedContent"</span> property set.

Note that at the moment <span class="code-keyword">this</span> feature is only available on the trunk. JAXB and Aegis DataBindings (XML only) is supported in CXF 2.2.3.

h2. Customizing request and response XML

Sometimes you may want to adapt an incoming XML request or outgoing XML response. For example, your application has changed but a lot of legacy clients have not been updated yet.
When dealing with XML, the easiest and fastest option is to register a custom STAX XMLStreamWriter or XMLStreamReader and modify XML as needed. You can register a custom STAX 
handler from RequestHandler or ResponseHandler filters or input/output CXF interceptors. For example, see [XMLStreamWriterProvider|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/XmlStreamWriterProvider.java] and [CustomXmlStreamWriter|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/CustomXmlStreamWriter.java].
</span>
Another option is to register a custom JAXB or JSON provider extending CXF JAXBElementProvider or JSONProvider and overriding a method like createStreamWriter(). 
Typically one would delegate to a <span class="code-keyword">super</span> class first and then wrap the returned writer in a custom writer, see [CustomXmlStreamWriter|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/CustomXmlStreamWriter.java] <span class="code-keyword">for</span> an example.
</span>
One can also use XSLTJaxbProvider to produce or modify the incoming XML. In fact, XSLTJaxbProvider can be used to adapt formats like JSON <span class="code-keyword">for</span> legacy consumers.

Please also see <span class="code-keyword">this</span> [overview|http:<span class="code-comment">//soa.dzone.com/articles/pragmatic-web-services-apache] of various related features available in CXF. 
</span>

h2. Schema validation support

There're two ways you can enable a schema validation.

1. Using jaxrs:schemaLocations element :

{code:xml}
&lt;beans xmlns:util=<span class="code-quote">"http:<span class="code-comment">//www.springframework.org/schema/util"</span>&gt;
</span>&lt;jaxrs:server address=<span class="code-quote">"/"</span>&gt;
  &lt;jaxrs:schemaLocations&gt;
     &lt;jaxrs:schemaLocation&gt;classpath:/schemas/a.xsd&lt;/jaxrs:schemaLocation&gt;
     &lt;jaxrs:schemaLocation&gt;classpath:/schemas/b.xsd&lt;/jaxrs:schemaLocation&gt;
  &lt;/jaxrs:schemaLocations&gt;
&lt;/jaxrs:server&gt;
/&lt;beans&gt;
</pre>
</div></div>

<p>Using this option is handy when you have multiple bindings involved which support the schema validation. In this case<br/>
individual MessageBodyReader implementations which have a method setSchemas(List&lt;Sring&gt; schemaLocations) called. Default JAXBElementProvider and JSONProvider which rely on JAXB can be enabled to do the validation this way. In the above example two schema documents are provided, with b.xsd schema presumably importing a.xsd  </p>

<p>2. Configuring providers individually</p>

<p>Please see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs/WEB-INF/beans.xml" rel="nofollow">this example</a> of how both JAXB and JSON providers are using a shared schema validation configuration.</p>

<h1><a name="JAX-RS-Debugging"></a>Debugging</h1>

<p>One can easily try from a browser how a given resource class reacts to different HTTP Accept or Accept-Language header values.<br/>
For example, if a resource class supports "/resource" URI then one can test the resource class using one of the following    <br/>
queries :</p>

<p>GET /resource.xml<br/>
GET /resource.en</p>

<p>The runtime will replace '.xml' or '.en' with an appropriate header value. For it to know the type or language value associated with <br/>
a given URI suffix, some configuration needs to be done. Here's an example how to do it in Spring :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">

  <span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService"</span> address=<span class="code-quote">"/"</span>&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"customerService"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>
    <span class="code-tag">&lt;jaxrs:extensionMappings&gt;</span>
      <span class="code-tag">&lt;entry key=<span class="code-quote">"json"</span> value=<span class="code-quote">"application/json"</span>/&gt;</span>
      <span class="code-tag">&lt;entry key=<span class="code-quote">"xml"</span> value=<span class="code-quote">"application/xml"</span>/&gt;</span>
    <span class="code-tag">&lt;/jaxrs:extensionMappings&gt;</span>
    <span class="code-tag">&lt;jaxrs:languageMappings/&gt;</span>
  <span class="code-tag">&lt;/jaxrs:server&gt;</span>
</pre>
</div></div>

<p>See below for a more complete configuration example.</p>

<p>See the JAX-RS specification for more details.</p>

<p>CXF also supports _type query as an alternative to appending extensions like '.xml' to request URIs :</p>

<p>GET /resource?_type=xml </p>

<h1><a name="JAX-RS-Logging"></a>Logging</h1>

<p>Existing CXF features can be applied to jaxrs:server or jaxrs:client, whenever it makes sense.<br/>
To enable logging of requests and responses, simply do :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
&lt;beans <span class="code-keyword">xmlns:cxf</span>=<span class="code-quote">"http://cxf.apache.org/core"</span> 
 xsi:schemaLocation=<span class="code-quote">"http://cxf.apache.org/core http://cxf.apache.org/schemascore.xsd"</span>&gt;
<span class="code-tag">&lt;jaxrs:server&gt;</span>
<span class="code-tag">&lt;jaxrs:features&gt;</span>
     <span class="code-tag">&lt;cxf:logging/&gt;</span>
<span class="code-tag">&lt;/jaxrs:features&gt;</span>
<span class="code-tag">&lt;jaxrs:server&gt;</span>
<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>

<p>Please make sure a "http://cxf.apache.org/core" namespace is in scope.</p>

<h1><a name="JAX-RS-Filters"></a>Filters</h1>

<p>CXF suports filters. Often it's necessary to pre- or post-process some requests according to a number of requirements.<br/>
For example, a request like </p>

<p>GET /resource?_type=xml is supported by a CXF specific RequestHandler filter which modifies the CXF input Message <br/>
by updating one of its headers.</p>

<p>In some cases users can use the existing filter technologies such as Servler filters or Spring AOP proxies. In other cases, it can be handy<br/>
to write a CXF filter which will introspect the resource class, input or output message, the operation which was invoked and modify the request or response accordingly. </p>

<p>Here are the interface definitions : </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> <span class="code-keyword">interface</span> RequestHandler {
    
    Response handleRequest(Message inputMessage, 
                           ClassResourceInfo resourceClass);

}
</pre>
</div></div>

<p>The request handler implementation can either modify the input Message and let the request to proceed or block the request by returning a non-null Response. </p>

<p>A response filter implementation can get an access to OperationResourceInfo object representing a method to be invoked on a resource class :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
OperationResourceInfo ori = exchange.get(OperationResourceInfo.class);
</pre>
</div></div>  

<p>Use OperationResourceInfo in your filter with care. In principle a given request chain may have filters which may want to  overwrite Accept or ContentType message headers which might lead to another method be selected. However if you know no such filters (will) exist in your application then you might want to check an OperationResourceInfo instance as part of your filter logic. </p>

<p>When modifying an input message, one would typically want to replace a message input stream or one of its headers, such as ContentType :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
InputStream is = message.getContent(InputStream.class);
message.setContent(<span class="code-keyword">new</span> MyFilterInputStream(is));
message.put(Message.ACCEPT_CONTENT_TYPE, <span class="code-quote">"custom/media"</span>); 
</pre>
</div></div>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> <span class="code-keyword">interface</span> ResponseHandler {
    
    Response handleResponse(Message outputMessage,
                           OperationResourceInfo invokedOperation, 
                           Response response);

}
</pre>
</div></div>

<p>The response handler implementation can optionally overwrite or modify the application Response or modify the output message. When modifying an output message, one may want to either replace an output stream before message body providers attempt to write to it or replace the actual response object :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">// replace an output stream
</span>OutputStream os = message.getContent(OutputStream.class);
message.setContent(<span class="code-keyword">new</span> MyFilterOutputStream(os));

<span class="code-comment">// replace an actual object
</span>response.setEntity(<span class="code-keyword">new</span> MyWrapper(response.getEntity()))
<span class="code-comment">// or using a low-level Message api <span class="code-keyword">if</span> needed
</span>MessageContentsList objs = MessageContentsList.getContentsList(message);
<span class="code-keyword">if</span> (objs !== <span class="code-keyword">null</span> &amp;&amp; objs.size() == 1) {
    <span class="code-object">Object</span> responseObj = objs.remove(0);
    obj.add(<span class="code-keyword">new</span> MyWrapper(responseObj));
}
</pre>
</div></div>

<p>Please see <a href="http://sberyozkin.blogspot.com/2008/07/rest-and-soap-united-in-cxf.html" rel="nofollow">this blog entry</a> for another example of when response filters can be useful.</p>

<p>Multiple request and response handlers are supported.</p>

<p>The implementations can be registered like any other types of providers :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">

<span class="code-tag">&lt;beans&gt;</span>
<span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService"</span> address=<span class="code-quote">"/"</span>&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;bean class=<span class="code-quote">"org.CustomerService"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>

    <span class="code-tag">&lt;jaxrs:providers&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"authorizationFilter"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:providers&gt;</span>
    <span class="code-tag">&lt;bean id=<span class="code-quote">"authorizationFilter"</span> class=<span class="code-quote">"com.bar.providers.AuthorizationRequestHandler"</span>&gt;</span>
        <span class="code-tag"><span class="code-comment">&lt;!-- authorization bean properties --&gt;</span></span>
    <span class="code-tag">&lt;/bean&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>
<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>

<h2><a name="JAX-RS-DifferencebetweenJAXRSfiltersandCXFinterceptors"></a>Difference between JAXRS filters and CXF interceptors</h2>

<p>JAXRS runtime flow is mainly implemented by a pair of 'classical' CXF interceptors. JAXRSInInterceptor is currently at Phase.PRE_STREAM phase while JAXRSOutInterceptor is currently at Phase.MARSHAL phase.</p>

<p>JAXRS filters can be thought of as additional handlers. JAXRSInInterceptor deals with a chain of RequestHandlers, just before the invocation. JAXRSOutInterceptor deals with a chain of ResponseHandlers, just after the invocation but before message body writers get their chance.</p>

<p>Sometimes you may want to use CXF interceptors rather than writing JAXRS filters. For example, suppose you combine JAXWS and JAXRS and you need to log only inbound or outbound messages. You can reuse the existing CXF interceptors :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;beans&gt;</span>
<span class="code-tag">&lt;bean id=<span class="code-quote">"logInbound"</span> class=<span class="code-quote">"org.apache.cxf.interceptor.LoggingInInterceptor"</span>/&gt;</span>
<span class="code-tag">&lt;bean id=<span class="code-quote">"logOutbound"</span> class=<span class="code-quote">"org.apache.cxf.interceptor.LoggingOutInterceptor"</span>/&gt;</span>

<span class="code-tag">&lt;jaxrs:server&gt;</span> 
 <span class="code-tag">&lt;jaxrs:inInterceptors&gt;</span>
     <span class="code-tag">&lt;ref bean=<span class="code-quote">"logInbound"</span>/&gt;</span>
 <span class="code-tag">&lt;/jaxrs:inInterceptors&gt;</span>
 <span class="code-tag">&lt;jaxrs:outInterceptors&gt;</span>
    <span class="code-tag">&lt;ref bean=<span class="code-quote">"logOutbound"</span>/&gt;</span>
 <span class="code-tag">&lt;/jaxrs:outInterceptors&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>

<span class="code-tag">&lt;jaxws:endpoint&gt;</span>
 <span class="code-tag">&lt;jaxws:inInterceptors&gt;</span>
     <span class="code-tag">&lt;ref bean=<span class="code-quote">"logInbound"</span>/&gt;</span>
 <span class="code-tag">&lt;/jaxws:inInterceptors&gt;</span>
 <span class="code-tag">&lt;jaxws:outInterceptors&gt;</span>
    <span class="code-tag">&lt;ref bean=<span class="code-quote">"logOutbound"</span>/&gt;</span>
 <span class="code-tag">&lt;/jaxws:outInterceptors&gt;</span>
<span class="code-tag">&lt;/jaxws:endpoint&gt;</span>

<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div> 

<p>Reusing other CXF interceptors/features such as GZIP handlers can be useful too.</p>

<h2><a name="JAX-RS-Overridingrequestandresponseproperties"></a>Overriding request and response properties</h2>

<p>Now and then one needs to overwrite various request and response properties like HTTP method or request URI, <br/>
response headers or status codes. JAX-RS Response may be used to specify custom status and response headers but <br/>
it might be intrusive to use it in certain cases.</p>

<p>Here are some more examples.</p>

<h3><a name="JAX-RS-OverridingHTTPmethod"></a>Overriding HTTP method</h3>

<p>There are 3 options available :<br/>
1. Use a _method system query like</p>

<p>&gt; GET /books?_method=RETRIEVE</p>

<p>2. Register a custom RequestHandler filter which will replace the current method value keyed by <br/>
Message.HTTP_REQUEST_METHOD in a given Message.   </p>

<p>3. Specify an HTTP header X-HTTP-Method-Override :</p>

<p>&gt; POST /books<br/>
&gt; X-HTTP-Method-Override : PATCH</p>

<p>For example, at the moment http-centric client API does not support arbitrary HTTP verbs except for those supported <br/>
by Java HTTPUrlConnection. When needed, X-HTTP-Method-Override can be set to overcome this limitation.</p>

<h3><a name="JAX-RS-OverridingrequestURI"></a>Overriding request URI</h3>

<p>One can do it either from a CXF input interceptor (registered at the early phase like USER_STREAM) or from a RequestHandler filter, for example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-object">String</span> s = m.get(Message.REQUEST_URI);
s += <span class="code-quote">"/data/"</span>;
m.put(Message.REQUEST_URI, s);
</pre>
</div></div> 

<p>Similarly, one can update request HTTP headers, by modifying a Message.REQUEST_HEADERS Message object which is a Map containing String and List of Strings entries.</p>

<h3><a name="JAX-RS-Overridingresponsestatuscodeandheaders"></a>Overriding response status code and headers</h3>

<p>It is assumed here a user prefers not to use explicit Response objects in the application code.<br/>
This can be done either from a CXF output interceptor (phase like MARSHALL will do) or from a ResponseHandler filter, for example this code will work for both JAXRS and JAXWS :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class CustomOutInterceptor <span class="code-keyword">extends</span> AbstractOutDatabindingInterceptor {
    
    <span class="code-keyword">public</span> CustomOutInterceptor() {
        <span class="code-keyword">super</span>(Phase.MARSHAL);
    }

    <span class="code-keyword">public</span> void handleMessage(Message outMessage) {
        Map&lt;<span class="code-object">String</span>, List&lt;<span class="code-object">String</span>&gt;&gt; headers = (Map&lt;<span class="code-object">String</span>, List&lt;<span class="code-object">String</span>&gt;&gt;)outMessage.get(Message.RESPONSE_HEADERS);
        <span class="code-comment">// modify headers  
</span>    }    
</pre>
</div></div>  

<p>At the moment it is not possible to override a response status code from a CXF interceptor running before JAXRSOutInterceptor, like CustomOutInterceptor above, which will be fixed.<br/>
The only option at the moment is to use a custom ResponseHandler which will replace the current Response object with another one containing the required status. </p>

<h2><a name="JAX-RS-IgnoringJAXRSMessageBodyWriters"></a>Ignoring JAXRS MessageBodyWriters</h2>

<p>In some cases you may want to have a JAXRS Response entity which a given RequestHandler or ResponseHandler has produced to be directly written to the output stream. For example, a CXF JAXRS WADLGenerator RequestHandler produces an XML content which does not have to be serialized by JAXRS MessageBodyWriters. If you do need to have the writers ignored then set the following property on the current exchange in the custom handler :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
message.getExchange().put(<span class="code-quote">"ignore.response.writers"</span>, <span class="code-keyword">true</span>);
</pre>
</div></div>

<h1><a name="JAX-RS-Custominvokers"></a>Custom invokers</h1>

<p><b>Note</b> This feature is not available in CXF 2.2.1 </p>

<p>Using custom JAXR-RS invokers is yet another way to pre or post process a given invocation. For example, this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/CustomJAXRSInvoker.java" rel="nofollow">invoker</a> does a security check before delegating to the default JAXRS invoker. A custom invoker, like a request filter, has the access to all the information accumulated during the processing of a given call, but additionally, it can also check the actual method parameter values.</p>

<p>Custom invokers can be registered like this :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;beans&gt;</span>

<span class="code-tag">&lt;jaxrs:server address=<span class="code-quote">"/"</span>&gt;</span> 
 <span class="code-tag">&lt;jaxrs:invoker&gt;</span>
   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.systest.jaxrs.CustomJAXRSInvoker"</span>/&gt;</span>
 <span class="code-tag">&lt;/jaxrs:invoker&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>

<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div> 

<h1><a name="JAX-RS-AdvancedHTTP"></a>Advanced HTTP</h1>

<p>CXF JAXRS provides support for a number of advanced HTTP features by handling If-Match, If-Modified-Since and ETags headers. JAXRS Request context object can be used to check the preconditions. Vary, CacheControl, Cookies and Set-Cookies are also supported.</p>

<h1><a name="JAX-RS-SupportforContinuations"></a>Support for Continuations </h1>

<p>Please see <a href="http://sberyozkin.blogspot.com/2008/12/continuations-in-cxf.html" rel="nofollow">this blog entry</a> describing how JAXRS (and indeed) JAXWS services can rely on the CXF Continuations API. Currently, only Jetty based services can rely on this option.</p>

<h1><a name="JAX-RS-SecureJAXRSservices"></a>Secure JAX-RS services</h1>

<p>A demo called samples\jax_rs\basic_https shows you how to do communications using HTTPS.<br/>
Spring Security can be quite easily applied too (see "JAXRS and Spring AOP" section for some general advice).</p>

<h2><a name="JAX-RS-CheckingHTTPsecurityheaders"></a>Checking HTTP security headers</h2>

<p>It is often containers like Tomcat or frameworks like Spring Security which deal with ensuring a current user is authenticated.  <br/>
Sometimes you might want to deal with the authentication manually. The easiest way to do it is to register a custom invoker or RequestHandler filter<br/>
which will extract a user name and password like this (note it will work only for basic authentication requests only) :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class AuthenticationHandler <span class="code-keyword">implements</span> RequestHandler {

    <span class="code-keyword">public</span> Response handleRequest(Message m, ClassResourceInfo resourceClass) {
        AuthorizationPolicy policy = (AuthorizationPolicy)m.getContent(AuthorizationPolicy.class);
        policy.getUserName();
        policy.getPassword(); 
        <span class="code-comment">// alternatively :
</span>        <span class="code-comment">// HttpHeaders headers = <span class="code-keyword">new</span> HttpHeadersImpl(m);
</span>        <span class="code-comment">// access the headers as needed  
</span>        <span class="code-keyword">return</span> <span class="code-keyword">null</span>;
    }

}
</pre>
</div></div> 

<h2><a name="JAX-RS-SecurityManagerandIllegalAccessExceptions"></a>SecurityManager and IllegalAccessExceptions</h2>

<p>If java.lang.SecurityManager is installed then you'll likely need to configure the trusted JAXRS codebase with a 'suppressAccessChecks' permission for the injection of JAXRS context or parameter fields to succeed. For example, you may want to update a Tomcat <a href="http://tomcat.apache.org/tomcat-5.5-doc/security-manager-howto.html" rel="nofollow">catalina.policy</a> with the following permission :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
grant codeBase <span class="code-quote">"file:${catalina.home}/webapps/yourwebapp/lib/cxf.jar"</span> {
    permission java.lang.reflect.ReflectPermission <span class="code-quote">"suppressAccessChecks"</span>;
};
</pre>
</div></div>

<h1><a name="JAX-RS-ClientAPI"></a>Client API</h1>

<p>JAX-RS 1.0 does not provide for the standard approach toward consuming pure HTTP-based services so in CXF we have provided 3 flavors of the client API : proxy-based, HTTP-centric and XML-centric.</p>

<h2><a name="JAX-RS-ProxybasedAPI"></a>Proxy-based API</h2>

<p>With the proxy-based API, one can reuse on the client side the interfaces or even the resource classes which have already been designed for processing the HTTP requests on the server side (note that a cglib-nodeps dependency need to be available on the classpath for proxies created from concrete classes). When reused on the client side, they simply act as the remote proxies.</p>

<p><a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/JAXRSClientFactory.java" rel="nofollow">JAXRSClientFactory</a> is a utility class which wraps <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/JAXRSClientFactoryBean.java" rel="nofollow">JAXRSClientFactoryBean</a>. JAXRSClientFactory has a number of utility methods but JAXRSClientFactoryBean can be used directly when needed.</p>

<p>For example, given these class definitions :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/bookstore"</span>)
<span class="code-keyword">public</span> <span class="code-keyword">interface</span> BookStore {
   @GET
   Books getAllBooks();
   
   @Path(<span class="code-quote">"{id}"</span>)
   BookResource getBookSubresource(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">long</span> id) <span class="code-keyword">throws</span> NoBookFoundException;
}

<span class="code-keyword">public</span> class BookStoreImpl <span class="code-keyword">implements</span> BookStore {
   <span class="code-keyword">public</span> Books getAllBooks() {}
   
   <span class="code-keyword">public</span> Book getBookSubresource(<span class="code-object">long</span> id) <span class="code-keyword">throws</span> NoBookFoundException {}
}

<span class="code-keyword">public</span> <span class="code-keyword">interface</span> BookResource {
   @GET
   Book getDescription();
}

<span class="code-keyword">public</span> class BookResourceImpl <span class="code-keyword">implements</span> BookResource {
   @GET
   Book getDescription() {}
}

</pre>
</div></div>

<p>the following client code retrieves a Book with id '1' and a collection of books: </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
BookStore store = JAXRSClientFactory.create(<span class="code-quote">"http:<span class="code-comment">//bookstore.com"</span>, BookStore.class);
</span><span class="code-comment">// (1) remote GET call to http://bookstore.com/bookstore
</span>Books books = store.getAllBooks();
<span class="code-comment">// (2) no remote call
</span>BookResource subresource = store.getBookSubresource(1);
<span class="code-comment">// {3} remote GET call to http://bookstore.com/bookstore/1
</span>Book b = subresource.getDescription();
</pre>
</div></div>     

<p>When proxies are created, initially or when subresource methods are invoked, the current URI is updated with corresponding &#64;Path, &#64;PathParam, &#64;QueryParam or @MatrixParam values, while &#64;HttpHeader and &#64;CookieParam values contribute to the current set of HTTP headers. Same happens before the remote invocation is done. </p>

<p>It is important to understand that strictly speaking there is no direct relationship between a given method on the client side and the same one on the server side. The job of the proxy is to construct a correct URI according to a given class and method specifications - it may or may not be the same method on the corresponding server class that will be invoked (provided of course that it is a JAX-RS annotated server resource class - but it may not be the case !). More often than not, you will see a method foo() invoked on a server resource class whenever the same method is invoked on the corresponding remote proxy - but in the presence of &#64;Path annotations with arbitrary regular expressions is is not guaranteed - never mind, the most important things is that a proxy will produce a correct URI and it will be matched as <b>expected</b> by a server class.   </p>

<p>MessageBodyReaders and MessageBodyWriters are used to process request or response bodies, same way as on the server side. More specifically. method body writers are invoked whenever a remote method parameter is assumed to be a request body (that is, it has no JAX-RS annotations attached) or when a form submission is emulated with the help of either &#64;FormParams or JAX-RS MultivaluedMap. </p>

<p>You can make multiple remote invocations on the same proxy (initial or subresource), the current URI and headers are updated properly. </p>

<p>If you would like to proxify concrete classes such as BookStoreImpl for example (say you can not extract interfaces), then drop a cglib-nodeps.jar on a classpath. Such classes must have a default constructor. All the methods which have nothing to do with JAX-RS will simply be ignored on the client side and marked as unsupported.</p>

<h3><a name="JAX-RS-Customizingproxies"></a>Customizing proxies </h3>

<p>Proxies end up implementing not only the interface requested at the proxy creation time but also a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/Client.java" rel="nofollow">Client</a> interface. In many cases one does not need to explicitly specify commonly used HTTP headers such as Content-Type or Accept as this information will likely be available from &#64;Consumes or &#64;Produces annotations. At the same time you may to explicitly set either of these headers, or indeed some other header. You can use a simple <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/WebClient.java" rel="nofollow">WebClient</a> utility method for converting a proxy to a base client :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
BookStore proxy = JAXRSClientFactory.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>, BookStore.class);
</span>WebClient.client(proxy).accept(<span class="code-quote">"text/xml"</span>);
<span class="code-comment">// <span class="code-keyword">continue</span> using the proxy    </span>
</pre>
</div></div>

<p>You can also check a current set of headers, current and base URIs and a client Response.</p>

<h3><a name="JAX-RS-ConvertingproxiestoWebClientsandviceversa"></a>Converting proxies to Web Clients and vice versa</h3>

<p>Using proxies is just one way how you can consume a service. Proxies hide away the details of how URIs are being composed while HTTP-centric WebClients provide for an explicit URI creation. Both proxies and http clients rely on the same base information such as headers and the current URI so at any moment of time you can create a WebClient instance out of the existing proxy :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
BookStore proxy = JAXRSClientFactory.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>, BookStore.class);
</span>WebClient client = WebClient.create(proxy);
<span class="code-comment">// <span class="code-keyword">continue</span> using the http client    </span>
</pre>
</div></div>

<p>At any moment of time you can convert an http client into a proxy too :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
BookStore proxy = JAXRSClientFactory.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>, BookStore.class);
</span>WebClient client = WebClient.create(proxy);
BookStore proxy = JAXRSClientFactory.fromClient(client, BookStore.class);
</pre>
</div></div>

<h3><a name="JAX-RS-Handlingexceptions"></a>Handling exceptions</h3>

<p>There is a couple of ways you can handle remote exceptions with proxies.<br/>
One approach is to register a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/ResponseExceptionMapper.java" rel="nofollow">ResponseExceptionMapper</a> as a provider either from Spring using a jaxrs:client or using a corresponding JAXRSClientFactory utility method. This way you can map remote error codes to expected checked exceptions or runtime exceptions if needed.</p>

<p>If no ResponseExceptionMapper is available when a remote invocation failed then a WebApplicationException will be thrown. At this point of time you can check the actual Response and proceed from there :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
BookStore proxy = JAXRSClientFactory.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>, BookStore.class);
</span><span class="code-keyword">try</span> {
    proxy.getBook();
} <span class="code-keyword">catch</span>(WebApplicationException ex) {
  Response r = WebClient.create(proxy).getResponse();
  <span class="code-comment">// check error code, <span class="code-keyword">try</span> using WebClient explicitly, etc
</span>}
</pre>
</div></div>

<h3><a name="JAX-RS-ConfiguringproxiesinSpring"></a>Configuring proxies in Spring</h3>

<p>When creating a proxy with JAXRSClientFactory, you can pass a Spring configuration location as one of the arguments. Or you can create a default bus using a spring configuration and all proxies will pick it up :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
SpringBusFactory bf = <span class="code-keyword">new</span> SpringBusFactory();
Bus bus = bf.createBus(<span class="code-quote">"org/apache/cxf/systest/jaxrs/security/jaxrs-https.xml"</span>);
BusFactory.setDefaultBus(bus);
<span class="code-comment">// BookStore proxy will get the configuration from Spring
</span>BookStore proxy = JAXRSClientFactory.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>, BookStore.class);</span>
</pre>
</div></div> 

<h3><a name="JAX-RS-Injectingproxies"></a>Injecting proxies</h3>

<p>See this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_soap_rest/WEB-INF/beans.xml" rel="nofollow">bean</a> for an example how jaxrs:client can be used to inject a proxy </p>

<h3><a name="JAX-RS-Limitations"></a>Limitations</h3>

<p>Proxy methods can not have &#64;Context method parameters and subresource methods returning Objects can not be invoked - perhaps it is actually not too bad at all - please inject contexts as field or bean properties and have subresource methods returning typed classes : interfaces, abstract classes or concrete implementations. </p>

<p>Proxies are currently not thread-safe.</p>

<h2><a name="JAX-RS-HTTPcentricclients"></a>HTTP-centric clients</h2>

<p>HTTP centric clients are <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/WebClient.java" rel="nofollow">WebClient</a> instances which also implement the <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/Client.java" rel="nofollow">Client</a> interface. In addition to setting various Client request properties, you can also make an explicit HTTP invocation with an HTTP verb being the name of a given operation :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
WebClient client = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>);
</span>Book book = client.path(<span class="code-quote">"bookstore/books"</span>).accept(<span class="code-quote">"text/xml"</span>).get(Book.class);
</pre>
</div></div>

<p>You can choose to get an explicit JAX-RS Response instead and check the response code, headers or entity body if any :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
WebClient client = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>);
</span>Response r = client.path(<span class="code-quote">"bookstore/books"</span>).type(<span class="code-quote">"text/xml"</span>).accept(<span class="code-quote">"text/xml"</span>).post(<span class="code-keyword">new</span> Book());
InputStream is = (InputStream)r.getEntity();
Book b = getFromInputStreamUsingJaxb(is);
</pre>
</div></div>

<p>WebClient lets you get back to a base URI or to a previous path segment and move forward, it can be handy for getting a number of individual entries from a service with ids embedded in path segments :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
WebClient client = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>);
</span>List&lt;Book&gt; books = getBooks(client, 1L, 2L, 3L)

<span class="code-keyword">private</span> List&lt;Book&gt; getBooks(WebClient client, <span class="code-object">Long</span> ...ids) {
   List&lt;Book&gt; books = <span class="code-keyword">new</span> ArrayList&lt;Book&gt;(); 
   <span class="code-keyword">for</span> (<span class="code-object">Long</span> id : ids) {
       books.add(client.path(id).get(Book.class));
       client.back(); 
   } 
   <span class="code-keyword">return</span> books;
}
</pre>
</div></div>

<p>The above code will send requests like "GET <a href="http://books/1" rel="nofollow">http://books/1</a>", "GET <a href="http://books/2" rel="nofollow">http://books/2</a>", etc. </p>

<h3><a name="JAX-RS-Handlingexceptions"></a>Handling exceptions</h3>


<p>You can handle remote exceptions by either explicitly getting a Response object as shown above and handling error statuses as needed or<br/>
you can catch a WebApplicationException and get a Response from it. </p>

<h3><a name="JAX-RS-ConfiguringHTTPclientsinSpring"></a>Configuring HTTP clients in Spring</h3>

<p>Like proxies, HTTP clients can be created using a number of WebClient static utility methods : you can pass a location to a Spring configuration bean if needed or you can set up a default bus as shown above. </p>

<h2><a name="JAX-RS-XMLcentricclients"></a>XML-centric clients</h2>

<p>XML-centric clients are WebClients using an <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/xml/XMLSource.java" rel="nofollow">XMLSource</a> utility class. XMLSource has a number of methods facilitating the retrieval of JAXB beans, individual properties or links with the help of XPath expressions. For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
WebClient wc = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//aggregated/data"</span>);
</span>XMLSource source = wc.get(XMLSource.class);
source.setBuffering(<span class="code-keyword">true</span>);
Book b1 = source.getNode(<span class="code-quote">"/books/book[position() = 1]"</span>, Book.class);
Book b2 = source.getNode(<span class="code-quote">"/books/book[position() = 2]"</span>, Book.class);
</pre>
</div></div>

<p>Note that an XMLSource instance can be set to buffer the input stream thus allowing for executing multiple XPath queries.</p>

<h2><a name="JAX-RS-ConfiguringClientsatRuntime"></a>Configuring Clients at Runtime</h2>

<p>Proxy and http-centric clients are typically created by JAXRSClientFactory or WebClient factory methods but <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/JAXRSClientFactoryBean.java" rel="nofollow">JAXRSClientFactoryBean</a> can also be used for pre-configuring clients, before they are created.</p>

<p>Sometimes, you may want to configure a client instance after it is been created. For example, one may want to configure HTTPConduit programmatically, as opposed to setting its properties using Spring. ClientConfiguration represents a client-specific configuration state and can be accessed like this :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
Book proxy = JAXRSClientFactory.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>, Book.class);
</span>ClientConfiguration config = WebClient.getConfig(proxy);
HTTPConduit conduit1 = (HTTPConduit)config.getConduit();

WebClient webclient = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>);
</span>HTTPConduit conduit2 = (HTTPConduit)WebClient.getConfig(webclient).getConduit();
</pre>
</div></div>

<h2><a name="JAX-RS-ConfiguringHTTPConduitfromSpring"></a>Configuring HTTP Conduit from Spring</h2>

<p>There's a number of ways to configure HTTPConduits for proxies and WebClients.</p>

<p>It is possible to have an HTTPConduit configuration which will apply to all clients using different request URIs or only to those with using a specific URI. For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;http:conduit name=<span class="code-quote">"http://books:9095/bookstore.*"</span>/&gt;</span> 
</pre>
</div></div>

<p>This configuration will affect all proxies and WebClients which have requestURIs starting from 'http://books:9095/bookstore'. Note the trailing '.*' suffix in the name of the http:conduit element.</p>

<p>Please see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/security/jaxrs-https-url.xml" rel="nofollow">this configuration file</a> for more examples.</p>

<p>Alternatively you can just do :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;http:conduit name=<span class="code-quote">"*.http-conduit"</span>/&gt;</span> 
</pre>
</div></div>

<p>This configuration will affect all the clients, irrespectively of which URIs the deal with.</p>

<p>If you work with proxies then you can have the proxy-specific configuration using the expanded QName notation:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;http:conduit name=<span class="code-quote">"{http://foo.bar}BookService.http-conduit"</span>/&gt;</span> 
</pre>
</div></div>

<p>In this example, 'foo.bar' is a reverse package name of the BookService proxy class.</p>

<p>Similarly, for WebClients you can do :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;http:conduit name=<span class="code-quote">"{http://localhost:8080}WebClient.http-conduit"</span>/&gt;</span> 
</pre>
</div></div>

<p>In this example, 'http://localhost:8080' is the base service URI.</p>

<p>Please see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/security/jaxrs-https.xml" rel="nofollow">this configuration file</a> for more examples.</p>

<p>Also see <a href="http://cwiki.apache.org/CXF20DOC/client-http-transport-including-ssl-support.html" rel="nofollow">this wiki page</a> on how to configure HTTPConduits.</p>

<h1><a name="JAX-RS-XPathandXSLT"></a>XPath and XSLT</h1>

<p>XPath and XSLT are promoted and treated as first-class citizens in CXF JAX-RS. These technologies can be very powerful when generating complex data or retrieving data of interest out of complex XML fragments.</p>

<h2><a name="JAX-RS-XPathsupport"></a>XPath support</h2>

<p>XPath is supported on the server and client sides with the help of <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/xml/XMLSource.java" rel="nofollow">XMLSource</a> utility class. Please see above how http-centric WebClients can use XPath, here is an example for the server side :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/root"</span>)
<span class="code-keyword">public</span> class Root {
   @POST
   <span class="code-keyword">public</span> void post(XMLSource source) {
       <span class="code-object">String</span> value = source.getProperty(<span class="code-quote">"/books/book/@name"</span>);
   }    
}
</pre>
</div></div> 

<p>Users have an option to hide XPath expressions, by registering an <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/XPathProvider.java" rel="nofollow">XPathProvider</a>, either on client or server sides. For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
XPathProvider provider = <span class="code-keyword">new</span> XPathProvider();
provider.setGlobalExpression(<span class="code-quote">"/books/book[position() = 1]"</span>);
WebClient wc = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//aggregated/data"</span>, Collections.singletonList(provider));
</span>Book b = wc.get(Book.class);
</pre>
</div></div>

<h2><a name="JAX-RS-XSLTsupport"></a>XSLT support</h2>

<p>XSLT is currently supported by <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/XSLTJaxbProvider.java" rel="nofollow">XSLTJaxbProvider</a>. This provider works in tandem with JAXB and can be used to produce pretty much any format, including non-XML ones. Likewise, it can be used to extract XML data out of incoming XML fragments, either on the client or server sides.</p>

<p>XSLTJaxbProvider can be configured to handle input or output data, scoped by media types if needed. For example, one may configure it such that one template handles "application/xml" formats only while the other one handles "application/json" writes only.</p>

<p>XSLTJaxbProvider uses an injected JAX-RS UriInfo to inject all the usual JAX-RS information like template or query parameters into a given XSLT template.</p>

<p>For example, given this resource method definition :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/root"</span>)
<span class="code-keyword">public</span> class Root {
   @GET
   @Path(<span class="code-quote">"{id}"</span>) 
   <span class="code-keyword">public</span> Book get(@PathParam(<span class="code-quote">"id"</span>) <span class="code-object">String</span> id, @QueryParam(<span class="code-quote">"name"</span>) <span class="code-object">String</span> name) {
       <span class="code-keyword">return</span> getBook(id, name);
   }    
}
</pre>
</div></div>

<p>an XSLT template processing the JAXB-driven serialization of a Book instance will have parameters with name 'id' and 'name' injected.</p>

<p>Note that when XSLTJaxbProvider is used on the client side, it may not always be possible for template parameters be injected in cases when http-centric clients are used (as opposed to proxies). For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
WebClient client = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>);
</span>client.path(<span class="code-quote">"/store/1"</span>).get();
</pre>
</div></div>

<p>it is not possible to deduce that '1' represents a template parameter in the "/store/1" expression. However, one can use the following code instead if '1' needs to be available to XSLT templates :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
WebClient client = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>);
</span>client.path(<span class="code-quote">"/store/{id}"</span>, 1).get();
</pre>
</div></div>


<h1><a name="JAX-RS-ModelViewControllersupport"></a>Model-View-Controller support</h1>

<p>Please see <a href="http://sberyozkin.blogspot.com/2009/05/mvc-xml-way-with-cxf-jax-rs.html" rel="nofollow">this blog entry</a> on how XSLTJaxbProvider can be used to generate complex (X)HTML views.</p>

<p>JSP may be eventually supported too</p>

<h1><a name="JAX-RS-SupportforMultiparts"></a>Support for Multiparts</h1>

<p>Multiparts can be handled in a number of ways. CXF core runtimes provides an advanced support for handling attachments and CXF JAX-RS builds upon it.</p>

<h2><a name="JAX-RS-Readingattachments"></a>Reading attachments</h2>

<p>Individual parts can be mapped to StreamSource, InputStream, DataSource or custom Java types for which message body readers are available.</p>

<p>For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@POST
@Path(<span class="code-quote">"/books/jaxbjson"</span>)
@Produces(<span class="code-quote">"text/xml"</span>)
<span class="code-keyword">public</span> Response addBookJaxbJson(
        @Multipart(value = <span class="code-quote">"rootPart"</span>, type = <span class="code-quote">"text/xml"</span>) Book2 b1,
        @Multipart(value = <span class="code-quote">"book2"</span>, type = <span class="code-quote">"application/json"</span>) Book b2) 
        <span class="code-keyword">throws</span> Exception {
}
</pre>
</div></div>

<p>Note that in this example it's expected that the root part named 'rootPart' is a text-xml Book representation, while a part named<br/>
'book2' is a Book JSON sequence.</p>

<p>All atachment parts can be accessed as a list of <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/Attachment.java" rel="nofollow">Attachment</a> with Attachment making it easy to deal with a given part :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@POST
<span class="code-keyword">public</span> void addAttachments(List&lt;Attachment&gt; atts) <span class="code-keyword">throws</span> Exception {
}
</pre>
</div></div>

<p>For example, Attachment class can be used to get to a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/ContentDisposition.java" rel="nofollow">Content-Disposition</a> header, when dealing with the form submission of files.</p>

<p>Similarly, the whole request body can be represented as a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/MultipartBody.java" rel="nofollow">MultipartBody</a> :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@POST
<span class="code-keyword">public</span> void addAttachments(MultipartBody body) <span class="code-keyword">throws</span> Exception {
body.getAllAtachments();
body.getRootAttachment();
}
</pre>
</div></div>

<p>When handling complex multipart/form-data submissions (such as those containing files) MultipartBody (and Attachment) need to be used directly. In simpler cases, when every form part can be captured by String, the following code will suffice :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@POST
@Consumes(<span class="code-quote">"multipart/form-data"</span>)
<span class="code-keyword">public</span> void addForm1(@FormParam(<span class="code-quote">"name"</span>) <span class="code-object">String</span> title, @FormParam(<span class="code-quote">"id"</span>) <span class="code-object">Long</span> id) <span class="code-keyword">throws</span> Exception {
}

@POST
@Consumes(<span class="code-quote">"multipart/form-data"</span>)
<span class="code-keyword">public</span> void addForm2(@FormParam("") BookBean book) <span class="code-keyword">throws</span> Exception {
}

@POST
@Consumes(<span class="code-quote">"multipart/form-data"</span>)
<span class="code-keyword">public</span> void addForm3(MultivaluedMap&lt;<span class="code-object">String</span>, <span class="code-object">String</span>&gt; formData) <span class="code-keyword">throws</span> Exception {
}
</pre>
</div></div>


<p>When a user code has <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/MessageContext.java" rel="nofollow">MessageContext</a> injected, <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/multipart/AttachmentUtils.java" rel="nofollow">AttachmentUtils</a> can also be used by the application code.</p>

<p>Please see these <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/MultipartStore.java" rel="nofollow">test resource class</a> and <a href="http://sberyozkin.blogspot.com/2009/02/multiparts-in-cxf-jaxrs.html" rel="nofollow">blog entry</a> for more examples.</p>

<h2><a name="JAX-RS-Writingattachments"></a>Writing attachments</h2>

<p>Starting from 2.2.4 and 2.3-SNAPSHOT it is also possible to write attachments to the output stream, both on the client and server sides.</p>

<p>On the server side it is sufficient to update the @Produces value for a given method :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class Resource {
   <span class="code-keyword">private</span> List&lt;Book&gt; books; 
   @Produces(<span class="code-quote">"multipart/mixed;type=text/xml"</span>)
   <span class="code-keyword">public</span> List&lt;Book&gt; getBooksAsMultipart() {
      <span class="code-keyword">return</span> booksList;
   }

   @Produces(<span class="code-quote">"multipart/mixed;type=text/xml"</span>)
   <span class="code-keyword">public</span> Book getBookAsMultipart() {
      <span class="code-keyword">return</span> booksList;
   }
}
</pre>
</div></div>

<p>Note that a 'type' parameter of the 'multipart/mixed' media type indicates that all parts in the multiparts response should have a Content-Type header set to 'text/xml' for both getBooksAsMultipart() and getBookAsMultipart() method responses. The getBooksAsMultipart() response will have 3 parts, the first part will have its Content-ID header set to "root.message@cxf.apache.org", the next parts will have '1' and '2' ids. The getBookAsMultipart() response will have a single part only with its Content-ID header set to "root.message@cxf.apache.org".</p>

<p>When returning mixed multiparts containing objects of different types, you can either return a Map with the media type string value to Object pairs or MultipartBody :  </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class Resource {
   <span class="code-keyword">private</span> List&lt;Book&gt; books; 
   @Produces(<span class="code-quote">"multipart/mixed"</span>)
   <span class="code-keyword">public</span> Map&lt;<span class="code-object">String</span>, <span class="code-object">Object</span>&gt; getBooks() {
      Map&lt;<span class="code-object">String</span>, <span class="code-object">Object</span>&gt; map = <span class="code-keyword">new</span> LinkedHashMap&lt;<span class="code-object">String</span>, <span class="code-object">Object</span>&gt;();
      map.put(<span class="code-quote">"text/xml"</span>, <span class="code-keyword">new</span> JaxbBook());
      map.put(<span class="code-quote">"application/json"</span>, <span class="code-keyword">new</span> JSONBook());
      map.put(<span class="code-quote">"application/octet-stream"</span>, imageInputStream);
      <span class="code-keyword">return</span> map;  
   } 

   @Produces(<span class="code-quote">"multipart/mixed"</span>)
   <span class="code-keyword">public</span> MultipartBody getBooks2() {
      List&lt;Attachment&gt; atts = <span class="code-keyword">new</span> LinkedList&lt;Attachment&gt;();
      atts.add(<span class="code-keyword">new</span> Attachment(<span class="code-quote">"root"</span>, <span class="code-quote">"application/json"</span>, <span class="code-keyword">new</span> JSONBook()));
      atts.add(<span class="code-keyword">new</span> Attachment(<span class="code-quote">"image"</span>, <span class="code-quote">"application/octet-stream"</span>, getImageInputStream()));
      <span class="code-keyword">return</span> <span class="code-keyword">new</span> MultipartBody(atts, <span class="code-keyword">true</span>);  
   }

}
</pre>
</div></div>

<p>Similarly to the method returning a list in a previous code fragment, getBooks() will have the response serialized as multiparts, where the first part will have its Content-ID header set to "root.message@cxf.apache.org", the next parts will have ids like '1', '2', etc . </p>

<p>In getBooks2() one can control the content ids of individual parts.</p>

<p>You can also control the contentId and the media type of the root attachment by using a Multipart annotation :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class Resource {
   @Produces(<span class="code-quote">"multipart/form-data"</span>)
   @Multipart(value = <span class="code-quote">"root"</span>, type = <span class="code-quote">"application/octet-stream"</span>) 
   <span class="code-keyword">public</span> File testGetImageFromForm() {
      <span class="code-keyword">return</span> getClass().getResource(<span class="code-quote">"image.png"</span>).getFile();
   }
}
</pre>
</div></div> 

<p>One can also have lists or maps of DataHandler, DataSource, Attachment, byte arrays or InputStreams handled as multiparts. </p>

<p>On the client side multiparts can be written the same way. For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

WebClient client = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>);
</span>client.type(<span class="code-quote">"multipart/mixed"</span>).accept(<span class="code-quote">"multipart/mixed"</span>);
List&lt;Attachment&gt; atts = <span class="code-keyword">new</span> LinkedList&lt;Attachment&gt;();
atts.add(<span class="code-keyword">new</span> Attachment(<span class="code-quote">"root"</span>, <span class="code-quote">"application/json"</span>, <span class="code-keyword">new</span> JSONBook()));
atts.add(<span class="code-keyword">new</span> Attachment(<span class="code-quote">"image"</span>, <span class="code-quote">"application/octet-stream"</span>, getImageInputStream()));
List&lt;Attachment&gt; atts = client.postAndGetCollection(atts, Attachment.class);
</pre>
</div></div>

<p>Note a new WebClient.postAndGetCollection which can be used for a type-safe retrieval of collections. A similar WebClient.getCollection has also been added.</p>

<p>When using proxies, a Multipart annotation attached to a method parameter can also be used to set the root contentId and media type. Proxies do not support at the moment multiple method parameters annotated with Multipart (as opposed to the server side) but only a single multipart parameter :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class Resource {
    @Produces(<span class="code-quote">"multipart/mixed"</span>)
    @Consumes(<span class="code-quote">"multipart/form-data"</span>)
    @Multipart(value = <span class="code-quote">"root"</span>, type = <span class="code-quote">"application/octet-stream"</span>) 
    <span class="code-keyword">public</span> File postGetFile(@Multipart(value = <span class="code-quote">"root2"</span>, type = <span class="code-quote">"application/octet-stream"</span>) File file) {}
}
</pre>
</div></div>

<p>A method-level Multipart annotation will affect the writing on the server side and the reading on the client side. A parameter-level Multipart annotation will affect writing on the client (proxy) side and reading on the server side. You don't have to use Multipart annotations.</p>

<h2><a name="JAX-RS-Uploadingfiles"></a>Uploading files</h2>

<p>At the moment the only way to upload a file is to use a MultipartBody, Attachment or File :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

WebClient client = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books"</span>);
</span>client.type(<span class="code-quote">"multipart/form-data"</span>);
ContentDisposition cd = <span class="code-keyword">new</span> ContentDisposition(<span class="code-quote">"attachment;filename=image.jpg"</span>);
Attachment att = <span class="code-keyword">new</span> Attachment(<span class="code-quote">"root"</span>, imageInputStream, cd);
client.post(<span class="code-keyword">new</span> MultipartBody(att));

<span class="code-comment">// or just post the attachment <span class="code-keyword">if</span> it's a single part request only
</span>client.post(att);

<span class="code-comment">// or just use a file
</span>client.post(getClass().getResource(<span class="code-quote">"image.png"</span>).getFile());

</pre>
</div></div>

<p>Using File provides a simpler way as the runtime can figure out how to create a ContentDisposition from a File.</p>


<h2><a name="JAX-RS-Readinglargeattachments"></a>Reading large attachments</h2>

<p>One can use the following properties to set up folder and threshold values when dealing with large attachments :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;beans&gt;</span>
  <span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"bookstore1"</span>&gt;</span>
     <span class="code-tag">&lt;jaxrs:properties&gt;</span>
         <span class="code-tag">&lt;entry key=<span class="code-quote">"attachment-directory"</span> value=<span class="code-quote">"/temp/bookstore1"</span>/&gt;</span>
         <span class="code-tag"><span class="code-comment">&lt;!-- 200K--&gt;</span></span>
         <span class="code-tag">&lt;entry key=<span class="code-quote">"attachment-memory-threshold"</span> value=<span class="code-quote">"404800"</span>/&gt;</span>
     <span class="code-tag">&lt;/jaxrs:properties&gt;</span>
  <span class="code-tag">&lt;/jaxrs:server&gt;</span>  
<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>

<p>Note that such properties can be set up on a per-endpoint basis.</p>

<p>Alternatively, you might want to set the following system properties which will apply to all endpoints :</p>

<p>&gt; -Dorg.apache.cxf.io.CachedOutputStream.Threshold=102400 <br/>
and<br/>
&gt; -Dorg.apache.cxf.io.CachedOutputStream.OutputDirectory=/temp</p>

<h1><a name="JAX-RS-ServicelistingsandWADLsupport"></a>Service listings and WADL support</h1>

<p>CXF JAX-RS now supports the auto-generation of WADL for JAX-RS endpoints. <br/>
Note that JAX-RS subresources are supposed to be late-resolved, so using annotated interfaces for subresources and a staticSubresourceResolution=true property will let the whole resource tree/graph be described in a generated instance. Schemas will be generated for JAXB-annotated types.</p>

<p>WADL instances for RESTful endpoints are available from {base endpointaddress}/services, in addition to SOAP endpoints if any. Note that you can override the location at which listings are provided (in case you would like '/services' be available to your resources) using<br/>
'service-list-path' servlet parameter, ex :</p>

<p>&gt; 'service-list-path' = '/listings'</p>

<p>Going to the service listings page is not the only way to see the wadl instances, generally one can get it using a ?_wadl query.</p>

<p>For example, given</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
Base address : 'http://localhost:8080'
WAR name : 'store'
CXFServlet : '/books/*'
jaxrs:server/@address = '/orders'
jaxrs:server/@staticSubresourceResoulution = 'true'
</pre>
</div></div>

<p>and 2 root resource classes registered with this endpoint, say</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/fiction"</span>) 
<span class="code-keyword">public</span> class FictionBookOrders {
}
@Path(<span class="code-quote">"/sport"</span>) 
<span class="code-keyword">public</span> class SportBookOrders {
}
</pre>
</div></div>

<p>then</p>

<p>&gt; <a href="http://localhost:8080/store/books/orders?_wadl" rel="nofollow">http://localhost:8080/store/books/orders?_wadl</a></p>

<p>will give you the description of all the root resource classes registered<br/>
with a given jaxrs:server endpoint, including all the subresources. While</p>

<p>&gt; <a href="http://localhost:8080/store/books/orders/fiction?_wadl" rel="nofollow">http://localhost:8080/store/books/orders/fiction?_wadl</a><br/>
&gt; <a href="http://localhost:8080/store/books/orders/sport?_wadl" rel="nofollow">http://localhost:8080/store/books/orders/sport?_wadl</a></p>

<p>will give you all the info for FictionBookOrders and SportBookOrders respectively.</p>

<p>If you have many jaxrs:endpoints then visiting</p>

<p>&gt; <a href="http://localhost:8080/store/books" rel="nofollow">http://localhost:8080/store/books</a> <br/>
&gt; <a href="http://localhost:8080/store/books/services" rel="nofollow">http://localhost:8080/store/books/services</a> </p>

<p>will let you see all the WADL links.</p>

<p>Note that the media type for a ?_wadl response is set to 'application/vnd.sun.wadl+xml' which is something Firefox does not really<br/>
like unless some wadl plugin is registered. If an HTTP Accept header is set to 'application/xml' then Firefox will show it with no problems. Doing<br/>
'?_wadl&amp;_type=xml' will ensure a WADL generator will see Accept being set set to 'application/xml'.</p>

<h1><a name="JAX-RS-ConfiguringJAXRSservices"></a>Configuring JAX-RS services</h1>

<h2><a name="JAX-RS-ConfiguringJAXRSservicesprogrammaticallycancreateaJAXRSRESTfulservicebyusingJAXRSServerFactoryBean"></a>Configuring JAX-RS services programmatically can create a JAX-RS RESTful service by using <a href="http://svn.apache.org/viewvc/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/JAXRSServerFactoryBean.java?view=markup&amp;pathrev=HEAD" rel="nofollow">JAXRSServerFactoryBean</a> from the <em>cxf-rt-frontend-jaxrs</em> package: </h2>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
JAXRSServerFactoryBean sf = <span class="code-keyword">new</span> JAXRSServerFactoryBean();
sf.setResourceClasses(CustomerService.class);
sf.setAddress(<span class="code-quote">"http:<span class="code-comment">//localhost:9000/"</span>);
</span>sf.create();
</pre>
</div></div>
<p>A couple of things to note:</p>
<ul>
	<li>The JAXRSServerFactoryBean creates a Server inside CXF which starts listening for requests on the URL specified.</li>
	<li>By default, the JAX-RS runtime is responsible for the lifecycle of resource classes, default lifecycle is per-request. You can set the lifecycle to singleton by using following line:
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
sf.setResourceProvider(BookStore.class, <span class="code-keyword">new</span> SingletonResourceProvider(<span class="code-keyword">new</span> BookStore()));
</pre>
</div></div></li>
	<li>If you prefer not to let the JAX-RS runtime to handle the resource class lifecycle for you (for example, it might be the case that your resource class is created by other containers such as Spring), you can do following:
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
JAXRSServerFactoryBean sf = <span class="code-keyword">new</span> JAXRSServerFactoryBean();
CustomerService cs = <span class="code-keyword">new</span> CustomerService();
sf.setServiceBeans(cs);
sf.setAddress(<span class="code-quote">"http:<span class="code-comment">//localhost:9080/"</span>);
</span>sf.create();
</pre>
</div></div></li>
</ul>



<h2><a name="JAX-RS-ConfiguringJAXRSendpointsprogrammaticallywithoutSpring"></a>Configuring JAX-RS endpoints programmatically without Spring</h2>

<p>Note that even though no Spring is explicitly used in the previous section, it is still used by default to have various CXF components registered with the bus such as transport factories. If no Spring libraries are available on the classpath then please follow the following example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
JAXRSServerFactoryBean sf = <span class="code-keyword">new</span> JAXRSServerFactoryBean();
sf.setResourceClasses(CustomerService.class);
sf.setResourceProvider(CustomerService.class, <span class="code-keyword">new</span> SingletonResourceProvider(<span class="code-keyword">new</span> CustomerService()));
sf.setAddress(<span class="code-quote">"http:<span class="code-comment">//localhost:9000/"</span>);
</span>BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class);
JAXRSBindingFactory factory = <span class="code-keyword">new</span> JAXRSBindingFactory();
factory.setBus(sf.getBus());
manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory);
sf.create();
</pre>
</div></div> 

<h2><a name="JAX-RS-ConfiguringJAXRSclientsprogrammaticallywithoutSpring"></a>Configuring JAX-RS clients programmatically without Spring</h2>

<p>Example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
JAXRSClientFactoryBean sf = <span class="code-keyword">new</span> JAXRSClientFactoryBean();
sf.setResourceClass(CustomerService.class);
sf.setAddress(<span class="code-quote">"http:<span class="code-comment">//localhost:9000/"</span>);
</span>BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class);
JAXRSBindingFactory factory = <span class="code-keyword">new</span> JAXRSBindingFactory();
factory.setBus(sf.getBus());
manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory);
CustomerService service = sf.create(CustomerService.class);
</pre>
</div></div> 


<h2><a name="JAX-RS-ConfiguringJAXRSservicesincontainerwithSpringconfigurationfile."></a>Configuring JAX-RS services in container with Spring configuration file.</h2>

<h3><a name="JAX-RS-web.xml"></a>web.xml</h3>

<p>In web.xml one needs to register one or more CXFServlet(s) and link to an application context configuration.</p>

<h4><a name="JAX-RS-UsingSpringContextLoaderListener"></a>Using Spring ContextLoaderListener</h4>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span> encoding=<span class="code-quote">"ISO-8859-1"</span>?&gt;</span>

&lt;!DOCTYPE web-app
    PUBLIC <span class="code-quote">"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"</span>
    <span class="code-quote">"http://java.sun.com/dtd/web-app_2_3.dtd"</span>&gt;
<span class="code-tag">&lt;web-app&gt;</span>
	<span class="code-tag">&lt;context-param&gt;</span>
		<span class="code-tag">&lt;param-name&gt;</span>contextConfigLocation<span class="code-tag">&lt;/param-name&gt;</span>
		<span class="code-tag">&lt;param-value&gt;</span>WEB-INF/beans.xml<span class="code-tag">&lt;/param-value&gt;</span>
	<span class="code-tag">&lt;/context-param&gt;</span>

	<span class="code-tag">&lt;listener&gt;</span>
		<span class="code-tag">&lt;listener-class&gt;</span>
			org.springframework.web.context.ContextLoaderListener
		<span class="code-tag">&lt;/listener-class&gt;</span>
	<span class="code-tag">&lt;/listener&gt;</span>

	<span class="code-tag">&lt;servlet&gt;</span>
		<span class="code-tag">&lt;servlet-name&gt;</span>CXFServlet<span class="code-tag">&lt;/servlet-name&gt;</span>
		<span class="code-tag">&lt;display-name&gt;</span>CXF Servlet<span class="code-tag">&lt;/display-name&gt;</span>
		<span class="code-tag">&lt;servlet-class&gt;</span>
			org.apache.cxf.transport.servlet.CXFServlet
		<span class="code-tag">&lt;/servlet-class&gt;</span>
		<span class="code-tag">&lt;load-on-startup&gt;</span>1<span class="code-tag">&lt;/load-on-startup&gt;</span>
	<span class="code-tag">&lt;/servlet&gt;</span>

	<span class="code-tag">&lt;servlet-mapping&gt;</span>
		<span class="code-tag">&lt;servlet-name&gt;</span>CXFServlet<span class="code-tag">&lt;/servlet-name&gt;</span>
		<span class="code-tag">&lt;url-pattern&gt;</span>/*<span class="code-tag">&lt;/url-pattern&gt;</span>
	<span class="code-tag">&lt;/servlet-mapping&gt;</span>
<span class="code-tag">&lt;/web-app&gt;</span>
</pre>
</div></div>

<p>The application context configuration is shared between all the CXFServlets</p>

<h4><a name="JAX-RS-UsingCXFServletinitparameters"></a>Using CXFServlet init parameters </h4>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span> encoding=<span class="code-quote">"ISO-8859-1"</span>?&gt;</span>

&lt;!DOCTYPE web-app
    PUBLIC <span class="code-quote">"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"</span>
    <span class="code-quote">"http://java.sun.com/dtd/web-app_2_3.dtd"</span>&gt;
<span class="code-tag">&lt;web-app&gt;</span>
	<span class="code-tag">&lt;servlet&gt;</span>
		<span class="code-tag">&lt;servlet-name&gt;</span>CXFServlet1<span class="code-tag">&lt;/servlet-name&gt;</span>
		<span class="code-tag">&lt;display-name&gt;</span>CXF Servlet1<span class="code-tag">&lt;/display-name&gt;</span>
		<span class="code-tag">&lt;servlet-class&gt;</span>
			org.apache.cxf.transport.servlet.CXFServlet
		<span class="code-tag">&lt;/servlet-class&gt;</span>
                <span class="code-tag">&lt;init-param&gt;</span>
                   <span class="code-tag">&lt;param-name&gt;</span>config-location<span class="code-tag">&lt;/param-name&gt;</span>
                   <span class="code-tag">&lt;param-value&gt;</span>/WEB-INF/beans1.xml<span class="code-tag">&lt;/param-value&gt;</span>
                <span class="code-tag">&lt;/init-param&gt;</span>
		<span class="code-tag">&lt;load-on-startup&gt;</span>1<span class="code-tag">&lt;/load-on-startup&gt;</span>
	<span class="code-tag">&lt;/servlet&gt;</span>

        <span class="code-tag">&lt;servlet&gt;</span>
		<span class="code-tag">&lt;servlet-name&gt;</span>CXFServlet2<span class="code-tag">&lt;/servlet-name&gt;</span>
		<span class="code-tag">&lt;display-name&gt;</span>CXF Servlet2<span class="code-tag">&lt;/display-name&gt;</span>
		<span class="code-tag">&lt;servlet-class&gt;</span>
			org.apache.cxf.transport.servlet.CXFServlet
		<span class="code-tag">&lt;/servlet-class&gt;</span>
                <span class="code-tag">&lt;init-param&gt;</span>
                   <span class="code-tag">&lt;param-name&gt;</span>config-location<span class="code-tag">&lt;/param-name&gt;</span>
                   <span class="code-tag">&lt;param-value&gt;</span>/WEB-INF/beans2.xml<span class="code-tag">&lt;/param-value&gt;</span>
                <span class="code-tag">&lt;/init-param&gt;</span>
		<span class="code-tag">&lt;load-on-startup&gt;</span>1<span class="code-tag">&lt;/load-on-startup&gt;</span>
	<span class="code-tag">&lt;/servlet&gt;</span>


	<span class="code-tag">&lt;servlet-mapping&gt;</span>
		<span class="code-tag">&lt;servlet-name&gt;</span>CXFServlet1<span class="code-tag">&lt;/servlet-name&gt;</span>
		<span class="code-tag">&lt;url-pattern&gt;</span>/1/*<span class="code-tag">&lt;/url-pattern&gt;</span>
	<span class="code-tag">&lt;/servlet-mapping&gt;</span>

        <span class="code-tag">&lt;servlet-mapping&gt;</span>
		<span class="code-tag">&lt;servlet-name&gt;</span>CXFServlet2<span class="code-tag">&lt;/servlet-name&gt;</span>
		<span class="code-tag">&lt;url-pattern&gt;</span>/2/*<span class="code-tag">&lt;/url-pattern&gt;</span>
	<span class="code-tag">&lt;/servlet-mapping&gt;</span>
<span class="code-tag">&lt;/web-app&gt;</span>
</pre>
</div></div>

<p>Each CXFServlet can get a unique application context configuration. Note, no Spring ContextLoaderListener is registered in web.xml in this case.</p>

<h3><a name="JAX-RS-beans.xml"></a>beans.xml</h3>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span> encoding=<span class="code-quote">"UTF-8"</span>?&gt;</span>
&lt;beans xmlns=<span class="code-quote">"http://www.springframework.org/schema/beans"</span>
  <span class="code-keyword">xmlns:xsi</span>=<span class="code-quote">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="code-keyword">xmlns:jaxrs</span>=<span class="code-quote">"http://cxf.apache.org/jaxrs"</span>
  xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd"&gt;

  <span class="code-tag"><span class="code-comment">&lt;!-- do not use import statements if CXFServlet init parameters link to this beans.xml --&gt;</span></span> 

  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf.xml"</span> /&gt;</span>
  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"</span> /&gt;</span>
  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf-servlet.xml"</span> /&gt;</span>

  <span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService"</span> address=<span class="code-quote">"/service1"</span>&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"customerBean"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>
  <span class="code-tag">&lt;/jaxrs:server&gt;</span>

  <span class="code-tag">&lt;bean id=<span class="code-quote">"customerBean"</span> class=<span class="code-quote">"demo.jaxrs.server.CustomerService"</span> /&gt;</span>
<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>

<h2><a name="JAX-RS-ConfiguringJAXRSservicesincontainerwithoutSpring"></a>Configuring JAX-RS services in container without Spring</h2>

<p>If you prefer, you can register JAX-RS endpoints without depending on Spring with the help of CXFNonSpringJaxrsServlet :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;servlet&gt;</span>
 <span class="code-tag">&lt;servlet-name&gt;</span>CXFServlet<span class="code-tag">&lt;/servlet-name&gt;</span>
 <span class="code-tag">&lt;display-name&gt;</span>CXF Servlet<span class="code-tag">&lt;/display-name&gt;</span>
 <span class="code-tag">&lt;servlet-class&gt;</span>
   org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet
 <span class="code-tag">&lt;/servlet-class&gt;</span>
 <span class="code-tag">&lt;init-param&gt;</span>
  <span class="code-tag">&lt;param-name&gt;</span>jaxrs.serviceClasses<span class="code-tag">&lt;/param-name&gt;</span>
  <span class="code-tag">&lt;param-value&gt;</span>
    org.apache.cxf.systest.jaxrs.BookStore1
    org.apache.cxf.systest.jaxrs.BookStore2		      
  <span class="code-tag">&lt;/param-value&gt;</span>
 <span class="code-tag">&lt;/init-param&gt;</span>
 <span class="code-tag">&lt;init-param&gt;</span>
  <span class="code-tag">&lt;param-name&gt;</span>jaxrs.providers<span class="code-tag">&lt;/param-name&gt;</span>
  <span class="code-tag">&lt;param-value&gt;</span>
    org.apache.cxf.systest.jaxrs.BookStoreProvider1
    org.apache.cxf.systest.jaxrs.BookStoreProvider2		      
  <span class="code-tag">&lt;/param-value&gt;</span>
 <span class="code-tag">&lt;/init-param&gt;</span>
 <span class="code-tag"><span class="code-comment">&lt;!-- enables schema validation --&gt;</span></span>
 <span class="code-tag">&lt;init-param&gt;</span>
  <span class="code-tag">&lt;param-name&gt;</span>jaxrs.schemaLocations<span class="code-tag">&lt;/param-name&gt;</span>
  <span class="code-tag">&lt;param-value&gt;</span>
    classpath:/WEB-INF/schemas/schema1.xsd
    classpath:/WEB-INF/schemas/schema2.xsd		      
  <span class="code-tag">&lt;/param-value&gt;</span>
 <span class="code-tag">&lt;/init-param&gt;</span> 
 <span class="code-tag"><span class="code-comment">&lt;!-- registers CXF in interceptors --&gt;</span></span>
 <span class="code-tag">&lt;init-param&gt;</span>
  <span class="code-tag">&lt;param-name&gt;</span>jaxrs.inInterceptors<span class="code-tag">&lt;/param-name&gt;</span>
  <span class="code-tag">&lt;param-value&gt;</span>
    org.apache.cxf.systest.jaxrs.CustomInInterceptor
  <span class="code-tag">&lt;/param-value&gt;</span>
 <span class="code-tag">&lt;/init-param&gt;</span> 
 <span class="code-tag"><span class="code-comment">&lt;!-- registers CXF out interceptors --&gt;</span></span>
 <span class="code-tag">&lt;init-param&gt;</span>
  <span class="code-tag">&lt;param-name&gt;</span>jaxrs.outInterceptors<span class="code-tag">&lt;/param-name&gt;</span>
  <span class="code-tag">&lt;param-value&gt;</span>
    org.apache.cxf.systest.jaxrs.CustomOutInterceptor
  <span class="code-tag">&lt;/param-value&gt;</span>
 <span class="code-tag">&lt;/init-param&gt;</span>
<span class="code-tag">&lt;load-on-startup&gt;</span>1<span class="code-tag">&lt;/load-on-startup&gt;</span>
<span class="code-tag">&lt;/servlet&gt;</span>
</pre>
</div></div>

<p>When service classes and providers are registered this way, the default life-cycle is 'singleton'. You can override it by setting a "jaxrs.scope" parameter with the value of 'prototype' (equivalent to per-request). <br/>
By default, the endpoint address is "/". One can provide a more specific value using a "jaxrs.address" parameter.</p>


<p>A more portable way to register resource classes and providers with CXFNonSpringJaxrsServlet is to use a JAX-RS Application <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookApplication.java" rel="nofollow">implementation</a> :</p>


<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;servlet&gt;</span>
 <span class="code-tag">&lt;servlet-name&gt;</span>CXFServlet<span class="code-tag">&lt;/servlet-name&gt;</span>
 <span class="code-tag">&lt;display-name&gt;</span>CXF Servlet<span class="code-tag">&lt;/display-name&gt;</span>
 <span class="code-tag">&lt;servlet-class&gt;</span>
   org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet
 <span class="code-tag">&lt;/servlet-class&gt;</span>
 <span class="code-tag">&lt;init-param&gt;</span>
  <span class="code-tag">&lt;param-name&gt;</span>javax.ws.rs.Application<span class="code-tag">&lt;/param-name&gt;</span>
  <span class="code-tag">&lt;param-value&gt;</span>
    org.apache.cxf.systest.jaxrs.BookApplication	      
  <span class="code-tag">&lt;/param-value&gt;</span>
 <span class="code-tag">&lt;/init-param&gt;</span>
<span class="code-tag">&lt;load-on-startup&gt;</span>1<span class="code-tag">&lt;/load-on-startup&gt;</span>
<span class="code-tag">&lt;/servlet&gt;</span>
</pre>
</div></div>

<p>Note that Application.getClasses() method returns a set of per-request resource class names. Application.getSingletons() returns a list of singleton resource and provider classes. </p>


<h3><a name="JAX-RS-AttachingJAXRSendpointstoanexistingJettyserver"></a>Attaching JAXRS endpoints to an existing Jetty server</h3>

<p>Here is a code fragment showing how it can be done with the help of CxfNonSpringJaxrsServlet :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
CXFNonSpringServlet cxf = <span class="code-keyword">new</span> CXFNonSpringJaxrsServlet();

...

ServletHolder servlet = <span class="code-keyword">new</span> ServletHolder(cxf);
servlet.setInitParameter(<span class="code-quote">"javax.ws.rs.Application"</span>, <span class="code-quote">"com.acme.MyServiceImpl"</span>);
servlet.setName(<span class="code-quote">"services"</span>);
servlet.setForcedPath(<span class="code-quote">"services"</span>);
root.addServlet(servlet, <span class="code-quote">"/*"</span>);

</pre>
</div></div>

<h2><a name="JAX-RS-ConfiguringJAXRSservicesprogrammaticallywithSpringconfigurationfile."></a>Configuring JAX-RS services programmatically with Spring configuration file. </h2>

<p>When using Spring explicitly in your code, you may want to follow this example :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
ClassPathXmlApplicationContext ctx = <span class="code-keyword">new</span> ClassPathXmlApplicationContext(<span class="code-keyword">new</span> <span class="code-object">String</span>[]
                      {<span class="code-quote">"/org/apache/cxf/jaxrs/spring/servers.xml"</span>});

<span class="code-comment">// 'simple' is the id of the jaxrs server bean
</span>JAXRSServerFactoryBean sfb = (JAXRSServerFactoryBean)ctx.getBean(<span class="code-quote">"simple"</span>);
sfb.create();
</pre>
</div></div>

<p>Note that in in this case your Spring configuration file should import cxf-extension-http-jetty.xml instead of cxf-servlet.xml :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
&lt;!--
<span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf-servlet.xml"</span> /&gt;</span>
--&gt;
<span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf-extension-http-jetty.xml"</span> /&gt;</span>
</pre>
</div></div>

<h2><a name="JAX-RS-Lifecyclemanagement"></a>Lifecycle management</h2>

<h3><a name="JAX-RS-FromSpring"></a>From Spring</h3>

<p>The singleton scope is applied to all service beans which are injected like this :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;beans&gt;</span>
  <span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService"</span> address=<span class="code-quote">"/service1"</span>&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"customerBean"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>
  <span class="code-tag">&lt;/jaxrs:server&gt;</span>
  <span class="code-tag">&lt;bean id=<span class="code-quote">"customerBean"</span> class=<span class="code-quote">"demo.jaxrs.server.CustomerService"</span> /&gt;</span>
<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>

<p>You can support prototypes by either using a beanNames attribute or schemaFactories element :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;beans&gt;</span>
  &lt;jaxrs:server id=<span class="code-quote">"customerService"</span> address=<span class="code-quote">"/service1"</span>
    beanNames=<span class="code-quote">"customerBean2 customerBean3"</span>&gt;
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"customerBean"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceFactories&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"sfactory1"</span> /&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"sfactory2"</span> /&gt;</span> 
    <span class="code-tag">&lt;/jaxrs:serviceFactories&gt;</span>
  <span class="code-tag">&lt;/jaxrs:server&gt;</span>
  <span class="code-tag">&lt;bean id=<span class="code-quote">"customerBean"</span> class=<span class="code-quote">"demo.jaxrs.server.CustomerService"</span> /&gt;</span>
  <span class="code-tag">&lt;bean id=<span class="code-quote">"customerBean2"</span> class=<span class="code-quote">"demo.jaxrs.server.CustomerService2"</span>  scope=<span class="code-quote">"prototype"</span>/&gt;</span>
  <span class="code-tag">&lt;bean id=<span class="code-quote">"customerBean3"</span> class=<span class="code-quote">"demo.jaxrs.server.CustomerService3"</span>  scope=<span class="code-quote">"prototype"</span>/&gt;</span> 

  <span class="code-tag">&lt;bean id=<span class="code-quote">"sfactory1"</span> class=<span class="code-quote">"org.apache.cxf.jaxrs.spring.SpringResourceFactory"</span>&gt;</span>
     <span class="code-tag">&lt;property name=<span class="code-quote">"beanName"</span> value=<span class="code-quote">"customerBean4"</span>/&gt;</span>
  <span class="code-tag">&lt;/bean&gt;</span>
  <span class="code-tag">&lt;bean id=<span class="code-quote">"sfactory2"</span> class=<span class="code-quote">"org.apache.cxf.jaxrs.spring.SpringResourceFactory"</span>&gt;</span>
     <span class="code-tag">&lt;property name=<span class="code-quote">"beanName"</span> value=<span class="code-quote">"customerBean5"</span>/&gt;</span>
  <span class="code-tag">&lt;/bean&gt;</span>

  <span class="code-tag">&lt;bean id=<span class="code-quote">"customerBean4"</span> class=<span class="code-quote">"demo.jaxrs.server.CustomerService4"</span> scope=<span class="code-quote">"prototype"</span>/&gt;</span> 
  <span class="code-tag">&lt;bean id=<span class="code-quote">"customerBean5"</span> class=<span class="code-quote">"demo.jaxrs.server.CustomerService5"</span>  scope=<span class="code-quote">"prototype"</span>/&gt;</span> 
<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>


<h3><a name="JAX-RS-WithCXFNonSpringJaxrsServlet"></a>With CXFNonSpringJaxrsServlet</h3>

<p>CXFNonSpringJaxrsServlet uses 'Singleton' as a default scope for service classes specified by a "jaxrs.serviceClasses" servlet parameter. It can be overridden by setting a "jaxrs.scope" parameter to a "prototype" value or by not using the "jaxrs.serviceClasses" parameter at all and registering a JAXRS Application implementation instead. Please see the section describing CXFNonSpringJaxrsServlet for more details.</p>

<p>CXFNonSpringJaxrsServlet can support singleton scopes for classes with constructors expecting JAXRS contexts, at the moment it can only inject ServletContext or ServletConfig contexts :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/"</span>)
<span class="code-keyword">public</span> class SingletonResourceClass {
   <span class="code-keyword">public</span> SingletonResourceClass(@Context ServletContext context, @Context ServletConfig context2) {}
}
</pre>
</div></div> 

<h3><a name="JAX-RS-Programmatically"></a>Programmatically</h3>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
JAXRSServerFactoryBean sf = <span class="code-keyword">new</span> JAXRSServerFactoryBean();
sf.setResourceClass(CustomerService.class);
sf.setResourceProvider(<span class="code-keyword">new</span> SingletonResourceProvider(<span class="code-keyword">new</span> CustomerService()));
sf.setResourceClass(CustomerService2.class);
sf.setResourceProvider(<span class="code-keyword">new</span> PerRequestResourceProvider(CustomerService.class));
</pre>
</div></div>

<h3><a name="JAX-RS-PostConstructandPreDestroy"></a>PostConstruct and PreDestroy</h3>

<p>Bean methods annotated with @PostConstruct and @PreDestroy annotations will be called as expected by the scope rules. <br/>
Singleton beans will have their postconstruct method called when the endpoint is created. If a given singleton resource instance was created by Spring then its predestroy method will also be called after, for example, the web application which uses it is about to be unloaded. At the moment singletons created by CXFNonSpringJaxrsServlet or programmatically will only have their postconstruct method (if any) called.  </p>

<p>Prototype beans will have their postconstruct and predestroy method called before a resource method is invoked and immediately after the invocation has returned but before the response has actually been serialized. You can indicate that the predestroy method has to be called after the request has completely gone out of scope (that is after the response body if any has been written to the output stream) by adding an "org.apache.cxf.jaxrs.service.scope" property with the value set to "request".</p>

<p>You can also register a custom Spring resource factory by extending org.apache.cxf.jaxrs.spring.SpringResourceFactory or providing a more sophisticated implementation.</p>

<h2><a name="JAX-RS-Locatingcustomresourcesinwebapplications"></a>Locating custom resources in web applications</h2>

<p>Resources like schemas, custom XSLT templates and user models are typically referenced using a classpath: prefix. Thus one can add them to a WEB-INF/classes folder in a given web application.<br/>
Since CXF 2.2.3 one can put them directly under WEB-INF, for example into WEB-INF/xslt,  WEB-INF/schemas, WEB-INF/model and referencing them like 'classpath:/WEB-INF/xslt/template.xsl'.</p>

<h2><a name="JAX-RS-Multipleendpointsandresourceclasses"></a>Multiple endpoints and resource classes</h2>

<p>One can configure as many jaxrs:server endpoints as needed for a given application, with every endpoint possibly providing an alternative path to a single resource bean. Every endpoint can employ as many shared or unique resource classes as needed, and have common or different providers.  </p>

<h2><a name="JAX-RS-HowtherequestURIismatchedagainstagivenjaxrsendpoint"></a>How the request URI is matched against a given jaxrs endpoint</h2>

<p>There's a number of variables involved here. </p>

<p>Lets assume you have a web application called 'rest'. CXFServlet's url-pattern is "/test/*". Finally, jaxrs:server's address is "/bar".</p>

<p>Requests like /rest/test/bar or /rest/test/bar/baz will be delivered to one of the resource classes in a given jaxrs:server endpoint. For the former request be handled, a resource class with &#64;Path("/") should be available, in the latter case - at least &#64;Path("/") or more specific @Path("/baz").</p>

<p>The same requirement can be expressed by having a CXFServlet with "/*" and jaxrs:server with "/test/bar". </p>

<p>When both CXFServlet and jaxrs:server use "/" then it's a root resource class which should provide a &#64;Path with at least "/test/bar" for the above requests be matched. </p>

<p>Generally, it can be a good idea to specify the URI segments which are more likely to change now and then with CXFServlets or jaxrs:server. </p>

<h2><a name="JAX-RS-CombiningJAXWSandJAXRS"></a>Combining JAX-WS and JAX-RS</h2>

<p>Here's a beans.xml showing how to have a single service class supporting both SOAP and REST-based invocations at the same time with the help of JAX-WS and JAX-RS : </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span> encoding=<span class="code-quote">"UTF-8"</span>?&gt;</span>
&lt;beans xmlns=<span class="code-quote">"http://www.springframework.org/schema/beans"</span>
  <span class="code-keyword">xmlns:xsi</span>=<span class="code-quote">"http://www.w3.org/2001/XMLSchema-instance"</span>
  <span class="code-keyword">xmlns:jaxrs</span>=<span class="code-quote">"http://cxf.apache.org/jaxrs"</span>
  <span class="code-keyword">xmlns:jaxws</span>=<span class="code-quote">"http://cxf.apache.org/jaxws"</span>
  xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd"&gt;

  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf.xml"</span> /&gt;</span>
  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"</span> /&gt;</span>
  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf-servlet.xml"</span> /&gt;</span>

  <span class="code-tag"><span class="code-comment">&lt;!-- JAX-RS --&gt;</span></span>
  <span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"customerService"</span> address=<span class="code-quote">"/"</span>&gt;</span>
    <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
      <span class="code-tag">&lt;ref bean=<span class="code-quote">"customerService"</span> /&gt;</span>
    <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>
  <span class="code-tag">&lt;/jaxrs:server&gt;</span>

  <span class="code-tag"><span class="code-comment">&lt;!-- JAX-WS --&gt;</span></span>
  &lt;jaxws:endpoint implementor=<span class="code-quote">"#customerService"</span>
    address=<span class="code-quote">"/CustomerWorld"</span> wsdlLocation=<span class="code-quote">"..."</span>/&gt;
  
  <span class="code-tag">&lt;bean id=<span class="code-quote">"customerService"</span> class=<span class="code-quote">"demo.jaxrs.server.CustomerService"</span> /&gt;</span>
<span class="code-tag">&lt;/beans&gt;</span>
</pre>
</div></div>

<p>Either contract-first or Java-first approach can be used for JAX-WS. JAX-RS annotations can be added to the existing service class. Some custom providers may need to be created, depending on the complexity of the method signatures.</p>

<p>When a WSDL-first approach is used then a document-literal-wrapped style may or may not be a good fit as the code generator unwraps all the types into a signature, for example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class CustomerService {
   <span class="code-keyword">public</span> void doIt(<span class="code-object">String</span> a, <span class="code-object">String</span> b) {...};
}
</pre>
</div></div>  

<p>By default JAX-RS may not be able to handle such methods as it requires that only a single parameter can be available in a signature that is not annotated by one of the JAX-RS annotations like @PathParam. So if <br/>
a 'String a' parameter can be mapped to a @Path template variable or one of the query segments then this signature won't need to be changed :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customers/{a}"</span>)
<span class="code-keyword">public</span> class CustomerService {
   <span class="code-keyword">public</span> void doIt(@PathParam(<span class="code-quote">"a"</span>) <span class="code-object">String</span> a, <span class="code-object">String</span> b) {...};
}
</pre>
</div></div>  

<p>Note that CXF Continuations API is supported for both JAXWS and JAXRS services.</p>

<h3><a name="JAX-RS-Dealingwithcontexts"></a>Dealing with contexts</h3>

<p>When combining JAXWS and JAXRS, one may need to access some context information as part of processing a given request. At the moment, CXF JAXRS does not offer a context implementation which can be used to access a request-specific information common for both JAXWS and JAXRS requests, in cases when the same methods are used to handle both JAXWS and JAXRS requests. Please use a JAXWS WebServiceContext and JAXRS contexts or CXF JAXRS composite MessageContext :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customers"</span>)
@WebService
<span class="code-keyword">public</span> class CustomerService {

   @Resource WebServiceContext jaxwsContext;
   @Resource MessageContext jaxrsContext;

   @WebMethod
   @POST
   <span class="code-keyword">public</span> void doIt(<span class="code-object">String</span> b) {
       isUserInRole();
   };

   <span class="code-keyword">private</span> void isUserInRole() <span class="code-keyword">throws</span> WebApplicationException {
       <span class="code-keyword">if</span> (jaxwsContext.getSecurityContext() != <span class="code-keyword">null</span>) {
           <span class="code-comment">// soap invocation
</span>           jaxwsContext.getSecurityContext().isUserInRole(theRole);
       } <span class="code-keyword">else</span> {
           <span class="code-comment">// http-only jaxrs one
</span>           jaxrsContext.getSecurityContext().isUserInRole(theRole);
       }  
   }
}
</pre>
</div></div>  

<p>Note that injected context instances (jaxwsContext and jaxrsContext) are in fact thread-local proxies hence they will not be equal to null even if they do not represent a given request. For example, jaxrsContext will not be equal to null even if it's not a JAXWS invocation which is being processed at the moment.</p>

<p>However, if say a (JAXWS or JAXRS) SecurityContext needs to be accessed then it will be set in, say, jaxwsContext only if it's a JAXWS/SOAP invocation. For this reason it can be handy using a composite CXF JAXRS MessageContext when accessing a JAXRS-specific context information when combining JAXWS and JAXRS as one can easily check if it's actually a JAXRS request by simply checking an individual context like SecurityContext or UriInfo for null.</p>

<p>Using individual contexts like JAXRS SecurityContext might be less attractive :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@WebService
<span class="code-keyword">public</span> class CustomerService {
   @Resource WebServiceContext jaxwsContext;
   <span class="code-comment">// @Resource can be applied too
</span>   @Context SecurityContext jaxrsSecurityContext;  
}
</pre>
</div></div>

<p>as some methods of SecurityContext return boolean values so only throwing a runtime exception can reliably indicate that this context is actually not in scope.</p>

<p>Note that if you do not share the same service methods between JAXRS and JAXWS invocations then you can directly access corresponding contexts : </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"/customers"</span>)
@WebService
<span class="code-keyword">public</span> class CustomerService {

   @Resource WebServiceContext jaxwsContext;
   @Resource MessageContext jaxrsContext;

   @WebMethod
   <span class="code-keyword">public</span> void doItSoap(<span class="code-object">String</span> b) {
       isUserInRole(jaxwsContext.getSecurityContext().getPrincipal());
   };

   @POST
   <span class="code-keyword">public</span> void doItSoap(<span class="code-object">String</span> b) {
       isUserInRole(jaxwsContext.getSecurityContext().getPrincipal());
   }

   <span class="code-keyword">private</span> void isUserInRole(Principal p) <span class="code-keyword">throws</span> WebApplicationException {
       ...  
   }
}
</pre>
</div></div>

<p>Another option is to avoid the use of contexts in the service code and deal with them in CXF interceptors or JAXRS filters. Sometimes it's possible to avoid the use of contexts altogether. For example, Spring Security can be used to secure a given service at an individual method level.     </p>

<h2><a name="JAX-RS-JAXRSandSpringAOP"></a>JAX-RS and Spring AOP</h2>

<p>CXF JAX-RS is capable of working with AOP interceptors applied to resource classes from Spring.<br/>
For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">

&lt;beans xsi:schemaLocation=" http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop  
  http://www.springframework.org/schema/aop/spring-aop.xsd 
  http://cxf.apache.org/jaxrs 
  http://cxf.apache.org/schemas/jaxrs.xsd"&gt;
  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf.xml"</span>/&gt;</span>
  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"</span>/&gt;</span>
  <span class="code-tag">&lt;import resource=<span class="code-quote">"classpath:META-INF/cxf/cxf-servlet.xml"</span>/&gt;</span>

  <span class="code-tag">&lt;jaxrs:server id=<span class="code-quote">"bookservice"</span> address=<span class="code-quote">"/"</span>&gt;</span>
	<span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
          <span class="code-tag">&lt;ref bean=<span class="code-quote">"bookstore"</span>/&gt;</span>
          <span class="code-tag">&lt;ref bean=<span class="code-quote">"bookstoreInterface"</span>/&gt;</span>
        <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>
   <span class="code-tag">&lt;/jaxrs:server&gt;</span>
   <span class="code-tag">&lt;bean id=<span class="code-quote">"bookstore"</span> class=<span class="code-quote">"org.apache.cxf.systest.jaxrs.BookStore"</span>/&gt;</span>
   <span class="code-tag">&lt;bean id=<span class="code-quote">"bookstoreInterface"</span> class=<span class="code-quote">"org.apache.cxf.systest.jaxrs.BookStoreWithInterface"</span>/&gt;</span>

   <span class="code-tag">&lt;aop:config&gt;</span>
	<span class="code-tag">&lt;aop:aspect id=<span class="code-quote">"loggingAspect"</span> ref=<span class="code-quote">"simpleLogger"</span>&gt;</span>
          <span class="code-tag">&lt;aop:before method=<span class="code-quote">"logBefore"</span> pointcut=<span class="code-quote">"execution(* org.apache.cxf.systest.jaxrs.BookStore*.*(..))"</span>/&gt;</span>
          <span class="code-tag">&lt;aop:after-returning method=<span class="code-quote">"logAfter"</span> pointcut=<span class="code-quote">"execution(* org.apache.cxf.systest.jaxrs.BookStore*.*(..))"</span>/&gt;</span>
        <span class="code-tag">&lt;/aop:aspect&gt;</span>
   <span class="code-tag">&lt;/aop:config&gt;</span>
   <span class="code-tag">&lt;bean id=<span class="code-quote">"simpleLogger"</span> class=<span class="code-quote">"org.apache.cxf.systest.jaxrs.SimpleLoggingAspect"</span>/&gt;</span>
<span class="code-tag">&lt;/beans&gt;</span>

</pre>
</div></div> 

<p>Note that some AOP configuration is applied to two JAX-RS resource classes. By default Spring uses JDK dynamic proxies every time a class to be proxified implements at least one interface or CGLIB proxies otherwise. </p>

<p>For example, here's how org.apache.cxf.systest.jaxrs.BookStoreWithInterface looks like : </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

<span class="code-keyword">public</span> <span class="code-keyword">interface</span> BookInterface {
    @GET
    @Path(<span class="code-quote">"/thosebooks/{bookId}/"</span>)
    @Produces(<span class="code-quote">"application/xml"</span>)
    Book getThatBook(<span class="code-object">Long</span> id) <span class="code-keyword">throws</span> BookNotFoundFault;
}

<span class="code-keyword">public</span> class BookStoreWithInterface <span class="code-keyword">extends</span> BookStoreStorage <span class="code-keyword">implements</span> BookInterface {

    <span class="code-keyword">public</span> Book getThatBook(@PathParam(<span class="code-quote">"bookId"</span>) <span class="code-object">Long</span> id) <span class="code-keyword">throws</span> BookNotFoundFault {
        <span class="code-keyword">return</span> doGetBook(id);
    }

    @Path(<span class="code-quote">"/thebook"</span>)
    <span class="code-keyword">public</span> Book getTheBook(@PathParam(<span class="code-quote">"bookId"</span>) <span class="code-object">Long</span> id) <span class="code-keyword">throws</span> BookNotFoundFault {
        <span class="code-keyword">return</span> doGetBook(id);
    }
}
</pre>
</div></div>

<p>In this case Spring will use a JDK proxy to wrap a BookStoreWithInterface class. As such it is important that a method which needs to be invoked such as getThatBook(...) is part of the interface. </p>

<p>The other method, getTheBook() can not be dispatched to by a JAX-RS runtime as it's not possible to discover it through a JDK proxy. If this method also needs to be invoked then this method should either be added to the interface or CGLIB proxies have to be explicitly enabled (consult Spring AOP documentation for more details). For example :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;aop:config proxy-target-class=<span class="code-quote">"true"</span>/&gt;</span>
</pre>
</div></div>

<h1><a name="JAX-RS-RESTfulserviceswithoutannotations"></a>RESTful services without annotations </h1>

<p>One of the latest CXF JAX-RS extensions allows users to provide external models with the information which the runtime typically gets from JAX-RS annotations like @Path, @PathParam, @Consumes, @Produces, etc.<br/>
There might be a number of cases when it can be advantageous to describe how a given resource can be exposed as a RESTful service without actually modifying this resource. For example, when new dynamic interface implementations are registered, when no source code can be modified, when the cost of future updates (for ex, modifying the value of @Path annotations) is considered to be expensive, etc.</p>

<p>User model schema type is described in the <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/resources/schemas/jaxrs.xsd" rel="nofollow">jaxrs.xsd</a>. </p>

<p>The top-level 'model' element can have 'resource' children elements. A 'resource' element describes a resource class which can be either a root resource class or a sub-resource one and it can have attributes describing 'path', 'produces' and 'consumes' values and it has a 'name' attribute which identifies a fully-qualified resource class. <br/>
A 'resource' element can have a number of 'operation' elements pointing to resource methods (with its 'name' attribute) and can have 'path', 'produces', 'consumes' and 'verb' (HTTP method) values. An 'operation' element which has no 'verb' attribute is treated as a sub-resource locator - a corresponding resource class has to be available in the model with its 'name' attribute matching the return type's name of this operation.<br/>
Every operation can have a number of 'param' elements. A 'param' element should have its 'name' attribute matching a corresponding parameter name in the class resource method. Its 'type' can have the following values : 'PATH', 'QUERY', 'CONTEXT', 'HEADER', 'MATRIX', 'COOKIE', 'FORM' or 'REQUEST_BODY'. Parameters corresponding to response types do not have to be described. It can also have 'defaultValue' and 'encoded' values being set.</p>

<p>Here is an example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;model xmlns=<span class="code-quote">"http://cxf.apache.org/jaxrs"</span>&gt;</span>
  &lt;resource name=<span class="code-quote">"org.apache.cxf.systest.jaxrs.BookStoreNoAnnotations"</span> path=<span class="code-quote">"bookstore"</span>
    produces=<span class="code-quote">"application/json"</span> consumes=<span class="code-quote">"application/json"</span>&gt;
    <span class="code-tag">&lt;operation name=<span class="code-quote">"getBook"</span> verb=<span class="code-quote">"GET"</span> path=<span class="code-quote">"/books/{id}"</span> produces=<span class="code-quote">"application/xml"</span>&gt;</span>
       <span class="code-tag">&lt;param name=<span class="code-quote">"id"</span> type=<span class="code-quote">"PATH"</span>/&gt;</span>
    <span class="code-tag">&lt;/operation&gt;</span>
    <span class="code-tag">&lt;operation name=<span class="code-quote">"getBookChapter"</span> path=<span class="code-quote">"/books/{id}/chapter"</span>&gt;</span>
       <span class="code-tag">&lt;param name=<span class="code-quote">"id"</span> type=<span class="code-quote">"PATH"</span>/&gt;</span>
    <span class="code-tag">&lt;/operation&gt;</span>
    <span class="code-tag">&lt;operation name=<span class="code-quote">"updateBook"</span> verb=<span class="code-quote">"PUT"</span>&gt;</span>
       <span class="code-tag">&lt;param name=<span class="code-quote">"book"</span> type=<span class="code-quote">"REQUEST_BODY"</span>/&gt;</span>
    <span class="code-tag">&lt;/operation&gt;</span>
  <span class="code-tag">&lt;/resource&gt;</span>
  <span class="code-tag">&lt;resource name=<span class="code-quote">"org.apache.cxf.systest.jaxrs.ChapterNoAnnotations"</span>&gt;</span>
    <span class="code-tag">&lt;operation name=<span class="code-quote">"getItself"</span> verb=<span class="code-quote">"GET"</span>/&gt;</span>
    <span class="code-tag">&lt;operation name=<span class="code-quote">"updateChapter"</span> verb=<span class="code-quote">"PUT"</span> consumes=<span class="code-quote">"application/xml"</span>&gt;</span>
        <span class="code-tag">&lt;param name=<span class="code-quote">"content"</span> type=<span class="code-quote">"REQUEST_BODY"</span>/&gt;</span>
    <span class="code-tag">&lt;/operation&gt;</span>
  <span class="code-tag">&lt;/resource&gt;</span>
<span class="code-tag">&lt;/model&gt;</span>
</pre>
</div></div>

<p>This model describes two resources, BookStoreNoAnnotations and ChapterNoAnnotations. The BookStoreNoAnnotations resource has three resource operations, 'getBook', 'getBookChapter' and 'updateBook'. Note that the 'getBookChapter' operation element (described in the model) has no 'verb' attribute so runtime will identify it as a subresource locator.<br/>
The runtime will introspect the <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookStoreNoAnnotations.java" rel="nofollow">org.apache.cxf.systest.jaxrs.BookStoreNoAnnotations</a> class and check the return types for both 'getBook' and 'getBookChapter' methods.  BookStoreNoAnnotations.getBookChapter() method's return type is <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/ChapterNoAnnotations.java" rel="nofollow">org.apache.cxf.systest.jaxrs.ChapterNoAnnotations</a> so the model will be checked if it contains the resource element with the 'name' attribute equal to 'org.apache.cxf.systest.jaxrs.ChapterNoAnnotations'. After this resource has been found, the  ChapterNoAnnotations class is recognized as a sub-resource and then its 'getItself' method is checked.  </p>

<p>Additionally the BookStoreNoAnnotations resource declares that all its resource methods produce 'application/json' mediaTypes, while its 'getBook' method overrides its with its own 'produces' value. BookStoreNoAnnotations resource also has a 'consumes' attribute which requires all of the resource methods (such as 'updateBook') to consume "application/json" formats. The ChapterNoAnnotations 'updateChapter' resource operation requires 'application/xml' formats.</p>

<p>You can use a comma-seperated list of media type values if needed, for example, produces("application/xml;charset=utf-8,application/json") or consumes("application/xml;charset=utf-8,application/json").</p>

<p>Please also see this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/resources2.xml" rel="nofollow">model file</a> for an example. Providing this file will let all implementations of the interface described in this model instance be exposed as RESTful services supported by the JAX-RS runtime. </p>

<h2><a name="JAX-RS-Configuration"></a>Configuration </h2>

<p>A user model can be referenced in a number of ways. It can be embedded in a jaxrs:server endpoint definition or linked to through a jaxrs:server modelRef attribute as a classpath resource. </p>

<p>Please see this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs/WEB-INF/beans.xml" rel="nofollow">bean</a> Spring configuration file, look at jaxrs server beans with 'bookservice6' and 'bookservice7' names.</p>

<p>Note that when registering a model from Spring you do not need to declare a jaxrs server serviceBeans section - the runtime will instantiate the beans itself. If you do need to inject certain properties into your service bean from Spring then you do need to declare a service bean too. In this case this bean will be instantiated twice - once by the runtime during the model introspection and once by Spring, however in the end it will be the bean created by Spring that will be used, the one created by the runtime will be removed.<br/>
You can avoid this double instantiation by having your model describing the interfaces which the actual root resource beans will implement. In this case only Spring will create a bean and the runtime will apply the model description to this injected bean. Note that if Spring proxifies your bean (for example by applying transaction aspects to it) then the model does have to describe an interface for a match between the model and the injected bean proxy to succeed.</p>

<p>Please have a look at <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_proxy/WEB-INF/beans.xml" rel="nofollow">this Spring bean</a>. The jaxrs endpoint with id 'bookservice2' will have BookStoreWithNoAnnotations created twice but it will be the Spring created BookStoreWithNoAnnotations bean that will serve as a resource class instance. The jaxrs endpoint with id 'bookservice3' will have BookStoreWithNoAnnotationsImpl class instantiated only by Spring, with the model describing BookStoreWithNoAnnotationsInterface only that this class implements.</p>


<p>You can also register a model programmatically, for example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
JAXRSServerFactoryBean sf = <span class="code-keyword">new</span> JAXRSServerFactoryBean();
            sf.setAddress(<span class="code-quote">"http:<span class="code-comment">//localhost:9080/"</span>);
</span><span class="code-object">String</span> modelRef = <span class="code-quote">"classpath:/org/apache/cxf/systest/jaxrs/resources/resources2.xml"</span>;
sf.setModelRef(modelRef);

<span class="code-comment">// or <span class="code-keyword">if</span> you have <span class="code-keyword">interface</span> classes described in the model already loaded, ex : OSGI
</span><span class="code-comment">// sf.setModelRefWithServiceClass(modelRef, BookStoreNoAnnotationsInterface.class);
</span>
<span class="code-comment">// register an actual bean only <span class="code-keyword">if</span> the model describes interfaces
</span>sf.setServiceBeans(<span class="code-keyword">new</span> BookStoreNoAnnotationsImpl());
</pre>
</div></div>

<p>Please also see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerUserResourceTest.java" rel="nofollow">this system test</a> for the example of how model beans like UserResource can be created and registered programmatically.</p>

<p>Similarly, you can register a user model on the client side, either from jaxrs:client or programmatically, example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
JAXRSClientFactoryBean cf = <span class="code-keyword">new</span> JAXRSClientFactoryBean();
cf.setAddress(<span class="code-quote">"http:<span class="code-comment">//localhost:9080/"</span>);
</span><span class="code-object">String</span> modelRef = <span class="code-quote">"classpath:/org/apache/cxf/systest/jaxrs/resources/resources2.xml"</span>;
sf.setModelRef(modelRef);
BookStoreNoAnnotations proxy = cf.create(BookStoreNoAnnotations.class);
</pre>
</div></div>

<p>At the moment it is only possible to register a user model with CXFNonSpringJAXRSServlet using the latest 2.2.3-SNAPSHOT like the way it is done in this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_non_spring/WEB-INF/web.xml" rel="nofollow">web.xml</a>. See CXFServlet3 and CXFServlet4 servlet declarations. Note that CXFServlet4 registers a model containing interfaces so it also registers a BookStoreNoAnnotationsImpl service class.</p>

<p>The workaround is to create a custom servlet :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class JAXRSUserModelServlet <span class="code-keyword">extends</span> CXFNonSpringJaxrsServlet  {

@Override
<span class="code-keyword">public</span> void loadBus(ServletConfig servletConfig) <span class="code-keyword">throws</span> ServletException {

<span class="code-keyword">super</span>.loadBus(servletConfig);

JAXRSServerFactoryBean sf = <span class="code-keyword">new</span> JAXRSServerFactoryBean();
<span class="code-object">String</span> address = servletConfig.getInitParameter(SERVICE_ADDRESS_PARAM); <span class="code-comment">//jaxrs.address
</span><span class="code-keyword">if</span> (address == <span class="code-keyword">null</span>) {
address = <span class="code-quote">"/"</span>;
}
sf.setAddress(address);

<span class="code-comment">// modelRef needs to start from 'classpath:', ex 'classpath:/WEB-INF/models/model1.xml
</span><span class="code-object">String</span> modelRef = servletConfig.getInitParameter(<span class="code-quote">"user.model"</span>);
sf.setModelRef(modelRef);
sf.create();
}
</pre>
</div></div>

<h1><a name="JAX-RS-IntegrationwithDistributedOSGi"></a>Integration with Distributed OSGi</h1>

<p>Distributed OSGi RI is a CXF <a href="http://cxf.apache.org/distributed-osgi.html" rel="nofollow">subproject</a>. DOSGi mandates how registered Java interfaces can be exposed<br/>
and consumed as remote services. DOSGi single and multi bundle distributions contain all the OSGI bundles required for a CXF endpoint be successfully published.</p>

<p>CXF JAX-RS implementations has been integrated with DOSGi RI 1.1-SNAPSHOT which makes it possible to expose Java interfaces as RESTful services and consume such services using a proxy-based client API.</p>

<p>Please see <a href="http://cxf.apache.org/distributed-osgi-reference.html#DistributedOSGiReference-ServiceProviderproperties" rel="nofollow">DOSGI Reference page</a> ('org.apache.cxf.rs' properties) and a <a href="http://svn.apache.org/repos/asf/cxf/dosgi/trunk/samples/greeter_rest/" rel="nofollow">greeter_rest</a> sample for more information. Note that this sampple can be run exactly as a SOAP-based <a href="http://cxf.apache.org/distributed-osgi-greeter-demo-walkthrough.html" rel="nofollow">greeter</a> demo as it registers and consumes a similar (but) JAX-RS annotated <a href="http://svn.apache.org/repos/asf/cxf/dosgi/trunk/samples/greeter_rest/interface/src/main/java/org/apache/cxf/dosgi/samples/greeter/rest/GreeterService.java" rel="nofollow">GreeterService</a>. In addition, this demo shows how one can register and consume a given interface (<a href="http://svn.apache.org/repos/asf/cxf/dosgi/trunk/samples/greeter_rest/interface/src/main/java/org/apache/cxf/dosgi/samples/greeter/rest/GreeterService2.java" rel="nofollow">GreeterService2</a>) without using explicit JAX-RS annotations but providing an out-of-band <a href="http://svn.apache.org/repos/asf/cxf/dosgi/trunk/samples/greeter_rest/interface/src/main/resources/OSGI-INF/cxf/jaxrs/GreeterService2-model.xml" rel="nofollow">user model description</a>.</p>

<h1><a name="JAX-RS-Howtocontribute"></a>How to contribute</h1>

<p>CXF JAX-RS implementation sits on top of the core CXF runtime and is quite self-contained and isolated from other CXF modules such as jaxws and simple frontends.</p>

<p>Please check this <a href="http://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&amp;mode=hide&amp;pid=12310511&amp;sorter/order=DESC&amp;sorter/field=priority&amp;resolution=-1&amp;component=12311911" rel="nofollow">list</a> and see if you are interested in fixing one of the issues.</p>

<p>If you decide to go ahead then the fastest way to start is to </p>
<ul>
	<li>do the fast trunk build using 'mvn install -Pfastinstall'</li>
	<li>setup the workspace 'mvn -Psetup.eclipse' which will create a workspace in a 'workspace' folder, next to 'trunk'</li>
	<li>import cxf modules from the trunk into the workspace and start working with the cxf-frontend-jaxrs module</li>
</ul>


<p>If you are about to submit a patch after building a trunk/rt/frontend/jaxrs, then please also run JAX-RS system tests in trunk/systests :<br/>
&gt; mvn test -Dtest=JAXRS* </p>

     </div>
     <div id="commentsSection" class="wiki-content pageSection">
       <div style="float: right;">
            <a href="http://cwiki.apache.org/confluence/users/viewnotifications.action" class="grey">Change Notification Preferences</a>
       </div>

       <a href="http://cwiki.apache.org/confluence/display/CXF20DOC/JAX-RS">View Online</a>
       |
       <a href="http://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=70366&revisedVersion=124&originalVersion=123">View Change</a>
              |
       <a href="http://cwiki.apache.org/confluence/display/CXF20DOC/JAX-RS?showComments=true&amp;showCommentArea=true#addcomment">Add Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message