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 Tue, 21 Dec 2010 22:48:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/1810/9/1/_/styles/combined.css?spaceKey=CXF20DOC&amp;forWysiwyg=true" type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/CXF20DOC/JAX-RS">JAX-RS</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~sergey_beryozkin">Sergey Beryozkin</a>
    </h4>
        <br/>
                         <h4>Changes (3)</h4>
                                 
    
<div id="page-diffs">
            <table class="diff" cellpadding="0" cellspacing="0">
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >JAX-RS 1.0 does not provide for the standard approach toward consuming pure HTTP-based services thus CXF JAX-RS provides a comprehensive support for developing RESTful clients by introducing 3 flavors of the client API : proxy-based, HTTP-centric and XML-centric. <br> <br></td></tr>
            <tr><td class="diff-changed-lines" >Please see <span class="diff-added-words"style="background-color: #dfd;">the</span> [JAX-RS Client API] <span class="diff-added-words"style="background-color: #dfd;">page</span> for more information. <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-deleted-lines" style="color:#999;background-color:#fdd;text-decoration:line-through;">h2. Proxy-based API <br> <br>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. <br> <br>[JAXRSClientFactory|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/JAXRSClientFactory.java] is a utility class which wraps [JAXRSClientFactoryBean|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/JAXRSClientFactoryBean.java]. JAXRSClientFactory has a number of utility methods but JAXRSClientFactoryBean can be used directly when needed. <br> <br>For example, given these class definitions : <br> <br>{code:java} <br>@Path(&quot;/bookstore&quot;) <br>public interface BookStore { <br>   @GET <br>   Books getAllBooks(); <br> <br>   @Path(&quot;{id}&quot;) <br>   BookResource getBookSubresource(@PathParam(&quot;id&quot;) long id) throws NoBookFoundException; <br>} <br> <br>public class BookStoreImpl implements BookStore { <br>   public Books getAllBooks() {} <br> <br>   public Book getBookSubresource(long id) throws NoBookFoundException {} <br>} <br> <br>public interface BookResource { <br>   @GET <br>   Book getDescription(); <br>} <br> <br>public class BookResourceImpl implements BookResource { <br>   @GET <br>   Book getDescription() {} <br>} <br> <br>{code} <br> <br>the following client code retrieves a Book with id &#39;1&#39; and a collection of books:  <br> <br>{code:java} <br>BookStore store = JAXRSClientFactory.create(&quot;http://bookstore.com&quot;, BookStore.class); <br>// (1) remote GET call to http://bookstore.com/bookstore <br>Books books = store.getAllBooks(); <br>// (2) no remote call <br>BookResource subresource = store.getBookSubresource(1); <br>// {3} remote GET call to http://bookstore.com/bookstore/1 <br>Book b = subresource.getDescription(); <br>{code}      <br> <br>When proxies are created, initially or when subresource methods are invoked, the current URI is updated with corresponding \@Path, \@PathParam, \@QueryParam or @MatrixParam values, while \@HttpHeader and \@CookieParam values contribute to the current set of HTTP headers. Same happens before the remote invocation is done.  <br> <br>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 \@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 *expected* by a server class.    <br> <br>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 \@FormParams or JAX-RS MultivaluedMap.  <br> <br>You can make multiple remote invocations on the same proxy (initial or subresource), the current URI and headers are updated properly.  <br> <br>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. <br> <br>h3. Customizing proxies  <br> <br>Proxies end up implementing not only the interface requested at the proxy creation time but also a [Client|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/Client.java] 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 \@Consumes or \@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 [WebClient|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/WebClient.java] utility method for converting a proxy to a base client : <br> <br>{code:java} <br>BookStore proxy = JAXRSClientFactory.create(&quot;http://books&quot;, BookStore.class); <br>WebClient.client(proxy).accept(&quot;text/xml&quot;); <br>// continue using the proxy     <br>{code} <br> <br>You can also check a current set of headers, current and base URIs and a client Response. <br> <br>h3. Converting proxies to Web Clients and vice versa <br> <br>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 : <br> <br>{code:java} <br>BookStore proxy = JAXRSClientFactory.create(&quot;http://books&quot;, BookStore.class); <br>WebClient client = WebClient.create(proxy); <br>// continue using the http client     <br>{code} <br> <br>At any moment of time you can convert an http client into a proxy too : <br> <br>{code:java} <br>BookStore proxy = JAXRSClientFactory.create(&quot;http://books&quot;, BookStore.class); <br>WebClient client = WebClient.create(proxy); <br>BookStore proxy = JAXRSClientFactory.fromClient(client, BookStore.class); <br>{code} <br> <br>h3. Handling exceptions <br> <br>There is a couple of ways you can handle remote exceptions with proxies. <br>One approach is to register a [ResponseExceptionMapper|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/ResponseExceptionMapper.java] 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. <br> <br>If no ResponseExceptionMapper is available when a remote invocation failed then an org.apache.cxf.jaxrs.client.ServerWebApplicationException (which is an instance of JAX-RS WebApplication) will be thrown. At this point of time you can check the actual Response and proceed from there : <br> <br>{code:java} <br>BookStore proxy = JAXRSClientFactory.create(&quot;http://books&quot;, BookStore.class); <br>try { <br>    proxy.getBook(); <br>} catch(ServerWebApplicationException ex) { <br>  Response r = ex.getResponse(); <br>  String message = ex.getMessage(); <br>} <br>{code} <br> <br>org.apache.cxf.jaxrs.client.ClientWebApplicationException will be thrown if the exception has occurred for one of two reasons :  <br>- the remote invocation succeeded but no proper MessageBodyReader has been found on the client side; in this case the Response object representing the result of the invocation will still be available <br>- the remote invocation has failed for whatever reasons on the client side, example, no MessageBodyWriter is available. <br> <br>h3. Configuring proxies in Spring <br> <br>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 : <br> <br>{code:java} <br>SpringBusFactory bf = new SpringBusFactory(); <br>Bus bus = bf.createBus(&quot;org/apache/cxf/systest/jaxrs/security/jaxrs-https.xml&quot;); <br>BusFactory.setDefaultBus(bus); <br>// BookStore proxy will get the configuration from Spring <br>BookStore proxy = JAXRSClientFactory.create(&quot;http://books&quot;, BookStore.class); <br>{code}  <br> <br>h3. Injecting proxies <br> <br>For injecting proxies via a spring context, use the jaxrs:client element like: <br>{code:xml} <br>  &lt;jaxrs:client id=&quot;restClient&quot; <br>         address=&quot;http://localhost:${testutil.ports.BookServerRestSoap}/test/services/rest&quot; <br>         serviceClass=&quot;org.apache.cxf.systest.jaxrs.BookStoreJaxrsJaxws&quot; <br>         inheritHeaders=&quot;true&quot;&gt; <br>         &lt;jaxrs:headers&gt; <br>             &lt;entry key=&quot;Accept&quot; value=&quot;text/xml&quot;/&gt; <br>         &lt;/jaxrs:headers&gt; <br>  &lt;/jaxrs:client&gt;   <br>{code} <br> <br>See this [bean|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_soap_rest/WEB-INF/beans.xml] for a full example how jaxrs:client can be used to inject a proxy  <br> <br>h3. Limitations <br> <br>Proxy methods can not have \@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.  <br> <br>When a proxy method returning JAX-RS Response is invoked, the returned Response.getEntity() will return a response InputStream by default. Starting from CXF 2.4.0-SNAPSHOT one can register an org.apache.cxf.jaxrs.client.ResponseReader provider and cast the Response.getEntity() to more specific application classes : <br> <br>{code:java} <br>ResponseReader reader = new ResponseReader(); <br>reader.setEntityClass(Book.class); <br> <br>BookStore bs = JAXRSClientFactory.create(&quot;http://localhost:8080/books&quot;, BookStore.class, <br>                                         Collections.singletonList(reader)); <br>Response r1 = bs.getBook(&quot;123&quot;); <br>Book book = (Book)r1.getEntity(); <br> <br>reader.setEntityClass(Author.class); <br>Response r2 = bs.getBookAuthor(&quot;123&quot;); <br>Author book = (Author)r2.getEntity(); <br>{code} <br> <br>h2. HTTP-centric clients <br> <br>HTTP centric clients are [WebClient|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/WebClient.java] instances which also implement the [Client|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/Client.java] 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 : <br> <br>{code:java} <br>WebClient client = WebClient.create(&quot;http://books&quot;); <br>Book book = client.path(&quot;bookstore/books&quot;).accept(&quot;text/xml&quot;).get(Book.class); <br>{code} <br> <br>You can choose to get an explicit JAX-RS Response instead and check the response code, headers or entity body if any : <br> <br>{code:java} <br>WebClient client = WebClient.create(&quot;http://books&quot;); <br>client.path(&quot;bookstore/books&quot;); <br>client.type(&quot;text/xml&quot;).accept(&quot;text/xml&quot;) <br>Response r = client.post(new Book()); <br>InputStream is = (InputStream)r.getEntity(); <br>Book b = getFromInputStreamUsingJaxb(is); <br>{code} <br> <br>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 : <br> <br>{code:java} <br>WebClient client = WebClient.create(&quot;http://books&quot;); <br>List&lt;Book&gt; books = getBooks(client, 1L, 2L, 3L) <br> <br>private List&lt;Book&gt; getBooks(WebClient client, Long ...ids) { <br>   List&lt;Book&gt; books = new ArrayList&lt;Book&gt;();  <br>   for (Long id : ids) { <br>       books.add(client.path(id).get(Book.class)); <br>       client.back();  <br>   }  <br>   return books; <br>} <br>{code} <br> <br>The above code will send requests like &quot;GET http://books/1&quot;, &quot;GET http://books/2&quot;, etc.  <br> <br>When reusing the same WebClient instance for multiple invocations, one may want to reset its state with the help of the reset() method, for example, when the Accept header value needs to be changed and the current URI needs to be reset to the baseURI (as an alternative to a back(true) call). The resetQuery() method may be used to reset the query values only. Both options are available for proxies too. <br> <br>h3. Working with explicit collections <br> <br>Example : <br> <br>{code:java} <br> <br>Collection&lt;? extends Book&gt; books = WebClient.getCollection(Book.class); <br>Collection&lt;? extends Book&gt; books = WebClient.postAndGetCollection(new ArrayList&lt;Book&gt;(), Book.class); <br> <br>{code} <br> <br>h3. Handling exceptions <br> <br> <br>You can handle remote exceptions by either explicitly getting a Response object as shown above and handling error statuses as needed or you can catch either ServerWebApplicationException or ClientWebApplicationException exceptions, the same way it can be done with proxies.  <br> <br>h3. Configuring HTTP clients in Spring <br> <br>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. For example : <br>{code:xml} <br>&lt;bean id=&quot;myJsonProvider&quot;  <br>class=&quot;org.apache.cxf.jaxrs.provider.JSONProvider&quot; &gt;  <br>        &lt;property name=&quot;supportUnwrapped&quot; value=&quot;true&quot; /&gt;  <br>        &lt;property name=&quot;wrapperName&quot; value=&quot;nodeName&quot; /&gt;  <br>    &lt;/bean&gt;  <br> <br>&lt;util:list id=&quot;webClientProviders&quot;&gt;  <br>    &lt;ref bean=&quot;myJsonProvider&quot;/&gt;  <br>&lt;/util:list&gt;  <br> <br>&lt;bean id=&quot;myWebClient&quot; class=&quot;org.apache.cxf.jaxrs.client.WebClient&quot;  <br>factory-method=&quot;create&quot;&gt;  <br>        &lt;constructor-arg type=&quot;java.lang.String&quot;  <br>value=&quot;http://some.base.url.that.responds/&quot; /&gt;  <br>        &lt;constructor-arg ref=&quot;webClientProviders&quot; /&gt;  <br>&lt;/bean&gt;  <br>{code}  <br> <br>h2. XML-centric clients <br> <br>XML-centric clients are WebClients using an [XMLSource|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/xml/XMLSource.java] 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 : <br> <br>{code:java} <br>WebClient wc = WebClient.create(&quot;http://aggregated/data&quot;); <br>XMLSource source = wc.get(XMLSource.class); <br>source.setBuffering(true); <br>Book b1 = source.getNode(&quot;/books/book[position() = 1]&quot;, Book.class); <br>Book b2 = source.getNode(&quot;/books/book[position() = 2]&quot;, Book.class); <br>{code} <br> <br>Note that an XMLSource instance can be set to buffer the input stream thus allowing for executing multiple XPath queries. <br>XMlSource can also help with getting the URIs representing the links or XML instances as Strings. <br> <br>h2. Thread Safety <br> <br>Proxies and web clients (clients) are not thread safe by default. In some cases this can be a limitation, especially when clients are injected; synchronizing on them can cause performance sideeffects.  <br> <br>One way to &#39;make&#39; clients thread-safe is to use WebClient.fromClient(Client) for web clients or JAXRSClientFactoryBean.fromClient() factory methods which copy all the original configuration properties and can be used to create new client instances per every request. <br> <br>A single client doing multiple invocations without changing the current URI or headers is thread-safe. The only limitation in this case applies to proxies, in that they can not get &quot;outofband&quot; headers without synchronizing, ex : <br>{code:java} <br>// get some response headers passed to us &#39;outofband&#39;, which is not thread-safe for a plain proxy :  <br>String bookHeader = WebClient.toClient(injectedBookStoreProxy).getHeaders().getFirst(&quot;BookHeader&quot;);  <br>{code}   <br> <br>Final option is to use a &#39;threadSafe&#39; boolean property when creating proxies or web clients (either from Spring or programmatically), see this [test|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSMultithreadedClientTest.java] for more details. Thread-safe clients created this way keep their state in a thread-local storage.  <br> <br>If a number of incoming threads is limited then one option is just do nothing, while the other option is to reset the thread local state : <br> <br>{code:java} <br>try {  <br>   webClient.path(&quot;bar&quot;)  <br>   webClient.header(&quot;bar&quot;, baz);  <br>   webClient.invoke(...);  <br>} finally {  <br>   // if proxy : WebClient.client(proxy).reset();  <br>   webClient.reset();  <br>}  <br>{code} <br> <br>Yet another option is to use JAXRSClientFactoryBean and a &#39;secondsToKeepState&#39; property for creating thread-safe clients - this will instruct clients to clean-up the thread-local state periodically. <br> <br> <br>h2. Configuring Clients at Runtime <br> <br>Proxy and http-centric clients are typically created by JAXRSClientFactory or WebClient factory methods but [JAXRSClientFactoryBean|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/client/JAXRSClientFactoryBean.java] can also be used for pre-configuring clients, before they are created. <br> <br>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 : <br> <br>{code:java} <br>Book proxy = JAXRSClientFactory.create(&quot;http://books&quot;, Book.class); <br>ClientConfiguration config = WebClient.getConfig(proxy); <br>HTTPConduit conduit1 = (HTTPConduit)config.getConduit(); <br> <br>WebClient webclient = WebClient.create(&quot;http://books&quot;); <br>HTTPConduit conduit2 = (HTTPConduit)WebClient.getConfig(webclient).getConduit(); <br>{code} <br> <br>h2. Configuring HTTP Conduit from Spring <br> <br>There&#39;s a number of ways to configure HTTPConduits for proxies and WebClients. <br> <br>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 : <br> <br>{code:xml} <br>&lt;http:conduit name=&quot;http://books:9095/bookstore.*&quot;/&gt;  <br>{code} <br> <br>This configuration will affect all proxies and WebClients which have requestURIs starting from &#39;http://books:9095/bookstore&#39;. Note the trailing &#39;.*&#39; suffix in the name of the http:conduit element. <br> <br>Please see [this configuration file|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/security/jaxrs-https-url.xml] for more examples. <br> <br>Alternatively you can just do : <br> <br>{code:xml} <br>&lt;http:conduit name=&quot;*.http-conduit&quot;/&gt;  <br>{code} <br> <br>This configuration will affect all the clients, irrespectively of which URIs the deal with. <br> <br>If you work with proxies then you can have the proxy-specific configuration using the expanded QName notation: <br> <br>{code:xml} <br>&lt;http:conduit name=&quot;{http://foo.bar}BookService.http-conduit&quot;/&gt;  <br>{code} <br> <br>In this example, &#39;foo.bar&#39; is a reverse package name of the BookService proxy class. <br> <br>Similarly, for WebClients you can do : <br> <br>{code:xml} <br>&lt;http:conduit name=&quot;{http://localhost:8080}WebClient.http-conduit&quot;/&gt;  <br>{code} <br> <br>In this example, &#39;http://localhost:8080&#39; is the base service URI. <br> <br>Please see [this configuration file|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/security/jaxrs-https.xml] for more examples. <br> <br>Also see [this wiki page|http://cwiki.apache.org/CXF20DOC/client-http-transport-including-ssl-support.html] on how to configure HTTPConduits. <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h1. XPath and XSLT <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >h1. Support for Multiparts <br> <br></td></tr>
            <tr><td class="diff-unchanged" >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.  <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">Please see the [JAX-RS Multiparts] page for more information.  <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h2. Reading attachments <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
        </table>
</div>                            <h4>Full Content</h4>
                    <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-Migration'>Migration</a></li>
<ul>
    <li><a href='#JAX-RS-MigratingfromJAXRS0.8to1.0'>Migrating from JAX-RS 0.8 to 1.0</a></li>
    <li><a href='#JAX-RS-Migratingfrom1.0to1.1'>Migrating from 1.0 to 1.1</a></li>
</ul>
    <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>
    <li><a href='#JAX-RS-Supportfordatabindings'>Support for data bindings</a></li>
    <li><a href='#JAX-RS-AdvancedSearchCapabilities'>Advanced Search Capabilities</a></li>
    <li><a href='#JAX-RS-Debugging'>Debugging</a></li>
    <li><a href='#JAX-RS-Logging'>Logging</a></li>
    <li><a href='#JAX-RS-ATOMlogging'>ATOM logging</a></li>
<ul>
    <li><a href='#JAX-RS-PushStyle'>Push Style</a></li>
<ul>
    <li><a href='#JAX-RS-Springconfiguration'>Spring configuration</a></li>
    <li><a href='#JAX-RS-Propertiesfile'>Properties file</a></li>
    <li><a href='#JAX-RS-Programmingstyle'>Programming style</a></li>
</ul>
    <li><a href='#JAX-RS-PollStyle'>Poll Style</a></li>
<ul>
    <li><a href='#JAX-RS-Springconfiguration'>Spring configuration</a></li>
    <li><a href='#JAX-RS-LinkingtoAtomendpointsfromCXFServicespage'>Linking to Atom endpoints from CXF Services page</a></li>
</ul>
</ul>
    <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>
    <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-Redirection'>Redirection</a></li>
<ul>
    <li><a href='#JAX-RS-WithRequestDispatcherProvider'>With RequestDispatcherProvider</a></li>
    <li><a href='#JAX-RS-WithCXFServlet'>With CXFServlet</a></li>
    <li><a href='#JAX-RS-CustomRedirection'>Custom Redirection</a></li>
</ul>
    <li><a href='#JAX-RS-ModelViewControllersupport'>Model-View-Controller support</a></li>
<ul>
    <li><a href='#JAX-RS-XSLT'>XSLT</a></li>
    <li><a href='#JAX-RS-JSP'>JSP</a></li>
</ul>
    <li><a href='#JAX-RS-SupportforMultiparts'>Support for Multiparts</a></li>
<ul>
    <li><a href='#JAX-RS-Readingattachments'>Reading attachments</a></li>
<ul>
    <li><a href='#JAX-RS-Formsandmultiparts'>Forms and multiparts</a></li>
</ul>
    <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>
    <li><a href='#JAX-RS-XOPsupport'>XOP support</a></li>
</ul>
    <li><a href='#JAX-RS-ServicelistingsandWADLsupport'>Service listings and WADL support</a></li>
<ul>
    <li><a href='#JAX-RS-DocumentingresourceclassesandmethodsinWADL'>Documenting resource classes and methods in WADL</a></li>
    <li><a href='#JAX-RS-CustomWADLproviders'>Custom WADL providers</a></li>
<ul>
    <li><a href='#JAX-RS-RepresentingexternalschemasandnonJAXBtypes'>Representing external schemas and non JAXB types</a></li>
</ul>
</ul>
    <li><a href='#JAX-RS-HidinglinkstoJAXRSendpointsfromtheservicespage'>Hiding links to JAXRS endpoints from the services page</a></li>
    <li><a href='#JAX-RS-CodeGeneration'>Code Generation</a></li>
<ul>
    <li><a href='#JAX-RS-Generatingtheclientcodeatruntime'>Generating the client code at runtime</a></li>
</ul>
    <li><a href='#JAX-RS-ConfiguringJAXRSservices'>Configuring JAX-RS services</a></li>
<ul>
    <li><a href='#JAX-RS-ConfiguringJAXRSservicesprogrammatically'>Configuring JAX-RS services programmatically</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-Onewayinvocations'>Oneway invocations</a></li>
    <li><a href='#JAX-RS-JMSSupport'>JMS Support</a></li>
    <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 standardizes the way RESTful services can be developed in Java. </p>

<p>CXF 2.3.0 supports <a href="https://jsr311.dev.java.net/nonav/releases/1.1/index.html" class="external-link" rel="nofollow">JSR-311 API 1.1</a>.<br/>
CXF 2.2.x supports <a href="https://jsr311.dev.java.net/nonav/releases/1.0/index.html" class="external-link" rel="nofollow">JSR-311 API 1.0 </a>.<br/>
CXF 2.3.0 and CXF 2.2.x have passed JAX-RS TCK 1.1 and TCK 1.0 respectively.</p>

<p>CXF 2.1.x supports <a href="https://jsr311.dev.java.net/nonav/releases/0.8/index.html" class="external-link" rel="nofollow">JSR-311 API 0.8</a>. </p>

<p>JAX-RS related demos are located under the samples/jax_rs directory.<br/>
This documentation will refer to <a href="https://jsr311.dev.java.net/nonav/releases/1.1/index.html" class="external-link" rel="nofollow">JSR-311 API 1.1 </a>.</p>

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

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


<h2><a name="JAX-RS-Migratingfrom1.0to1.1"></a>Migrating from 1.0 to 1.1</h2>

<p>Existing JAX-RS 1.0 applications should run in CXF 2.3.0 without any problems.<br/>
There have been just few minor modifications at the JAX-RS API level :</p>
<ul class="alternate" type="square">
	<li>@ApplicationPath has been introduced which JAX-RS Application implementations can be annotated with;</li>
	<li>Request interface has been updated with a new evaluatePreconditions method with no input parameters - the existing applications which are already using the Request interface may need to be recompiled.</li>
</ul>



<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.3.0<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 other CXF modules such cxf-api, cxf-rt-core, cxf-rt-transports-http and cxf-rt-bindings-xml as well as <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/pom.xml" class="external-link" rel="nofollow">the following 3rd-party dependencies</a>:</p>

<p>1. javax.ws.rs/jsr311-api/1.1 (or 1.0 for CXF 2.2.x)</p>

<p>2. org.apache.abdera groupId : abdera-core, abdera-parser and abdera-extensions-json artifacts, version 1.1. Note that starting from CXF 2.3.0 the Abdera dependencies are optional.</p>

<p>3. org.springframework/spring-core/3.0.5-RELEASE (and other core Spring dependencies)</p>

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

<p>5. org.apache.xmlbeans/xmlbeans/2.4.0</p>

<p>Please check <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/pom.xml" class="external-link" 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/" class="external-link" 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 Maven is not used then the following jars need to be available at the runtime classpath.</p>

<p>For CXF 2.3.0:</p>

<ul class="alternate" type="square">
	<li>cxf-2.3.0.jar</li>
	<li>jsr311-api-1.1.jar</li>
	<li>jaxb-impl-2.1.13.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.1.jar</li>
	<li>geronimo-servlet_3.0_spec_1.0.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.8.jar</li>
	<li>stax2-api-3.0.1.jar</li>
</ul>


<ul class="alternate" type="square">
	<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.x the dependencies are similar :</p>

<ul class="alternate" type="square">
	<li>cxf-2.2.12.jar</li>
	<li>jsr311-api-1.0.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 Jetty 7 or Jetty 6 jars shipped with CXF 2.3.0 and 2.2.12 respectively.</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" class="external-link" 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" class="external-link" rel="nofollow">JAX-RS spec </a>  <a href="https://jsr311.dev.java.net/nonav/releases/1.1/spec/spec.html" class="external-link" rel="nofollow">(html version) </a> to find out information not covered by this documentation.</p>

<p>The JAX-RS introduces such terms as root resources, resource methods, sub-resources and sub-resource locators, message body readers and writers, etc.  </p>

<p>Please see the <a href="/confluence/display/CXF20DOC/JAX-RS+Basics" title="JAX-RS Basics">JAX&#45;RS Basics</a> page for more information.</p>

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

<p>JAX-RS MessageBodyReader and MessageBodyWriter can be used to create data bindings for reading and writing the data in a number of different formats. Compliant JAX-RS implementations are expected to support JAXB-annotated beans, JAXP Source objects, InputStreams, etc.</p>

<p>In addition, CXF JAX-RS lets users reuse existing CXF DataBindings for working with JAXB, XBeans, Aegis and SDO.     </p>

<p>Please see the <a href="/confluence/display/CXF20DOC/JAX-RS+Data+Bindings" title="JAX-RS Data Bindings">JAX&#45;RS Data Bindings</a> page for more information. </p>

<h1><a name="JAX-RS-AdvancedSearchCapabilities"></a>Advanced Search Capabilities</h1>

<p>Using <a href="http://cxf.apache.org/docs/jax-rs.html#JAX-RS-Parameterbeans" class="external-link" rel="nofollow">query parameter beans</a> provides for a way to capture all the search requirements which can be expressed by enumerating simple name/value pairs, example, a query such as '?name=CXF&amp;version=2.3' can be captured by a bean containing setName and setVersion methods. This 'template' bean can be used in the code to compare it against all the available local data.</p>

<p>CXF JAXRS (since 2.3) supports another option for users to do the advanced search queries based on the <a href="http://tools.ietf.org/html/draft-nottingham-atompub-fiql-00" class="external-link" rel="nofollow">Feed Item Query Language</a>(FIQL). FIQL lets users express complex search expressions using an intuitive and URI friendly language.</p>

<p>For example, a query such as</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
?_search=name==CXF;version=ge=2.2
</pre>
</div></div>

<p>lets users to search for all the Apache projects with the name 'CXF' and the version greater or equals to '2.2'. The initial '=' separates the name of the query '_search' from the FIQL expression, while '==' and '=ge=' convey 'equals to' and 'greater or equals to' respectively.</p>

<p>More complex composite expressions can also be expressed easily enough.</p>

<p>Note that either '_search' or '_s' query has to be used to pass the FIQL expression.</p>

<p>To avail of this feature, a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchContext.java" class="external-link" rel="nofollow">SearchContext</a> can be injected into an application code and used to retrieve a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchCondition.java" class="external-link" rel="nofollow">SearchCondition</a> representing the current FIQL query. This SearchCondition can be used in a number of ways for finding the matching data.</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">"books"</span>)
<span class="code-keyword">public</span> class Books {

<span class="code-keyword">private</span> Map&lt;<span class="code-object">Long</span>, Book&gt; books;
@Context
<span class="code-keyword">private</span> SearchContext context;

 @GET
 <span class="code-keyword">public</span> List&lt;Book&gt; getBook() {

   SearchCondition&lt;Book&gt; sc = searchContext.getCondition(Book.class);
   <span class="code-comment">// SearchCondition#isMet method can also be used to build a list of matching beans
</span>   List&lt;Book&gt; found = sc.findAll(books.values());
   <span class="code-keyword">return</span> found;
 }
}
</pre>
</div></div>

<p>SearchCondition can also be used to get to all the search requirements (originally expressed in FIQL) and do some manual<br/>
comparison against the local data. For example, SearchCondition provides a utility toSQL(String tableName, String... columnNames) method which internally introspects all the search expressions constituting a current query and converts them into an SQL expression :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">// find all conditions with names starting from 'ami' 
</span><span class="code-comment">// and levels greater than 10 :
</span><span class="code-comment">// ?_s=<span class="code-quote">"name==ami*;level=gt=10"</span>
</span>SearchCondition&lt;Book&gt; sc = searchContext.getCondition(Book.class);
assertEquals("SELECT * FROM table 
              WHERE 
              name LIKE 'ami%' 
              AND 
              level &gt; '10'",
              sq.toSQL(<span class="code-quote">"table"</span>));
</pre>
</div></div>

<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/schemas/core.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-ATOMlogging"></a>ATOM logging</h1>
<p><b>This feature is available since 2.3, as part of the cxf-rt-management-web component</b></p>

<p>CXF supports collecting log events, converting them to <a href="http://tools.ietf.org/html/rfc4287" class="external-link" rel="nofollow">ATOM Syndication Format</a> and either pushing to the client or making them available for polling. Logging is based on custom <tt>java.util.logging</tt> (JUL) handler that can be registered with loggers extending today's publishing protocols.</p>

<p>CXF JAXRS and JAXWS endpoints can avail of this feature.</p>

<h2><a name="JAX-RS-PushStyle"></a>Push Style</h2>

<p>Push-style handler enqueues log records as they are published from loggers. After the queue size exceeds configurable "batch size", processing of collection of these records (in size of batch size) is triggered. Batch of log events is transformed by converter to ATOM element and then it is pushed out by deliverer to client. Both converter and deliverer are configurable units that allow to change transformation and transportation strategies. Next to predefined own custom implementations can be used when necessary &#8211; see examples. Batches are processed sequentially to allow client side to recreate stream of events. </p>

<p><b>Limitations:</b> Reliability is not supported out of the box, however there is predefined retrying delivery strategy. Persistence is also not supported, any enqueued and undelivered log events are lost on shutdown. Definitions of delivery endpoints is static, subscription of callback URIs is not yet supported. </p>

<h3><a name="JAX-RS-Springconfiguration"></a>Spring configuration</h3>
<p>In simplest case pushing ATOM Feeds can be declared this way:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPushBean"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"url"</span> value=<span class="code-quote">"http://somewhere.com/foo/bar"</span>/&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"level"</span> value=<span class="code-quote">"ALL"</span> /&gt;</span>
   <span class="code-tag">&lt;/bean&gt;</span>
</pre>
</div></div>
<p>Spring bean creates ATOM push handler and registers it with root logger for all log levels. This setup leads to logging everything CXF, Spring and others inclued. Since batch size is not specified default value of one is used - each event is packed up as single feed pushed out to specified URL. Default conversion strategy and default WebClient-based deliver are used. </p>

<p>More complex example shows how to specify non-root logger and define batch size:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPushBean"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"url"</span> value=<span class="code-quote">"http://somewhere.com/foo/bar"</span>/&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"logger"</span> value=<span class="code-quote">"org.apache.cxf.jaxrs"</span> /&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"level"</span> value=<span class="code-quote">"INFO"</span> /&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"batchSize"</span> value=<span class="code-quote">"10"</span> /&gt;</span>
   <span class="code-tag">&lt;/bean&gt;</span>
</pre>
</div></div>

<p>To push to client events generated by different loggers on different levels, "loggers" property must be used instead of pair "logger" and "level":</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.jaxrs.management.web.atom.AtomPushBean"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"url"</span> value=<span class="code-quote">"http://somewhere.com/foo/bar"</span>/&gt;</span>
       &lt;property name=<span class="code-quote">"loggers"</span> value="
           org.apache.cxf:DEBUG,
           org.apache.cxf.jaxrs,
           org.apache.cxf.bus:ERROR,
           myNamedLogger:INFO" /&gt;
   <span class="code-tag">&lt;/bean&gt;</span>
</pre>
</div></div>
<p>In example above, second logger does not have specified level, in such case default level of "INFO" is used.</p>

<p>In all above cases, when first delivery fails engine of ATOM push handler is shutdown and no events will be processed and pushed until configuration reload. To avoid this frequent case, retrial can be enabled:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPushBean"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"url"</span> value=<span class="code-quote">"http://somewhere.com/foo/bar"</span>/&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"logger"</span> value=<span class="code-quote">"org.apache.cxf.jaxrs"</span> /&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"level"</span> value=<span class="code-quote">"INFO"</span> /&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"retryPause"</span> value=<span class="code-quote">"linear"</span> /&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"retryPauseTime"</span> value=<span class="code-quote">"60"</span> /&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"retryTimeout"</span> value=<span class="code-quote">"300"</span> /&gt;</span>
   <span class="code-tag">&lt;/bean&gt;</span>
</pre>
</div></div>
<p>In this case for 5 minutes ("retryTimeout") after delivery failure there will be 1 minute pause ("retryPauseTime") repeated every time with same value ("retryPause" as "linear"). Instead of same pause time, "exponential" value of "retryPause" can be used - each next time pause time doubles. When timeout value is set to 0 retrying is infinite. In case of invalid or missing values defaults are used: for pause time 30 seconds and for timeout 0 (infinite). Instead of same pause time, "exponential" value of "retryPauseType" can be used - each next time pause time doubles. When timeout value is set to 0 retrying is infinite. In case of invalid or missing values defaults are used: for pause time 30 seconds and for timeout 0 (infinite).</p>

<p>Ultimate control is given by "converter" and "deliverer" properties. Either beans of predefined or custom classes can be used (see "Programming syle" chapter for more details). Example below shows custom class using different transport protocol than default:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   &lt;bean id=<span class="code-quote">"soapDeliverer"</span> ...
   ...
   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPushBean"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"deliverer"</span>&gt;</span>
           <span class="code-tag">&lt;ref bean=<span class="code-quote">"soapDeliverer"</span>/&gt;</span>
       <span class="code-tag">&lt;/property&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"loggers"</span> ... /&gt;</span>
   <span class="code-tag">&lt;/bean&gt;</span>
</pre>
</div></div>
<p>Note that specifying custom deliverer cause ignoring "url" and "retryXxx" because underneath configuration replaces employed tandem of RetryingDeliverer and WebClientDeliverer with provided one.</p>

<p>When ATOM feeds must be delivered to more than one endpoint and additionally each endpoint is fed by different loggers simply use multiple ATOM push beans in Spring config:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;bean id=<span class="code-quote">"atom1"</span> class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPushBean"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"url"</span> value=<span class="code-quote">"http://someplace.com/foo/bar"</span>/&gt;</span>
       ...
   <span class="code-tag">&lt;/bean&gt;</span>
   <span class="code-tag">&lt;bean id=<span class="code-quote">"atom2"</span> class=<span class="code-quote">"org.apache.cxf.jaxrs.management.web.atom.AtomPushBean"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"url"</span> value=<span class="code-quote">"http://otherplace.com/baz/blah"</span>/&gt;</span>
       ...
   <span class="code-tag">&lt;/bean&gt;</span>
   ....
</pre>
</div></div>

<h3><a name="JAX-RS-Propertiesfile"></a>Properties file</h3>
<p>When CXF is used either without Spring or logging is configured with properties file, support for this type of configuration becomes handy. ATOM push handler supports "simple configuration" with properties file; simple means aligned to expressiveness of JUL configuration that is limited to cases, where each type of handler can be used only once and registered with root logger.</p>

<p>Set of properties is very similar to Spring configuration with following exceptions:</p>
<ul>
	<li>Properties specify classes of custom deliverers and converters, instead of instances.</li>
	<li>Custom deliverer must have public constructor with the only String parameters; created instance will have passed URL of client.</li>
	<li>Multiple client endpoints is not supported out of the box (cannot instantiate multiple handlers as in Spring)</li>
</ul>


<p>Example:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
 handlers = org.apache.cxf.management.web.logging.atom.AtomPushHandler, java.util.logging.ConsoleHandler
 .level = INFO
 ...
 org.apache.cxf.jaxrs.ext.management.web.AtomPushHandler.url = http:<span class="code-comment">//localhost:9080
</span> org.apache.cxf.jaxrs.ext.management.web.AtomPushHandler.batchSize = 10
 org.apache.cxf.jaxrs.ext.management.web.AtomPushHandler.deliverer = WebClientDeliverer 
 org.apache.cxf.jaxrs.ext.management.web.AtomPushHandler.converter = foo.bar.MyConverter
 org.apache.cxf.jaxrs.ext.management.web.AtomPushHandler.retry.pause = linear
 org.apache.cxf.jaxrs.ext.management.web.AtomPushHandler.retry.pause.time = 10
 org.apache.cxf.jaxrs.ext.management.web.AtomPushHandler.retry.timeout = 360
 ...
</pre>
</div></div>

<h3><a name="JAX-RS-Programmingstyle"></a>Programming style</h3>
<p>In most complex cases direct programming using <tt><a href="http://cxf.apache.org/javadoc/latest/org/apache/cxf/management/web/logging/atom/package-summary.html" class="external-link" rel="nofollow">org.apache.cxf.jaxrs.ext.logging.atom</a></tt> package may be necessary. In this case AtomPushHandler class is main artifact and Deliverer and Converter interfaces and their implementations are necessary components.</p>

<p>Following example:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
    Deliverer d = <span class="code-keyword">new</span> WebClientDeliverer(<span class="code-quote">"http:<span class="code-comment">//somewhere.com/foo/bar"</span>);
</span>    d = <span class="code-keyword">new</span> RetryingDeliverer(d, 300, 60, <span class="code-keyword">true</span>);
    Converter c = <span class="code-keyword">new</span> SingleEntryContentConverter();
    AtomPushHandler h = <span class="code-keyword">new</span> AtomPushHandler(1, c, d);    
    Logger l = Logger.getLogger(<span class="code-quote">"org.apache.cxf.jaxrs"</span>);
    l.setLevel(Level.INFO);
    l.addHandler(h);
</pre>
</div></div>
<p>is equivalent to Spring configuration:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
   &lt;bean class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPushBean"</span> init-method=<span class="code-quote">"init"</span>&gt;
       &lt;property name=<span class="code-quote">"url"</span> value=<span class="code-quote">"http:<span class="code-comment">//somewhere.com/foo/bar"</span>/&gt;
</span>       &lt;property name=<span class="code-quote">"logger"</span> value=<span class="code-quote">"org.apache.cxf.jaxrs"</span> /&gt;
       &lt;property name=<span class="code-quote">"level"</span> value=<span class="code-quote">"INFO"</span> /&gt;
       &lt;property name=<span class="code-quote">"retryPause"</span> value=<span class="code-quote">"linear"</span> /&gt;
       &lt;property name=<span class="code-quote">"retryPauseTime"</span> value=<span class="code-quote">"60"</span> /&gt;
       &lt;property name=<span class="code-quote">"retryTimeout"</span> value=<span class="code-quote">"300"</span> /&gt;
   &lt;/bean&gt;
</pre>
</div></div>

<h2><a name="JAX-RS-PollStyle"></a>Poll Style</h2>

<p><a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/management-web/src/main/java/org/apache/cxf/management/web/logging/atom/AtomPullServer.java" class="external-link" rel="nofollow">AtomPullServer</a> acts as an Atom feed endpoint and makes all log events it has accumulated or read from some external storage available for polling.</p>

<p>Log events are made available in pages, that is a feed instance will list up to a configurable maximum number of entries and will also include atom links of types 'prev', 'next', 'first' and 'last', thus making it possible to browse through all the log records.</p>

<h3><a name="JAX-RS-Springconfiguration"></a>Spring configuration</h3>

<p>When configuring AtomPullServer endpoints, one can set the 'loggers' property the same way as it is done for AtomPushBeans, for example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPullServer"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       &lt;property name=<span class="code-quote">"loggers"</span> value="
           org.apache.cxf:DEBUG,
           org.apache.cxf.jaxrs,
           org.apache.cxf.bus:ERROR,
           myNamedLogger:INFO" /&gt;
       <span class="code-tag">&lt;property name=<span class="code-quote">"pageSize"</span> value=<span class="code-quote">"30"</span>/&gt;</span>
   <span class="code-tag">&lt;/bean&gt;</span>
</pre>
</div></div>

<p>In addition to the 'loggers' property, a 'pageSize' property limiting a number of entries per page to 30 is also set (default is 40).</p>

<p>One can have a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/management-web/src/main/java/org/apache/cxf/management/web/logging/ReadWriteLogStorage.java" class="external-link" rel="nofollow">ReadWriteLogStorage</a> bean injected into AtomPushBean if the log records have to be periodically offloaded from memory and persisted across restarts :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;bean id=<span class="code-quote">"storage"</span> class=<span class="code-quote">"org.apache.cxf.systest.jaxrs.JAXRSLoggingAtomPullSpringTest$Storage"</span>/&gt;</span>

   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPullServer"</span> init-method=<span class="code-quote">"init"</span>&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"loggers"</span> value=<span class="code-quote">"org.apache.cxf.jaxrs"</span> /&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"maxInMemorySize"</span> value=<span class="code-quote">"400"</span>/&gt;</span>
       <span class="code-tag">&lt;property name=<span class="code-quote">"storage"</span>&gt;</span>
           <span class="code-tag">&lt;ref bean=<span class="code-quote">"storage"</span>/&gt;</span>
       <span class="code-tag">&lt;/property&gt;</span>
   <span class="code-tag">&lt;/bean&gt;</span>
</pre>
</div></div>

<p>When a number of records in memory reaches 400 (default is 500) then the records will be offloaded into a provided storage and will be read from it after the restart or when a client has requested a relevant page. If no storage is available then after an in-memory limit is reached the oldest records will be discarded, one can set a maxInMemorySize property to a large enough value if needed.</p>

<p>Another option is to require a given AtomPullServer to read from the external read-only storage by registering a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/management-web/src/main/java/org/apache/cxf/management/web/logging/ReadableLogStorage.java" class="external-link" rel="nofollow">ReadableLogStorage</a> bean. For example, very often, the runtime is already logging to some external file, thus AtomPullServer can be asked to read from this file only with the help of ReadableLogStorage, without AtomPullServer having to catch log events too. </p>

<p>Once AtomPullServer has been configured, it has to be registered as a service bean with the jaxrs endpoint so that Atom aware clients (blog readers, etc) can start polling it :</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">"atomServer"</span> address=<span class="code-quote">"/atom"</span>&gt;</span>
 <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
   <span class="code-tag">&lt;ref bean=<span class="code-quote">"atomPullServer"</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">"feed"</span>/&gt;</span>
  <span class="code-tag">&lt;ref bean=<span class="code-quote">"entry"</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">"feed"</span> class=<span class="code-quote">"org.apache.cxf.jaxrs.provider.AtomFeedProvider"</span>/&gt;</span>
<span class="code-tag">&lt;bean id=<span class="code-quote">"entry"</span> class=<span class="code-quote">"org.apache.cxf.jaxrs.provider.AtomEntryProvider"</span>/&gt;</span>
</pre>
</div></div>

<h3><a name="JAX-RS-LinkingtoAtomendpointsfromCXFServicespage"></a>Linking to Atom endpoints from CXF Services page</h3>

<p>If you would like your users to find about the Atom feeds which are collecting log events from your endpoints then AtomPullServers will need to have a CXF bus injected, as well as be told about the address of the corresponding atom feed endpoint and of the jaxrs or jaxws endpoint :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
&lt;bean id=<span class="code-quote">"atomPullServer"</span> class=<span class="code-quote">"org.apache.cxf.management.web.logging.atom.AtomPullServer"</span> init-method=<span class="code-quote">"init"</span>&gt;
&lt;property name=<span class="code-quote">"loggers"</span> value=<span class="code-quote">"org.apache.cxf.systest.jaxrs.JAXRSLoggingAtomPullSpringTest$Resource:ALL"</span>/&gt;
&lt;property name=<span class="code-quote">"bus"</span>&gt;
&lt;ref bean=<span class="code-quote">"cxf"</span>/&gt;
&lt;/property&gt;
&lt;!-- <span class="code-keyword">this</span> is a jaxrs:server/@adrress or jaxws:endpoint/@address of the endpoint generating the log events --&gt;
&lt;property name=<span class="code-quote">"endpointAddress"</span> value=<span class="code-quote">"/resource"</span>/&gt;
&lt;!-- <span class="code-keyword">this</span> is a jaxrs:server/@address of the endpoint <span class="code-keyword">for</span> which <span class="code-keyword">this</span> atomPullServer bean is registered as a service bean --&gt;
&lt;property name=<span class="code-quote">"serverAddress"</span> value=<span class="code-quote">"/atom"</span>/&gt;
&lt;/bean&gt;
</pre>
</div></div>

<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" class="external-link" 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.PROTOCOL_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" class="external-link" 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" class="external-link" 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.get(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" class="external-link" 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 thus CXF JAX-RS provides a comprehensive support for developing RESTful clients by introducing 3 flavors of the client API : proxy-based, HTTP-centric and XML-centric.</p>

<p>Please see the <a href="/confluence/display/CXF20DOC/JAX-RS+Client+API" title="JAX-RS Client API">JAX&#45;RS Client API</a> page for more information.</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" class="external-link" 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" class="external-link" 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" class="external-link" 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-Redirection"></a>Redirection</h1>

<p>CXF 2.2.5 supports redirecting to other servlet resources for a given request and/or response be completed. </p>

<h2><a name="JAX-RS-WithRequestDispatcherProvider"></a>With RequestDispatcherProvider</h2>

<p><a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/RequestDispatcherProvider.java" class="external-link" rel="nofollow">RequestDispatcherProvider</a> is a JAXRS MessageBodyWriter which can redirect to JSP pages, named or default servlets. It can be used to serve all the responses from a given resource class or restricted to serving a limited set of classes only using a classResources map property. Note that this classResources property can also be used to specify the name of the key which JSP pages or other downstream servlets will use to access a response object.</p>

<p>At the moment, this provider is statically configured to support text/html content types, but it can be easily configured to support other content types if needed.  </p>

<p>Please see this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_dispatch/WEB-INF/beans.xml" class="external-link" rel="nofollow">beans.xml</a>. As you can see, it is possible to redirect to either to static resources such as book.html (possibly for providing some default response) or dynamic resources such as JSP pages. It is also possible to redirect to named servlets. </p>

<p>Note that the only required property is a 'requestPath' one and its value should start with a forward slash but it does not have to point to an existing web application resource such as book.html; it can also have values like "/other/services/", possibly in a combination with a 'dispatcherName' property.</p>

<p>Finally, a servletContextPath property can be used to have some other ServletContext (as opposed to the current one) be used for RequestDispatcher look-ups. If set then the current ServletContext.getContext(servletContextPath) will be used to get the needed ServletContext.</p>



<h2><a name="JAX-RS-WithCXFServlet"></a>With CXFServlet</h2>

<p>Please see the "Redirection" section on the <a href="http://cwiki.apache.org/confluence/display/CXF20DOC/Servlet+Transport" class="external-link" rel="nofollow">Servlet Transport</a> page.</p>

<p>Note that both CXFServlet and JAXRS RequestDispatcher provider can work together effectively on executing the redirection requests as described at that page.</p>

<p>If you have CXFServlet listening on "/" (thus effectively catching all the requests) and also would like to use RequestDispatcher, then make sure that a 'dispatcherName' property is also set, for example :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;bean id=<span class="code-quote">"dispatchProvider"</span> class=<span class="code-quote">"org.apache.cxf.jaxrs.provider.RequestDispatcherProvider"</span>&gt;</span>
    <span class="code-tag">&lt;property name=<span class="code-quote">"dispatcherName"</span> value=<span class="code-quote">"jsp"</span>/&gt;</span>
    <span class="code-tag">&lt;property name=<span class="code-quote">"resourcePath"</span> value=<span class="code-quote">"/WEB-INF/jsp/test.jsp"</span>/&gt;</span>
    <span class="code-tag">&lt;property name=<span class="code-quote">"scope"</span> value=<span class="code-quote">"request"</span>/&gt;</span>
<span class="code-tag">&lt;/bean&gt;</span> 
</pre>
</div></div>

<p>If resources which are redirected to can be made public (i.e, moved out of /WEB-INF) then alternative option (instead of adding a 'dispatcherName' property to RequestDispatcherProvider and still have CXFServlet listening on '/') is to configure both RequestDispatcherProvider and CXFServlet to redirect to resources such as "/jsp/test.jsp".</p>

<h2><a name="JAX-RS-CustomRedirection"></a>Custom Redirection</h2>

<p>One can borrow some of the code from RequestDispatcherProvider and do the custom redirection from CXF in interceptors or custom invokers, if you will try to do it then you will also need to set an AbstractHTTPDestination.REQUEST_REDIRECTED property with a 'true' value on a current input message.</p>

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

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

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

<p>With the introduction of the RequestDispatcherProvider (see above) it is now possible for JAXRS service responses be redirected to JSP pages for further processing. Please see this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_dispatch/WEB-INF/beans.xml" class="external-link" rel="nofollow">beans.xml</a>. </p>

<p>In addition to 'resourcePath' and 'dispatcherName' properties, one can set a 'scope' property which has two possible values, 'request' and 'session' with 'request' being the default value. It affects the way the JSP code can retrieve parameters passed to it by the RequestDispatcherProvider. If it is a 'request' scope then all the parameters are set as the attributes on the current HTTP request, if it is a session then they're set as the attributes on the current HTTP session.</p>

<p>RequestDispatcherProvider sets the following parameters :</p>

<ul class="alternate" type="square">
	<li>JAXRS method response object, the name of this parameter is either a simple class name of this object (lower case) or a value retrieved from a beanNames map property using the fully qualified class name of this object.</li>
	<li>All the path, query and matrix parameters which have been initialized during the method execution</li>
	<li>"absolute.path", "base.path" and "relative.path" obtained from the current UriInfo</li>
</ul>


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

<p>Please see the <a href="/confluence/pages/createpage.action?spaceKey=CXF20DOC&amp;title=JAX-RS+Multiparts&amp;linkCreation=true&amp;fromPageId=70366" class="createlink">JAX&#45;RS Multiparts</a> page for more information. </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" class="external-link" 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" class="external-link" 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" class="external-link" 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 working with either List of Attachments or MultipartBody, one may want to process the individual parts with the help of some custom procedures. Starting from CXF 2.3.0 it is also possible to do the following :</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 {
    Book book = body.getAttachmentObject(<span class="code-quote">"bookPart"</span>, Book.class);
}

@POST
<span class="code-keyword">public</span> void addAttachments(List&lt;Attachment&gt; attachments) <span class="code-keyword">throws</span> Exception {
    <span class="code-keyword">for</span> (Attachment attachment : attachments) {
        Book book = attachment.getObject(Book.class);
    }  
}

</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" class="external-link" 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" class="external-link" 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" class="external-link" rel="nofollow">test resource class</a> and <a href="http://sberyozkin.blogspot.com/2009/02/multiparts-in-cxf-jaxrs.html" class="external-link" rel="nofollow">blog entry</a> for more examples.</p>

<h3><a name="JAX-RS-Formsandmultiparts"></a>Forms and multiparts</h3>

<p>The <a href="http://www.w3.org/TR/html401/interact/forms.html" class="external-link" rel="nofollow">Forms in HTML documents</a> recommendation <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2" class="external-link" rel="nofollow">suggests</a> that multipart/form-data requests should mainly be used to upload files.</p>

<p>As mentioned in the previous section, one way to deal with multipart/form-data submissions is to deal directly with a CXF JAXRS Attachment class and get a Content-Disposition header and/or the underlying input stream.</p>

<p>It is now possible (since 2.2.5) to have individual multipart/form-data parts read by registered JAX-RS MessageBodyReaders, something that is already possible to do for types like multipart/mixed or multipart/related.</p>

<p>For example this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJson" class="external-link" rel="nofollow">request</a> can be handled by a method with the following signature :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@POST
@Path(<span class="code-quote">"/books/jsonform"</span>)
@Consumes(<span class="code-quote">"multipart/form-data"</span>)
<span class="code-keyword">public</span> Response addBookJsonFromForm(Book b1)  {...}
</pre>
</div></div>

<p>Similarly, this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJsonJaxb" class="external-link" rel="nofollow">request</a> can be handled by a method with the following signature :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@POST
@Path(<span class="code-quote">"/books/jsonjaxbform"</span>)
@Consumes(<span class="code-quote">"multipart/form-data"</span>)
<span class="code-keyword">public</span> Response addBookJaxbJsonForm(@Multipart(<span class="code-quote">"jsonPart"</span>) Book b1,
                                        @Multipart(<span class="code-quote">"bookXML"</span>) Book b2) {}
</pre>
</div></div>

<p>Note that once a request has more than two parts then one needs to start using @Mutipart, the values can refer to either ContentId header or to ContentDisposition/name. Note that at the moment using @Multipart is preferred to using @FormParam unless a plain name/value submission is dealt with. The reason is that @Multipart can also specify an expected media type of the individual part and thus act similarly to a @Consume annotation.</p>

<p>When dealing with multiple parts one can avoid using  @Multipart and just use List, ex, List\&lt;Atachment\&gt;, List\&lt;Book\&gt;, etc.</p>

<p>Finally, multipart/form-data requests with multiple files (file uploads) can be supported too. For example, this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJsonFiles" class="external-link" rel="nofollow">request</a> can be handled by a method with the signature like :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@POST
@Path(<span class="code-quote">"/books/filesform"</span>)
@Produces(<span class="code-quote">"text/xml"</span>)
@Consumes(<span class="code-quote">"multipart/form-data"</span>)
<span class="code-keyword">public</span> Response addBookFilesForm(@Multipart(<span class="code-quote">"owner"</span>) <span class="code-object">String</span> name,
                                 @Multipart(<span class="code-quote">"files"</span>) List&lt;Book&gt; books) {} 
</pre>
</div></div>

<p>If you need to know the names of the individual file parts embedded in a "files" outer part (such as "book1" and "book2"), then please use List&lt;Attachment&gt; instead. It is currently not possible to use a Multipart annotation to refer to such inner parts but you can easily get the names from the individual Attachment instances representing these inner parts.</p>

<p>Note that it is only the last request which has been structured according to the recommendation on how to upload multiple files but it is more complex than the other simpler requests linked to in this section. </p>

<p>Please note that using JAX-RS FormParams is recommended for dealing with plain application/www-url-encoded submissions consisting of name/value pairs only.</p>

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

<p>Starting from 2.2.4 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>

<h2><a name="JAX-RS-XOPsupport"></a>XOP support</h2>

<p>CXF JAXRS clients and endpoints can support <a href="http://www.w3.org/TR/xop10/" class="external-link" rel="nofollow">XML-binary Optimized Packaging (XOP)</a>.<br/>
What it means at a practical level is that a JAXB bean containing binary data is serialized using a multipart packaging, with the root part containing non-binary data only but also linking to co-located parts containing the actual binary payloads. Next it is deserialized into a JAXB bean on the server side.</p>

<p>If you'd like to experiment with XOP then you need to set an "mtom-enabled" property on CXF jaxrs endpoints and clients.<br/>
Please see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSMultipartTest.java" class="external-link" rel="nofollow">JAXRSMultipartTest</a> (testXopWebClient) and <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/MultipartStore.java" class="external-link" rel="nofollow">MultipartStore</a> (addBookXop) for more details.</p>

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

<p>CXF JAX-RS now supports the auto-generation of <a href="http://www.w3.org/Submission/wadl" class="external-link" rel="nofollow">WADL</a> 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" class="external-link" 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" class="external-link" rel="nofollow">http://localhost:8080/store/books/orders/fiction?_wadl</a><br/>
&gt; <a href="http://localhost:8080/store/books/orders/sport?_wadl" class="external-link" 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" class="external-link" rel="nofollow">http://localhost:8080/store/books</a> <br/>
&gt; <a href="http://localhost:8080/store/books/services" class="external-link" 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>

<h2><a name="JAX-RS-DocumentingresourceclassesandmethodsinWADL"></a>Documenting resource classes and methods in WADL</h2>

<p>WADL documents can include <a href="http://www.w3.org/Submission/wadl/#x3-80002.3" class="external-link" rel="nofollow">doc</a> fragments. Users may want to use <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/Description.java" class="external-link" rel="nofollow">Description</a> annotations which can be attached to resource classes and methods.</p>

<h2><a name="JAX-RS-CustomWADLproviders"></a>Custom WADL providers</h2>

<p>One can register a custom WADLGenerator as a jaxrs:provider. The custom generator can extend the default <br/>
org.apache.cxf.jaxrs.model.wadl.WADLGenerator or register a default one with one of the following properties set.</p>

<ul class="alternate" type="square">
	<li>wadlNamespace : default is "http://wadl.dev.java.net/2009/02", the earlier one is "http://research.sun.com/wadl/2006/10".</li>
	<li>singleResourceMultipleMethods : default is 'true', for example, if a resource class has multiple methods supported at the same path such as "/" (GET, POST, etc) then WADL will list them all as the child nodes of a single resource element.</li>
	<li>useSingleSlashResource : default is false, for example, if you have a root resource class with a path "root" and a resource method with a path "" or "/" then a WADL resource representing the root will not have a child resource representing this resource method (it would do if a resource method had a more specific path such as "bar").</li>
</ul>


<h3><a name="JAX-RS-RepresentingexternalschemasandnonJAXBtypes"></a>Representing external schemas and non JAXB types</h3>

<p>By default, the WADL grammar section will be properly generated if resource methods accept or return JAXB types. </p>

<p>Even when you do use JAXB, the JAXB types may have been generated from the external schema so having WADLGenerator attempting to recreate the original schema may not work well. To have a generated WADL referencing the original schema(s) please set a 'schemaLocations' list property (programmatically or from Spring) :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
WadlGenerator wg = <span class="code-keyword">new</span> WadlGenerator();
wg.setSchemaLocations(Collections.singletonList(<span class="code-quote">"classpath:/book.xsd"</span>));
</pre>
</div></div> 

<p>In this case the grammar section will have the 'book.xsd' schema inlined. If this schema imports other schemas then the imports with relative URIs will be replaced by the absolute URIs based on the current endpoint's base address. For example, if the endpoint address is "http://somehost/bar" and the 'book.xsd' imports "foo/book1.xsd" then the published WADL will contain an "http://somehost/bar/foo/book1.xsd". At the moment a custom RequestHandler filter will have to be registered to serve resources such as "http://somehost/bar/foo/book1.xsd" which can 'calculate' which resource is required get the absolute request URI and comparing it with the base URI, possibly with the help of the injected JAXRS UriInfo context. Alternatively, resources such as book1.xsd may be served by CXFServlet itself (see the Redirection with CXFServlet)  </p>

<p>TODO : add ignoreImports flag so that users can list root and imported schemas in "schemaLocations" and have them all inlined.</p>

<p>Note that the root schema such as "book.xsd" is inlined - you can have it referenced only by setting an 'externalLinks' list property. This will very well when the "book.xsd" is indeed available at some external URI, but this property can be used to avoid the local schemas being inlined. Moreover, using JAXB will not be required. The result will look like this :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;wadl:grammars&gt;</span>
<span class="code-tag">&lt;wadl:include href=<span class="code-quote">"http://books.xsd"</span>/&gt;</span>
<span class="code-tag">&lt;/wadl:grammars&gt;</span>
</pre>
</div></div> 

<p>Note that "schemaLocations" and "externalLinks" properties differ in that the schemas referenced by the former one are inlined.</p>

<p>You can also customize the way schema elements are referenced. When WADLGenerator creates WADL representation elements (representing resource method input or output types) it will be able to link to schema elements provided a given type is actually a JAXB one, so the result may look like this :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
&lt;!-- 
  thebook2 element is declared in a schema inlined in or referenced from the grammar section
  prefix1 is bound to that schema's target namespace and is declared at the wadl:application element 
--&gt;
<span class="code-tag">&lt;representation mediaType=<span class="code-quote">"application/xml"</span> element=<span class="code-quote">"prefix1:thebook2"</span>/&gt;</span>
</pre>
</div></div>

<p>If no JAXB is used then you can attach an <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/xml/XMLName.java" class="external-link" rel="nofollow">XmlName</a> annotation to method input or output types. Alternatively, you can register an instance of <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/model/wadl/ElementQNameResolver.java" class="external-link" rel="nofollow">ElementQNameResolver</a> with the WADLGenerator which will be used for creating wadl:representation/@element values.</p>

<h1><a name="JAX-RS-HidinglinkstoJAXRSendpointsfromtheservicespage"></a>Hiding links to JAXRS endpoints from the services page </h1>

<p>In some cases you may not want the users to see the links to some of your JAXRS endpoints. For example, if you have an AtomPullServer endpoint collecting the log entries for a number of application endpoints, you may not want to the AtomPullServer endpoint being listed among the endpoints which the users are actually interested in. If so then adding an "org.apache.cxf.endpoint.private" boolean property with the value "true" will do the trick; note the same property can be used by jaxws endpoints.</p>

<h1><a name="JAX-RS-CodeGeneration"></a>Code Generation</h1>

<h2><a name="JAX-RS-Generatingtheclientcodeatruntime"></a>Generating the client code at runtime</h2>

<p>If you register an org.apache.cxf.jaxrs.ext.codegen.CodeGeneratorProvider with a jaxrs endpoint and issue a '_code' query to it then you will get back an XHTML page containing the link to a zipped client source code which you can download and start customizing. </p>

<p>Internally, before the code gets generated, WADL will be generated first. The archive will include JAXB generated classes from a WADL grammar section plus the proxy based client code for accessing root and sub resources. The WebClient based code can not be generated just yet but one can request that only a WADL grammar section is processed by adding a '_codeType=grammar' query and easily adding a WebClient-based code. </p>

<p>Here is how to get the archive programmatically :</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">//localhost:9080/petstore"</span>);
</span>XMLSource source = wc.query(<span class="code-quote">"_code"</span>).query(<span class="code-quote">"_os"</span>, getOs()).get(XMLSource.class);
<span class="code-object">String</span> link = source.getValue(<span class="code-quote">"ns:html/ns:body/ns:ul/ns:a/@href"</span>,  
              Collections.singletonMap(<span class="code-quote">"ns"</span>,<span class="code-quote">"http:<span class="code-comment">//www.w3.org/1999/xhtml"</span>));
</span><span class="code-comment">// download a zip file          
</span>WebClient wcZip = WebClient.create(link);
InputStream is = wcZip.accept(<span class="code-quote">"application/zip"</span>).get(InputStream.class);
<span class="code-comment">// unzip and compile it</span>
</pre>
</div></div>

<p>Please see a <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerResourceCreatedSpringProviderTest.java" class="external-link" rel="nofollow">testPetStore</a> test for more details.</p>

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

<h2><a name="JAX-RS-ConfiguringJAXRSservicesprogrammatically"></a>Configuring JAX-RS services programmatically</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 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 the 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" class="external-link" 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-Onewayinvocations"></a>Oneway invocations</h1>

<p>Resource methods with an org.apache.cxf.jaxrs.ext.Oneway annotation will be invoked oneway with the original request returning 202 HTTP status. HTTP or JMS clients can also add a "OnewayRequest" header if adding Oneway annotations is not an option.</p>

<h1><a name="JAX-RS-JMSSupport"></a>JMS Support</h1>

<p>CXF has been designed such that multiple transports can be supported for a given endpoint. If you would like your JAXRS endpoint be capable of serving not only HTTP but also JMS requests then you need to specify a JMS transportId, example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;jaxrs:server serviceName=<span class="code-quote">"s:BookService"</span> transportId=<span class="code-quote">"http://cxf.apache.org/transports/jms"</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.apache.cxf.systest.jaxrs.JMSBookStore"</span>/&gt;</span>
 <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>
</pre>
</div></div> 

<p>Additionally, JMS queue or topic <a href="http://cxf.apache.org/docs/using-the-jmsconfigfeature.html" class="external-link" rel="nofollow">configuration</a> needs to be done, for example, please see this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/jms_server_config.xml" class="external-link" rel="nofollow">beans.xml</a>. Please note how a serviceName attribute is used to specify a service QName for a jaxrs endpoint (default is {<a href="http://reverse.package.name" class="external-link" rel="nofollow">http://reverse.package.name</a>}ServiceClassName), this service name is <br/>
used to configure a jms destination.</p>

<p>Here is the actual <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSJmsTest.java" class="external-link" rel="nofollow">test</a>. </p>

<p>Here are JMS properties which can help with matching a required method on the JAXRS endpoint :</p>
<ul class="alternate" type="square">
	<li>"Content-Type" : default is "text/xml"</li>
	<li>"Accept" : default is "<b>/</b>"</li>
	<li>"OnewayMessage" : default is "false"</li>
	<li>"org.apache.cxf.message.Message.REQUEST_URI" : default is "/"</li>
	<li>"org.apache.cxf.message.Message.HTTP_REQUEST_METHOD" : default is "POST"</li>
</ul>


<p>If JMS messages are sent to topic destinations then one has to either set a "OnewayMessage" property or ensure that target JAXRS methods are annotated with org.apache.cxf.jaxrs.ext.Oneway. </p>

<p>As far as REQUEST_URI is concerned, it is initially matched against a jaxrs:server/@address. So if REQUEST_URI is not set or set to "/" then jaxrs:server/@address has to be set to "/". If REQUEST_URI is set to "/bar/foo" and<br/>
jaxrs:server/@address is set to "/bar" then it will be '/foo' which will be used to find a root resource class and its method.</p>

<p>By referencing a bean such as 'org.apache.cxf.systest.jaxrs.JMSBookStore' from multiple jaxrs endpoints you can ensure that both HTTP and JMS requests are handled by the same service bean. In such cases you may want to use a CXF JAXRS specific <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ProtocolHeaders.java" class="external-link" rel="nofollow">ProtocolHeaders</a> context which will let you get either HTTP or JMS headers. </p>


<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" class="external-link" 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>Starting from CXF 2.3.2-SNAPSHOT a "oneway" attribute can also be applied to individual operations.</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" class="external-link" 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" class="external-link" 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" class="external-link" 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" class="external-link" 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" class="external-link" 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" class="external-link" 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" class="external-link" 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" class="external-link" 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" class="external-link" 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/" class="external-link" rel="nofollow">greeter_rest</a> sample for more information. Note that this demo can be run exactly as a SOAP-based <a href="http://cxf.apache.org/distributed-osgi-greeter-demo-walkthrough.html" class="external-link" 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" class="external-link" 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" class="external-link" 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" class="external-link" 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" class="external-link" 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/jaxrs :<br/>
&gt; mvn install </p>

    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;">
            <a href="https://cwiki.apache.org/confluence/users/viewnotifications.action" class="grey">Change Notification Preferences</a>
        </div>
        <a href="https://cwiki.apache.org/confluence/display/CXF20DOC/JAX-RS">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=70366&revisedVersion=182&originalVersion=181">View Changes</a>
                |
        <a href="https://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