Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


{span:style=
Span
Wiki Markup
style
font-size:2em;font-weight:bold
} JAX-RS (JSR-311) {span} {toc} h1. Introduction CXF supports JAX-RS (JSR-311), Java API for RESTful Web Services. JAX-RS standardizes the way RESTful services can be developed in Java. CXF 2.3.0 supports [JSR-311 API 1.1| https://jsr311.dev.java.net/nonav/releases/1.1/index.html]. CXF 2.2.x supports [JSR-311 API 1.0 | https://jsr311.dev.java.net/nonav/releases/1.0/index.html]. CXF 2.3.0 and CXF 2.2.x have passed JAX-RS TCK 1.1 and TCK 1.0 respectively. CXF 2.1.x supports [JSR-311 API 0.8| https://jsr311.dev.java.net/nonav/releases/0.8/index.html]. JAX-RS related demos are located under the samples/jax_rs directory. This documentation will refer to [JSR-311 API 1.1 | https://jsr311.dev.java.net/nonav/releases/1.1/index.html]. h1. Migration h2. Migrating from JAX-RS 0.8 to 1.0 The following major changes in 1.0 will most likely affect users migrating from 0.8 - @ProduceMime and @ConsumeMime have been replaced with @Produces and @Consumes respectively - HttpHeaders has had some of its methods returning a string representation of Locale updated to return Locale instead h2. Migrating from 1.0 to 1.1 Existing JAX-RS 1.0 applications should run in CXF 2.3.0 without any problems. There have been just few minor modifications at the JAX-RS API level : - @ApplicationPath has been introduced which JAX-RS Application implementations can be annotated with; - 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. h1. Maven dependencies To incorporate JAX-RS, you will need: {code:xml} <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>2.3.0</version> </dependency> {code} 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 [the following 3rd-party dependencies|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/pom.xml]: 1. javax.ws.rs/jsr311-api/1.1 (or 1.0 for CXF 2.2.x) 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. 3. org.springframework/spring-core/3.0.5-RELEASE (and other core Spring dependencies) 4. org.codehaus.jettison/jettison/1.2 5. org.apache.xmlbeans/xmlbeans/2.4.0 Please check [the pom.xml|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/pom.xml] for the list of cxf components used by the JAX-RS implementation. Snapshots are available from http://repository.apache.org/snapshots/org/apache/cxf/apache-cxf/ h1. Setting up the classpath in Eclipse or Ant If Maven is not used then the following jars need to be available at the runtime classpath. For CXF 2.3.0: - cxf-2.3.0.jar - jsr311-api-1.1.jar - jaxb-impl-2.1.13.jar - jaxb-api-2.1.jar - geronimo-annotation_1.0_spec-1.1.1.jar - geronimo-activation_1.1_spec-1.1.jar - geronimo-servlet_3.0_spec_1.0.jar - commons-logging-1.1.1.jar - geronimo-stax_api_1.0_spec-1.0.1.jar - woodstox-core-asl-4.0.8.jar - stax2-api-3.0.1.jar - wsdl4j-1.6.2.jar - XmlSchema-1.4.5.jar - neethi-2.0.4.jar For CXF 2.2.x the dependencies are similar : - cxf-2.2.12.jar - jsr311-api-1.0.jar - do not add stax2-api-3.0.1.jar - add wstx-asl-3.2.8.jar instead of woodstox-core-asl-4.0.3.jar - add saaj-api-1.3.jar 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. We will work on reducing the set of required dependencies. Please see the configuration sections below on how a spring dependency can be dropped. h1. CXF JAX-RS bundle A standalone [JAX-RS bundle|http://svn.apache.org/repos/asf/cxf/trunk/distribution/bundle/jaxrs/pom.xml] is now available which may be of interest to users doing JAX-RS work only. h1. Understanding the basics You are encouraged to read [JAX-RS spec | http://jcp.org/en/jsr/detail?id=311] [(html version) | https://jsr311.dev.java.net/nonav/releases/1.1/spec/spec.html] to find out information not covered by this documentation. The JAX-RS introduces such terms as root resources, resource methods, sub-resources and sub-resource locators, message body readers and writers, etc. Please see the [JAX-RS Basics] page for more information. h1. Support for data bindings 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. In addition, CXF JAX-RS lets users reuse existing CXF DataBindings for working with JAXB, XBeans, Aegis and SDO. Please see the [JAX-RS Data Bindings] page for more information. h1. Advanced Search Capabilities Using [query parameter beans|http://cxf.apache.org/docs/jax-rs.html#JAX-RS-Parameterbeans] 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&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. CXF JAXRS (since 2.3) supports another option for users to do the advanced search queries based on the [Feed Item Query Language|http://tools.ietf.org/html/draft-nottingham-atompub-fiql-00](FIQL). FIQL lets users express complex search expressions using an intuitive and URI friendly language. For example, a query such as {code:java} ?_search=name==CXF;version=ge=2.2 {code} 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. More complex composite expressions can also be expressed easily enough. Note that either '_search' or '_s' query has to be used to pass the FIQL expression. To avail of this feature, a [SearchContext|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchContext.java] can be injected into an application code and used to retrieve a [SearchCondition|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchCondition.java] representing the current FIQL query. This SearchCondition can be used in a number of ways for finding the matching data. For example : {code:java} @Path("books") public class Books { private Map<Long, Book> books; @Context private SearchContext context; @GET public List<Book> getBook() { SearchCondition<Book> sc = searchContext.getCondition(Book.class); // SearchCondition#isMet method can also be used to build a list of matching beans List<Book> found = sc.findAll(books.values()); return found; } } {code} SearchCondition can also be used to get to all the search requirements (originally expressed in FIQL) and do some manual 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 : {code:java} // find all conditions with names starting from 'ami' // and levels greater than 10 : // ?_s="name==ami*;level=gt=10" SearchCondition<Book> sc = searchContext.getCondition(Book.class); assertEquals("SELECT * FROM table WHERE name LIKE 'ami%' AND level > '10'", sq.toSQL("table")); {code} h1. Debugging One can easily try from a browser how a given resource class reacts to different HTTP Accept or Accept-Language header values. For example, if a resource class supports "/resource" URI then one can test the resource class using one of the following queries : GET /resource.xml GET /resource.en The runtime will replace '.xml' or '.en' with an appropriate header value. For it to know the type or language value associated with a given URI suffix, some configuration needs to be done. Here's an example how to do it in Spring : {code:xml} <jaxrs:server id="customerService" address="/"> <jaxrs:serviceBeans> <ref bean="customerService" /> </jaxrs:serviceBeans> <jaxrs:extensionMappings> <entry key="json" value="application/json"/> <entry key="xml" value="application/xml"/> </jaxrs:extensionMappings> <jaxrs:languageMappings/> </jaxrs:server> {code} See below for a more complete configuration example. See the JAX-RS specification for more details. CXF also supports _type query as an alternative to appending extensions like '.xml' to request URIs : GET /resource?_type=xml h1. Logging Existing CXF features can be applied to jaxrs:server or jaxrs:client, whenever it makes sense. To enable logging of requests and responses, simply do : {code:xml} <beans xmlns:cxf="http://cxf.apache.org/core" xsi:schemaLocation="http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd"> <jaxrs:server> <jaxrs:features> <cxf:logging/> </jaxrs:features> <jaxrs:server> </beans> {code} Please make sure a "http://cxf.apache.org/core" namespace is in scope. h1. ATOM logging *This feature is available since 2.3, as part of the cxf-rt-management-web component* CXF supports collecting log events, converting them to [ATOM Syndication Format|http://tools.ietf.org/html/rfc4287] and either pushing to the client or making them available for polling. Logging is based on custom {{java.util.logging}} (JUL) handler that can be registered with loggers extending today's publishing protocols. CXF JAXRS and JAXWS endpoints can avail of this feature. h2. Push Style 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 -- see examples. Batches are processed sequentially to allow client side to recreate stream of events. *Limitations:* 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. h3. Spring configuration In simplest case pushing ATOM Feeds can be declared this way: {code:xml} <bean class="org.apache.cxf.management.web.logging.atom.AtomPushBean" init-method="init"> <property name="url" value="http://somewhere.com/foo/bar"/> <property name="level" value="ALL" /> </bean> {code} 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. More complex example shows how to specify non-root logger and define batch size: {code:xml} <bean class="org.apache.cxf.management.web.logging.atom.AtomPushBean" init-method="init"> <property name="url" value="http://somewhere.com/foo/bar"/> <property name="logger" value="org.apache.cxf.jaxrs" /> <property name="level" value="INFO" /> <property name="batchSize" value="10" /> </bean> {code} To push to client events generated by different loggers on different levels, "loggers" property must be used instead of pair "logger" and "level": {code:xml} <bean class="org.apache.cxf.jaxrs.management.web.atom.AtomPushBean" init-method="init"> <property name="url" value="http://somewhere.com/foo/bar"/> <property name="loggers" value=" org.apache.cxf:DEBUG, org.apache.cxf.jaxrs, org.apache.cxf.bus:ERROR, myNamedLogger:INFO" /> </bean> {code} In example above, second logger does not have specified level, in such case default level of "INFO" is used. 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: {code:xml} <bean class="org.apache.cxf.management.web.logging.atom.AtomPushBean" init-method="init"> <property name="url" value="http://somewhere.com/foo/bar"/> <property name="logger" value="org.apache.cxf.jaxrs" /> <property name="level" value="INFO" /> <property name="retryPause" value="linear" /> <property name="retryPauseTime" value="60" /> <property name="retryTimeout" value="300" /> </bean> {code} 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). 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: {code:xml} <bean id="soapDeliverer" ... ... <bean class="org.apache.cxf.management.web.logging.atom.AtomPushBean" init-method="init"> <property name="deliverer"> <ref bean="soapDeliverer"/> </property> <property name="loggers" ... /> </bean> {code} Note that specifying custom deliverer cause ignoring "url" and "retryXxx" because underneath configuration replaces employed tandem of RetryingDeliverer and WebClientDeliverer with provided one. 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: {code:xml} <bean id="atom1" class="org.apache.cxf.management.web.logging.atom.AtomPushBean" init-method="init"> <property name="url" value="http://someplace.com/foo/bar"/> ... </bean> <bean id="atom2" class="org.apache.cxf.jaxrs.management.web.atom.AtomPushBean" init-method="init"> <property name="url" value="http://otherplace.com/baz/blah"/> ... </bean> .... {code} h3. Properties file 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. Set of properties is very similar to Spring configuration with following exceptions: * Properties specify classes of custom deliverers and converters, instead of instances. * Custom deliverer must have public constructor with the only String parameters; created instance will have passed URL of client. * Multiple client endpoints is not supported out of the box (cannot instantiate multiple handlers as in Spring) Example: {code} 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://localhost:9080 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 ... {code} h3. Programming style In most complex cases direct programming using {{[org.apache.cxf.jaxrs.ext.logging.atom|http://cxf.apache.org/javadoc/latest/org/apache/cxf/management/web/logging/atom/package-summary.html]}} package may be necessary. In this case AtomPushHandler class is main artifact and Deliverer and Converter interfaces and their implementations are necessary components. Following example: {code} Deliverer d = new WebClientDeliverer("http://somewhere.com/foo/bar"); d = new RetryingDeliverer(d, 300, 60, true); Converter c = new SingleEntryContentConverter(); AtomPushHandler h = new AtomPushHandler(1, c, d); Logger l = Logger.getLogger("org.apache.cxf.jaxrs"); l.setLevel(Level.INFO); l.addHandler(h); {code} is equivalent to Spring configuration: {code} <bean class="org.apache.cxf.management.web.logging.atom.AtomPushBean" init-method="init"> <property name="url" value="http://somewhere.com/foo/bar"/> <property name="logger" value="org.apache.cxf.jaxrs" /> <property name="level" value="INFO" /> <property name="retryPause" value="linear" /> <property name="retryPauseTime" value="60" /> <property name="retryTimeout" value="300" /> </bean> {code} h2. Poll Style [AtomPullServer|http://svn.apache.org/repos/asf/cxf/trunk/rt/management-web/src/main/java/org/apache/cxf/management/web/logging/atom/AtomPullServer.java] acts as an Atom feed endpoint and makes all log events it has accumulated or read from some external storage available for polling. 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. h3. Spring configuration When configuring AtomPullServer endpoints, one can set the 'loggers' property the same way as it is done for AtomPushBeans, for example : {code:xml} <bean class="org.apache.cxf.management.web.logging.atom.AtomPullServer" init-method="init"> <property name="loggers" value=" org.apache.cxf:DEBUG, org.apache.cxf.jaxrs, org.apache.cxf.bus:ERROR, myNamedLogger:INFO" /> <property name="pageSize" value="30"/> </bean> {code} In addition to the 'loggers' property, a 'pageSize' property limiting a number of entries per page to 30 is also set (default is 40). One can have a [ReadWriteLogStorage|http://svn.apache.org/repos/asf/cxf/trunk/rt/management-web/src/main/java/org/apache/cxf/management/web/logging/ReadWriteLogStorage.java] bean injected into AtomPushBean if the log records have to be periodically offloaded from memory and persisted across restarts : {code:xml} <bean id="storage" class="org.apache.cxf.systest.jaxrs.JAXRSLoggingAtomPullSpringTest$Storage"/> <bean class="org.apache.cxf.management.web.logging.atom.AtomPullServer" init-method="init"> <property name="loggers" value="org.apache.cxf.jaxrs" /> <property name="maxInMemorySize" value="400"/> <property name="storage"> <ref bean="storage"/> </property> </bean> {code} 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. Another option is to require a given AtomPullServer to read from the external read-only storage by registering a [ReadableLogStorage|http://svn.apache.org/repos/asf/cxf/trunk/rt/management-web/src/main/java/org/apache/cxf/management/web/logging/ReadableLogStorage.java] 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. 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 : {code:xml} <jaxrs:server id="atomServer" address="/atom"> <jaxrs:serviceBeans> <ref bean="atomPullServer"/> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="feed"/> <ref bean="entry"/> </jaxrs:providers> </jaxrs:server> <bean id="feed" class="org.apache.cxf.jaxrs.provider.AtomFeedProvider"/> <bean id="entry" class="org.apache.cxf.jaxrs.provider.AtomEntryProvider"/> {code} h3. Linking to Atom endpoints from CXF Services page 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 : {code:java} <bean id="atomPullServer" class="org.apache.cxf.management.web.logging.atom.AtomPullServer" init-method="init"> <property name="loggers" value="org.apache.cxf.systest.jaxrs.JAXRSLoggingAtomPullSpringTest$Resource:ALL"/> <property name="bus"> <ref bean="cxf"/> </property> <!-- this is a jaxrs:server/@adrress or jaxws:endpoint/@address of the endpoint generating the log events --> <property name="endpointAddress" value="/resource"/> <!-- this is a jaxrs:server/@address of the endpoint for which this atomPullServer bean is registered as a service bean --> <property name="serverAddress" value="/atom"/> </bean> {code} h1. Filters CXF suports filters. Often it's necessary to pre- or post-process some requests according to a number of requirements. For example, a request like GET /resource?_type=xml is supported by a CXF specific RequestHandler filter which modifies the CXF input Message by updating one of its headers. 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 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. Here are the interface definitions : {code:java} public interface RequestHandler { Response handleRequest(Message inputMessage, ClassResourceInfo resourceClass); } {code} 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. A response filter implementation can get an access to OperationResourceInfo object representing a method to be invoked on a resource class : {code:java} OperationResourceInfo ori = exchange.get(OperationResourceInfo.class); {code} 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. When modifying an input message, one would typically want to replace a message input stream or one of its headers, such as ContentType : {code:java} InputStream is = message.getContent(InputStream.class); message.setContent(new MyFilterInputStream(is)); message.put(Message.ACCEPT_CONTENT_TYPE, "custom/media"); {code} {code:java} public interface ResponseHandler { Response handleResponse(Message outputMessage, OperationResourceInfo invokedOperation, Response response); } {code} 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 : {code:java} // replace an output stream OutputStream os = message.getContent(OutputStream.class); message.setContent(new MyFilterOutputStream(os)); // replace an actual object response.setEntity(new MyWrapper(response.getEntity())) // or using a low-level Message api if needed MessageContentsList objs = MessageContentsList.getContentsList(message); if (objs !== null && objs.size() == 1) { Object responseObj = objs.remove(0); obj.add(new MyWrapper(responseObj)); } {code} Please see [this blog entry|http://sberyozkin.blogspot.com/2008/07/rest-and-soap-united-in-cxf.html] for another example of when response filters can be useful. Multiple request and response handlers are supported. The implementations can be registered like any other types of providers : {code:xml} <beans> <jaxrs:server id="customerService" address="/"> <jaxrs:serviceBeans> <bean class="org.CustomerService" /> </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="authorizationFilter" /> </jaxrs:providers> <bean id="authorizationFilter" class="com.bar.providers.AuthorizationRequestHandler"> <!-- authorization bean properties --> </bean> </jaxrs:server> </beans> {code} h2. Difference between JAXRS filters and CXF interceptors 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. 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. 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 : {code:xml} <beans> <bean id="logInbound" class="org.apache.cxf.interceptor.LoggingInInterceptor"/> <bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/> <jaxrs:server> <jaxrs:inInterceptors> <ref bean="logInbound"/> </jaxrs:inInterceptors> <jaxrs:outInterceptors> <ref bean="logOutbound"/> </jaxrs:outInterceptors> </jaxrs:server> <jaxws:endpoint> <jaxws:inInterceptors> <ref bean="logInbound"/> </jaxws:inInterceptors> <jaxws:outInterceptors> <ref bean="logOutbound"/> </jaxws:outInterceptors> </jaxws:endpoint> </beans> {code} Reusing other CXF interceptors/features such as GZIP handlers can be useful too. h2. Overriding request and response properties Now and then one needs to overwrite various request and response properties like HTTP method or request URI, response headers or status codes. JAX-RS Response may be used to specify custom status and response headers but it might be intrusive to use it in certain cases. Here are some more examples. h3. Overriding HTTP method There are 3 options available : 1. Use a _method system query like > GET /books?_method=RETRIEVE 2. Register a custom RequestHandler filter which will replace the current method value keyed by Message.HTTP_REQUEST_METHOD in a given Message. 3. Specify an HTTP header X-HTTP-Method-Override : > POST /books > X-HTTP-Method-Override : PATCH For example, at the moment http-centric client API does not support arbitrary HTTP verbs except for those supported by Java HTTPUrlConnection. When needed, X-HTTP-Method-Override can be set to overcome this limitation. h3. Overriding request URI 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 : {code:java} String s = m.get(Message.REQUEST_URI); s += "/data/"; m.put(Message.REQUEST_URI, s); {code} 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. h3. Overriding response status code and headers It is assumed here a user prefers not to use explicit Response objects in the application code. 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 : {code:java} public class CustomOutInterceptor extends AbstractOutDatabindingInterceptor { public CustomOutInterceptor() { super(Phase.MARSHAL); } public void handleMessage(Message outMessage) { Map<String, List<String>> headers = (Map<String, List<String>>)outMessage.get(Message.PROTOCOL_HEADERS); // modify headers } {code} 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. 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. h2. Ignoring JAXRS MessageBodyWriters 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 : {code:java} message.getExchange().put("ignore.response.writers", true); {code} h1. Custom invokers *Note* This feature is not available in CXF 2.2.1 Using custom JAXR-RS invokers is yet another way to pre or post process a given invocation. For example, this [invoker|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/CustomJAXRSInvoker.java] 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. Custom invokers can be registered like this : {code:xml} <beans> <jaxrs:server address="/"> <jaxrs:invoker> <bean class="org.apache.cxf.systest.jaxrs.CustomJAXRSInvoker"/> </jaxrs:invoker> </jaxrs:server> </beans> {code} h1. Advanced HTTP 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. h1. Support for Continuations Please see [this blog entry|http://sberyozkin.blogspot.com/2008/12/continuations-in-cxf.html] describing how JAXRS (and indeed) JAXWS services can rely on the CXF Continuations API. Currently, only Jetty based services can rely on this option. h1. Secure JAX-RS services A demo called samples\jax_rs\basic_https shows you how to do communications using HTTPS. Spring Security can be quite easily applied too (see "JAXRS and Spring AOP" section for some general advice). h2. Checking HTTP security headers It is often containers like Tomcat or frameworks like Spring Security which deal with ensuring a current user is authenticated. 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 which will extract a user name and password like this (note it will work only for basic authentication requests only) : {code:java} public class AuthenticationHandler implements RequestHandler { public Response handleRequest(Message m, ClassResourceInfo resourceClass) { AuthorizationPolicy policy = (AuthorizationPolicy)m.get(AuthorizationPolicy.class); policy.getUserName(); policy.getPassword(); // alternatively : // HttpHeaders headers = new HttpHeadersImpl(m); // access the headers as needed return null; } } {code} h2. SecurityManager and IllegalAccessExceptions 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 [catalina.policy|http://tomcat.apache.org/tomcat-5.5-doc/security-manager-howto.html] with the following permission : {code} grant codeBase "file:${catalina.home}/webapps/yourwebapp/lib/cxf.jar" { permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; }; {code} h1. Client API 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. Please see [JAX-RS Client API] for more information. h2. Proxy-based API 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. [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. For example, given these class definitions : {code:java} @Path("/bookstore") public interface BookStore { @GET Books getAllBooks(); @Path("{id}") BookResource getBookSubresource(@PathParam("id") long id) throws NoBookFoundException; } public class BookStoreImpl implements BookStore { public Books getAllBooks() {} public Book getBookSubresource(long id) throws NoBookFoundException {} } public interface BookResource { @GET Book getDescription(); } public class BookResourceImpl implements BookResource { @GET Book getDescription() {} } {code} the following client code retrieves a Book with id '1' and a collection of books: {code:java} BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class); // (1) remote GET call to http://bookstore.com/bookstore Books books = store.getAllBooks(); // (2) no remote call BookResource subresource = store.getBookSubresource(1); // {3} remote GET call to http://bookstore.com/bookstore/1 Book b = subresource.getDescription(); {code} 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. 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. 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. You can make multiple remote invocations on the same proxy (initial or subresource), the current URI and headers are updated properly. 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. h3. Customizing proxies 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 : {code:java} BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class); WebClient.client(proxy).accept("text/xml"); // continue using the proxy {code} You can also check a current set of headers, current and base URIs and a client Response. h3. Converting proxies to Web Clients and vice versa 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 : {code:java} BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class); WebClient client = WebClient.create(proxy); // continue using the http client {code} At any moment of time you can convert an http client into a proxy too : {code:java} BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class); WebClient client = WebClient.create(proxy); BookStore proxy = JAXRSClientFactory.fromClient(client, BookStore.class); {code} h3. Handling exceptions There is a couple of ways you can handle remote exceptions with proxies. 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. 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 : {code:java} BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class); try { proxy.getBook(); } catch(ServerWebApplicationException ex) { Response r = ex.getResponse(); String message = ex.getMessage(); } {code} org.apache.cxf.jaxrs.client.ClientWebApplicationException will be thrown if the exception has occurred for one of two reasons : - 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 - the remote invocation has failed for whatever reasons on the client side, example, no MessageBodyWriter is available. h3. Configuring proxies in Spring 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 : {code:java} SpringBusFactory bf = new SpringBusFactory(); Bus bus = bf.createBus("org/apache/cxf/systest/jaxrs/security/jaxrs-https.xml"); BusFactory.setDefaultBus(bus); // BookStore proxy will get the configuration from Spring BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class); {code} h3. Injecting proxies For injecting proxies via a spring context, use the jaxrs:client element like: {code:xml} <jaxrs:client id="restClient" address="http://localhost:${testutil.ports.BookServerRestSoap}/test/services/rest" serviceClass="org.apache.cxf.systest.jaxrs.BookStoreJaxrsJaxws" inheritHeaders="true"> <jaxrs:headers> <entry key="Accept" value="text/xml"/> </jaxrs:headers> </jaxrs:client> {code} 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 h3. Limitations 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. 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 : {code:java} ResponseReader reader = new ResponseReader(); reader.setEntityClass(Book.class); BookStore bs = JAXRSClientFactory.create("http://localhost:8080/books", BookStore.class, Collections.singletonList(reader)); Response r1 = bs.getBook("123"); Book book = (Book)r1.getEntity(); reader.setEntityClass(Author.class); Response r2 = bs.getBookAuthor("123"); Author book = (Author)r2.getEntity(); {code} h2. HTTP-centric clients 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 : {code:java} WebClient client = WebClient.create("http://books"); Book book = client.path("bookstore/books").accept("text/xml").get(Book.class); {code} You can choose to get an explicit JAX-RS Response instead and check the response code, headers or entity body if any : {code:java} WebClient client = WebClient.create("http://books"); client.path("bookstore/books"); client.type("text/xml").accept("text/xml") Response r = client.post(new Book()); InputStream is = (InputStream)r.getEntity(); Book b = getFromInputStreamUsingJaxb(is); {code} 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 : {code:java} WebClient client = WebClient.create("http://books"); List<Book> books = getBooks(client, 1L, 2L, 3L) private List<Book> getBooks(WebClient client, Long ...ids) { List<Book> books = new ArrayList<Book>(); for (Long id : ids) { books.add(client.path(id).get(Book.class)); client.back(); } return books; } {code} The above code will send requests like "GET http://books/1", "GET http://books/2", etc. 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. h3. Working with explicit collections Example : {code:java} Collection<? extends Book> books = WebClient.getCollection(Book.class); Collection<? extends Book> books = WebClient.postAndGetCollection(new ArrayList<Book>(), Book.class); {code} h3. Handling exceptions 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. h3. Configuring HTTP clients in Spring 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 : {code:xml} <bean id="myJsonProvider" class="org.apache.cxf.jaxrs.provider.JSONProvider" > <property name="supportUnwrapped" value="true" /> <property name="wrapperName" value="nodeName" /> </bean> <util:list id="webClientProviders"> <ref bean="myJsonProvider"/> </util:list> <bean id="myWebClient" class="org.apache.cxf.jaxrs.client.WebClient" factory-method="create"> <constructor-arg type="java.lang.String" value="http://some.base.url.that.responds/" /> <constructor-arg ref="webClientProviders" /> </bean> {code} h2. XML-centric clients 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 : {code:java} WebClient wc = WebClient.create("http://aggregated/data"); XMLSource source = wc.get(XMLSource.class); source.setBuffering(true); Book b1 = source.getNode("/books/book[position() = 1]", Book.class); Book b2 = source.getNode("/books/book[position() = 2]", Book.class); {code} Note that an XMLSource instance can be set to buffer the input stream thus allowing for executing multiple XPath queries. XMlSource can also help with getting the URIs representing the links or XML instances as Strings. h2. Thread Safety 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. One way to 'make' 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. 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 "outofband" headers without synchronizing, ex : {code:java} // get some response headers passed to us 'outofband', which is not thread-safe for a plain proxy : String bookHeader = WebClient.toClient(injectedBookStoreProxy).getHeaders().getFirst("BookHeader"); {code} Final option is to use a 'threadSafe' 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. 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 : {code:java} try { webClient.path("bar") webClient.header("bar", baz); webClient.invoke(...); } finally { // if proxy : WebClient.client(proxy).reset(); webClient.reset(); } {code} Yet another option is to use JAXRSClientFactoryBean and a 'secondsToKeepState' property for creating thread-safe clients - this will instruct clients to clean-up the thread-local state periodically. h2. Configuring Clients at Runtime 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. 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 : {code:java} Book proxy = JAXRSClientFactory.create("http://books", Book.class); ClientConfiguration config = WebClient.getConfig(proxy); HTTPConduit conduit1 = (HTTPConduit)config.getConduit(); WebClient webclient = WebClient.create("http://books"); HTTPConduit conduit2 = (HTTPConduit)WebClient.getConfig(webclient).getConduit(); {code} h2. Configuring HTTP Conduit from Spring There's a number of ways to configure HTTPConduits for proxies and WebClients. 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 : {code:xml} <http:conduit name="http://books:9095/bookstore.*"/> {code} This configuration will affect all proxies and WebClients which have requestURIs starting from 'http://books:9095/bookstore'. Note the trailing '.*' suffix in the name of the http:conduit element. 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. Alternatively you can just do : {code:xml} <http:conduit name="*.http-conduit"/> {code} This configuration will affect all the clients, irrespectively of which URIs the deal with. If you work with proxies then you can have the proxy-specific configuration using the expanded QName notation: {code:xml} <http:conduit name="{http://foo.bar}BookService.http-conduit"/> {code} In this example, 'foo.bar' is a reverse package name of the BookService proxy class. Similarly, for WebClients you can do : {code:xml} <http:conduit name="{http://localhost:8080}WebClient.http-conduit"/> {code} In this example, 'http://localhost:8080' is the base service URI. 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. Also see [this wiki page|http://cwiki.apache.org/CXF20DOC/client-http-transport-including-ssl-support.html] on how to configure HTTPConduits. h1. XPath and XSLT 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. h2. XPath support XPath is supported on the server and client sides with the help of [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. Please see above how http-centric WebClients can use XPath, here is an example for the server side : {code:java} @Path("/root") public class Root { @POST public void post(XMLSource source) { String value = source.getProperty("/books/book/@name"); } } {code} Users have an option to hide XPath expressions, by registering an [XPathProvider|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/XPathProvider.java], either on client or server sides. For example : {code:java} XPathProvider provider = new XPathProvider(); provider.setGlobalExpression("/books/book[position() = 1]"); WebClient wc = WebClient.create("http://aggregated/data", Collections.singletonList(provider)); Book b = wc.get(Book.class); {code} h2. XSLT support XSLT is currently supported by [XSLTJaxbProvider|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/XSLTJaxbProvider.java]. 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. 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. 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. For example, given this resource method definition : {code:java} @Path("/root") public class Root { @GET @Path("{id}") public Book get(@PathParam("id") String id, @QueryParam("name") String name) { return getBook(id, name); } } {code} an XSLT template processing the JAXB-driven serialization of a Book instance will have parameters with name 'id' and 'name' injected. 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 : {code:java} WebClient client = WebClient.create("http://books"); client.path("/store/1").get(); {code} 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 : {code:java} WebClient client = WebClient.create("http://books"); client.path("/store/{id}", 1).get(); {code} h1. Redirection CXF 2.2.5 supports redirecting to other servlet resources for a given request and/or response be completed. h2. With RequestDispatcherProvider [RequestDispatcherProvider|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/provider/RequestDispatcherProvider.java] 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. 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. Please see this [beans.xml|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_dispatch/WEB-INF/beans.xml]. 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. 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. 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. h2. With CXFServlet Please see the "Redirection" section on the [Servlet Transport|http://cwiki.apache.org/confluence/display/CXF20DOC/Servlet+Transport] page. Note that both CXFServlet and JAXRS RequestDispatcher provider can work together effectively on executing the redirection requests as described at that page. 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 : {code:xml} <bean id="dispatchProvider" class="org.apache.cxf.jaxrs.provider.RequestDispatcherProvider"> <property name="dispatcherName" value="jsp"/> <property name="resourcePath" value="/WEB-INF/jsp/test.jsp"/> <property name="scope" value="request"/> </bean> {code} 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". h2. Custom Redirection 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. h1. Model-View-Controller support h2. XSLT Please see [this blog entry|http://sberyozkin.blogspot.com/2009/05/mvc-xml-way-with-cxf-jax-rs.html] on how XSLTJaxbProvider can be used to generate complex (X)HTML views. h2. JSP 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 [beans.xml|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_dispatch/WEB-INF/beans.xml]. 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. RequestDispatcherProvider sets the following parameters : - 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. - All the path, query and matrix parameters which have been initialized during the method execution - "absolute.path", "base.path" and "relative.path" obtained from the current UriInfo h1. Support for Multiparts 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. h2. Reading attachments Individual parts can be mapped to StreamSource, InputStream, DataSource or custom Java types for which message body readers are available. For example : {code:java} @POST @Path("/books/jaxbjson") @Produces("text/xml") public Response addBookJaxbJson( @Multipart(value = "rootPart", type = "text/xml") Book2 b1, @Multipart(value = "book2", type = "application/json") Book b2) throws Exception { } {code} Note that in this example it's expected that the root part named 'rootPart' is a text-xml Book representation, while a part named 'book2' is a Book JSON sequence. All atachment parts can be accessed as a list of [Attachment|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/Attachment.java] with Attachment making it easy to deal with a given part : {code:java} @POST public void addAttachments(List<Attachment> atts) throws Exception { } {code} For example, Attachment class can be used to get to a [Content-Disposition|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/ContentDisposition.java] header, when dealing with the form submission of files. Similarly, the whole request body can be represented as a [MultipartBody|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/multipart/MultipartBody.java] : {code:java} @POST public void addAttachments(MultipartBody body) throws Exception { body.getAllAtachments(); body.getRootAttachment(); } {code} 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 : {code:java} @POST @Consumes("multipart/form-data") public void addForm1(@FormParam("name") String title, @FormParam("id") Long id) throws Exception { } @POST @Consumes("multipart/form-data") public void addForm2(@FormParam("") BookBean book) throws Exception { } @POST @Consumes("multipart/form-data") public void addForm3(MultivaluedMap<String, String> formData) throws Exception { } {code} 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 : {code:java} @POST public void addAttachments(MultipartBody body) throws Exception { Book book = body.getAttachmentObject("bookPart", Book.class); } @POST public void addAttachments(List<Attachment> attachments) throws Exception { for (Attachment attachment : attachments) { Book book = attachment.getObject(Book.class); } } {code} When a user code has [MessageContext|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/MessageContext.java] injected, [AttachmentUtils|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/utils/multipart/AttachmentUtils.java] can also be used by the application code. Please see these [test resource class|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/MultipartStore.java] and [blog entry|http://sberyozkin.blogspot.com/2009/02/multiparts-in-cxf-jaxrs.html] for more examples. h3. Forms and multiparts The [Forms in HTML documents|http://www.w3.org/TR/html401/interact/forms.html] recommendation [suggests|http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2] that multipart/form-data requests should mainly be used to upload files. 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. 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. For example this [request|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJson] can be handled by a method with the following signature : {code:java} @POST @Path("/books/jsonform") @Consumes("multipart/form-data") public Response addBookJsonFromForm(Book b1) {...} {code} Similarly, this [request|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJsonJaxb] can be handled by a method with the following signature : {code:java} @POST @Path("/books/jsonjaxbform") @Consumes("multipart/form-data") public Response addBookJaxbJsonForm(@Multipart("jsonPart") Book b1, @Multipart("bookXML") Book b2) {} {code} 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. When dealing with multiple parts one can avoid using @Multipart and just use List, ex, List\<Atachment\>, List\<Book\>, etc. Finally, multipart/form-data requests with multiple files (file uploads) can be supported too. For example, this [request|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/attachmentFormJsonFiles] can be handled by a method with the signature like : {code:java} @POST @Path("/books/filesform") @Produces("text/xml") @Consumes("multipart/form-data") public Response addBookFilesForm(@Multipart("owner") String name, @Multipart("files") List<Book> books) {} {code} 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<Attachment> 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. 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. Please note that using JAX-RS FormParams is recommended for dealing with plain application/www-url-encoded submissions consisting of name/value pairs only. h2. Writing attachments Starting from 2.2.4 it is also possible to write attachments to the output stream, both on the client and server sides. On the server side it is sufficient to update the @Produces value for a given method : {code:java} public class Resource { private List<Book> books; @Produces("multipart/mixed;type=text/xml") public List<Book> getBooksAsMultipart() { return booksList; } @Produces("multipart/mixed;type=text/xml") public Book getBookAsMultipart() { return booksList; } } {code} 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". 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 : {code:java} public class Resource { private List<Book> books; @Produces("multipart/mixed") public Map<String, Object> getBooks() { Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("text/xml", new JaxbBook()); map.put("application/json", new JSONBook()); map.put("application/octet-stream", imageInputStream); return map; } @Produces("multipart/mixed") public MultipartBody getBooks2() { List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("root", "application/json", new JSONBook())); atts.add(new Attachment("image", "application/octet-stream", getImageInputStream())); return new MultipartBody(atts, true); } } {code} 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 . In getBooks2() one can control the content ids of individual parts. You can also control the contentId and the media type of the root attachment by using a Multipart annotation : {code:java} public class Resource { @Produces("multipart/form-data") @Multipart(value = "root", type = "application/octet-stream") public File testGetImageFromForm() { return getClass().getResource("image.png").getFile(); } } {code} One can also have lists or maps of DataHandler, DataSource, Attachment, byte arrays or InputStreams handled as multiparts. On the client side multiparts can be written the same way. For example : {code:java} WebClient client = WebClient.create("http://books"); client.type("multipart/mixed").accept("multipart/mixed"); List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("root", "application/json", new JSONBook())); atts.add(new Attachment("image", "application/octet-stream", getImageInputStream())); List<Attachment> atts = client.postAndGetCollection(atts, Attachment.class); {code} Note a new WebClient.postAndGetCollection which can be used for a type-safe retrieval of collections. A similar WebClient.getCollection has also been added. 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 : {code:java} public class Resource { @Produces("multipart/mixed") @Consumes("multipart/form-data") @Multipart(value = "root", type = "application/octet-stream") public File postGetFile(@Multipart(value = "root2", type = "application/octet-stream") File file) {} } {code} 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. h2. Uploading files At the moment the only way to upload a file is to use a MultipartBody, Attachment or File : {code:java} WebClient client = WebClient.create("http://books"); client.type("multipart/form-data"); ContentDisposition cd = new ContentDisposition("attachment;filename=image.jpg"); Attachment att = new Attachment("root", imageInputStream, cd); client.post(new MultipartBody(att)); // or just post the attachment if it's a single part request only client.post(att); // or just use a file client.post(getClass().getResource("image.png").getFile()); {code} Using File provides a simpler way as the runtime can figure out how to create a ContentDisposition from a File. h2. Reading large attachments One can use the following properties to set up folder and threshold values when dealing with large attachments : {code:xml} <beans> <jaxrs:server id="bookstore1"> <jaxrs:properties> <entry key="attachment-directory" value="/temp/bookstore1"/> <!-- 200K--> <entry key="attachment-memory-threshold" value="404800"/> </jaxrs:properties> </jaxrs:server> </beans> {code} Note that such properties can be set up on a per-endpoint basis. Alternatively, you might want to set the following system properties which will apply to all endpoints : > -Dorg.apache.cxf.io.CachedOutputStream.Threshold=102400 and > -Dorg.apache.cxf.io.CachedOutputStream.OutputDirectory=/temp h2. XOP support CXF JAXRS clients and endpoints can support [XML-binary Optimized Packaging (XOP)|http://www.w3.org/TR/xop10/]. 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. If you'd like to experiment with XOP then you need to set an "mtom-enabled" property on CXF jaxrs endpoints and clients. Please see [JAXRSMultipartTest|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSMultipartTest.java] (testXopWebClient) and [MultipartStore|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/MultipartStore.java] (addBookXop) for more details. h1. Service listings and WADL support CXF JAX-RS now supports the auto-generation of [WADL|http://www.w3.org/Submission/wadl] for JAX-RS endpoints. 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. 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 'service-list-path' servlet parameter, ex : > 'service-list-path' = '/listings' 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. For example, given {code:xml} Base address : 'http://localhost:8080' WAR name : 'store' CXFServlet : '/books/*' jaxrs:server/@address = '/orders' jaxrs:server/@staticSubresourceResoulution = 'true' {code} and 2 root resource classes registered with this endpoint, say {code:java} @Path("/fiction") public class FictionBookOrders { } @Path("/sport") public class SportBookOrders { } {code} then > http://localhost:8080/store/books/orders?_wadl will give you the description of all the root resource classes registered with a given jaxrs:server endpoint, including all the subresources. While > http://localhost:8080/store/books/orders/fiction?_wadl > http://localhost:8080/store/books/orders/sport?_wadl will give you all the info for FictionBookOrders and SportBookOrders respectively. If you have many jaxrs:endpoints then visiting > http://localhost:8080/store/books > http://localhost:8080/store/books/services will let you see all the WADL links. Note that the media type for a ?_wadl response is set to 'application/vnd.sun.wadl+xml' which is something Firefox does not really 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 '?_wadl&_type=xml' will ensure a WADL generator will see Accept being set set to 'application/xml'. h2. Documenting resource classes and methods in WADL WADL documents can include [doc|http://www.w3.org/Submission/wadl/#x3-80002.3] fragments. Users may want to use [Description|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/Description.java] annotations which can be attached to resource classes and methods. h2. Custom WADL providers One can register a custom WADLGenerator as a jaxrs:provider. The custom generator can extend the default org.apache.cxf.jaxrs.model.wadl.WADLGenerator or register a default one with one of the following properties set. - wadlNamespace : default is "http://wadl.dev.java.net/2009/02", the earlier one is "http://research.sun.com/wadl/2006/10". - 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. - 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"). h3. Representing external schemas and non JAXB types By default, the WADL grammar section will be properly generated if resource methods accept or return JAXB types. 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) : {code:java} WadlGenerator wg = new WadlGenerator(); wg.setSchemaLocations(Collections.singletonList("classpath:/book.xsd")); {code} 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) TODO : add ignoreImports flag so that users can list root and imported schemas in "schemaLocations" and have them all inlined. 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 : {code:xml} <wadl:grammars> <wadl:include href="http://books.xsd"/> </wadl:grammars> {code} Note that "schemaLocations" and "externalLinks" properties differ in that the schemas referenced by the former one are inlined. 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 : {code:xml} <!-- 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 --> <representation mediaType="application/xml" element="prefix1:thebook2"/> {code} If no JAXB is used then you can attach an [XmlName|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/xml/XMLName.java] annotation to method input or output types. Alternatively, you can register an instance of [ElementQNameResolver|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/model/wadl/ElementQNameResolver.java] with the WADLGenerator which will be used for creating wadl:representation/@element values. h1. Hiding links to JAXRS endpoints from the services page 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. h1. Code Generation h2. Generating the client code at runtime 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. 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. Here is how to get the archive programmatically : {code:java} WebClient wc = WebClient.create("http://localhost:9080/petstore"); XMLSource source = wc.query("_code").query("_os", getOs()).get(XMLSource.class); String link = source.getValue("ns:html/ns:body/ns:ul/ns:a/@href", Collections.singletonMap("ns","http://www.w3.org/1999/xhtml")); // download a zip file WebClient wcZip = WebClient.create(link); InputStream is = wcZip.accept("application/zip").get(InputStream.class); // unzip and compile it {code} Please see a [testPetStore|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerResourceCreatedSpringProviderTest.java] test for more details. h1. Configuring JAX-RS services h2. Configuring JAX-RS services programmatically {code:java} JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setResourceClasses(CustomerService.class); sf.setAddress("http://localhost:9000/"); sf.create(); {code} A couple of things to note: * The JAXRSServerFactoryBean creates a Server inside CXF which starts listening for requests on the URL specified. * 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: {code:java} sf.setResourceProvider(BookStore.class, new SingletonResourceProvider(new BookStore())); {code} * 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: {code:java} JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); CustomerService cs = new CustomerService(); sf.setServiceBeans(cs); sf.setAddress("http://localhost:9080/"); sf.create(); {code} h2. Configuring JAX-RS endpoints programmatically without Spring 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 : {code:java} JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setResourceClasses(CustomerService.class); sf.setResourceProvider(CustomerService.class, new SingletonResourceProvider(new CustomerService())); sf.setAddress("http://localhost:9000/"); BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class); JAXRSBindingFactory factory = new JAXRSBindingFactory(); factory.setBus(sf.getBus()); manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory); sf.create(); {code} h2. Configuring JAX-RS clients programmatically without Spring Example : {code:java} JAXRSClientFactoryBean sf = new JAXRSClientFactoryBean(); sf.setResourceClass(CustomerService.class); sf.setAddress("http://localhost:9000/"); BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class); JAXRSBindingFactory factory = new JAXRSBindingFactory(); factory.setBus(sf.getBus()); manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory); CustomerService service = sf.create(CustomerService.class); {code} h2. Configuring JAX-RS services in container with Spring configuration file. h3. web.xml In web.xml one needs to register one or more CXFServlet(s) and link to an application context configuration. h4. Using Spring ContextLoaderListener {code:xml} <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/beans.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <servlet> <servlet-name>CXFServlet</servlet-name> <display-name>CXF Servlet</display-name> <servlet-class> org.apache.cxf.transport.servlet.CXFServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app> {code} The application context configuration is shared between all the CXFServlets h4. Using CXFServlet init parameters {code:xml} <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>CXFServlet1</servlet-name> <display-name>CXF Servlet1</display-name> <servlet-class> org.apache.cxf.transport.servlet.CXFServlet </servlet-class> <init-param> <param-name>config-location</param-name> <param-value>/WEB-INF/beans1.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>CXFServlet2</servlet-name> <display-name>CXF Servlet2</display-name> <servlet-class> org.apache.cxf.transport.servlet.CXFServlet </servlet-class> <init-param> <param-name>config-location</param-name> <param-value>/WEB-INF/beans2.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet1</servlet-name> <url-pattern>/1/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CXFServlet2</servlet-name> <url-pattern>/2/*</url-pattern> </servlet-mapping> </web-app> {code} Each CXFServlet can get a unique application context configuration. Note, no Spring ContextLoaderListener is registered in web.xml in this case. h3. beans.xml {code:xml} <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" 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"> <!-- do not use import statements if CXFServlet init parameters link to this beans.xml --> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <jaxrs:server id="customerService" address="/service1"> <jaxrs:serviceBeans> <ref bean="customerBean" /> </jaxrs:serviceBeans> </jaxrs:server> <bean id="customerBean" class="demo.jaxrs.server.CustomerService" /> </beans> {code} h2. Configuring JAX-RS services in container without Spring If you prefer, you can register JAX-RS endpoints without depending on Spring with the help of CXFNonSpringJaxrsServlet : {code:xml} <servlet> <servlet-name>CXFServlet</servlet-name> <display-name>CXF Servlet</display-name> <servlet-class> org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet </servlet-class> <init-param> <param-name>jaxrs.serviceClasses</param-name> <param-value> org.apache.cxf.systest.jaxrs.BookStore1 org.apache.cxf.systest.jaxrs.BookStore2 </param-value> </init-param> <init-param> <param-name>jaxrs.providers</param-name> <param-value> org.apache.cxf.systest.jaxrs.BookStoreProvider1 org.apache.cxf.systest.jaxrs.BookStoreProvider2 </param-value> </init-param> <!-- enables schema validation --> <init-param> <param-name>jaxrs.schemaLocations</param-name> <param-value> classpath:/WEB-INF/schemas/schema1.xsd classpath:/WEB-INF/schemas/schema2.xsd </param-value> </init-param> <!-- registers CXF in interceptors --> <init-param> <param-name>jaxrs.inInterceptors</param-name> <param-value> org.apache.cxf.systest.jaxrs.CustomInInterceptor </param-value> </init-param> <!-- registers CXF out interceptors --> <init-param> <param-name>jaxrs.outInterceptors</param-name> <param-value> org.apache.cxf.systest.jaxrs.CustomOutInterceptor </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> {code} 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). By default, the endpoint address is "/". One can provide a more specific value using a "jaxrs.address" parameter. A more portable way to register resource classes and providers with CXFNonSpringJaxrsServlet is to use a JAX-RS Application [implementation|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookApplication.java] : {code:xml} <servlet> <servlet-name>CXFServlet</servlet-name> <display-name>CXF Servlet</display-name> <servlet-class> org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet </servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value> org.apache.cxf.systest.jaxrs.BookApplication </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> {code} 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. h3. Attaching JAXRS endpoints to an existing Jetty server Here is a code fragment showing how it can be done with the help of CxfNonSpringJaxrsServlet : {code:java} CXFNonSpringServlet cxf = new CXFNonSpringJaxrsServlet(); ... ServletHolder servlet = new ServletHolder(cxf); servlet.setInitParameter("javax.ws.rs.Application", "com.acme.MyServiceImpl"); servlet.setName("services"); servlet.setForcedPath("services"); root.addServlet(servlet, "/*"); {code} h2. Configuring JAX-RS services programmatically with Spring configuration file. When using Spring explicitly in your code, you may want to follow this example : {code:java} ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"/org/apache/cxf/jaxrs/spring/servers.xml"}); // 'simple' is the id of the jaxrs server bean JAXRSServerFactoryBean sfb = (JAXRSServerFactoryBean)ctx.getBean("simple"); sfb.create(); {code} Note that in in this case your Spring configuration file should import cxf-extension-http-jetty.xml instead of cxf-servlet.xml : {code:xml} <!-- <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> --> <import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml" /> {code} h2. Lifecycle management h3. From Spring The singleton scope is applied to all service beans which are injected like this : {code:xml} <beans> <jaxrs:server id="customerService" address="/service1"> <jaxrs:serviceBeans> <ref bean="customerBean" /> </jaxrs:serviceBeans> </jaxrs:server> <bean id="customerBean" class="demo.jaxrs.server.CustomerService" /> </beans> {code} You can support prototypes by either using a beanNames attribute or schemaFactories element : {code:xml} <beans> <jaxrs:server id="customerService" address="/service1" beanNames="customerBean2 customerBean3"> <jaxrs:serviceBeans> <ref bean="customerBean" /> </jaxrs:serviceBeans> <jaxrs:serviceFactories> <ref bean="sfactory1" /> <ref bean="sfactory2" /> </jaxrs:serviceFactories> </jaxrs:server> <bean id="customerBean" class="demo.jaxrs.server.CustomerService" /> <bean id="customerBean2" class="demo.jaxrs.server.CustomerService2" scope="prototype"/> <bean id="customerBean3" class="demo.jaxrs.server.CustomerService3" scope="prototype"/> <bean id="sfactory1" class="org.apache.cxf.jaxrs.spring.SpringResourceFactory"> <property name="beanName" value="customerBean4"/> </bean> <bean id="sfactory2" class="org.apache.cxf.jaxrs.spring.SpringResourceFactory"> <property name="beanName" value="customerBean5"/> </bean> <bean id="customerBean4" class="demo.jaxrs.server.CustomerService4" scope="prototype"/> <bean id="customerBean5" class="demo.jaxrs.server.CustomerService5" scope="prototype"/> </beans> {code} h3. With CXFNonSpringJaxrsServlet 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. CXFNonSpringJaxrsServlet can support singleton scopes for classes with constructors expecting JAXRS contexts, at the moment it can only inject ServletContext or ServletConfig contexts : {code:java} @Path("/") public class SingletonResourceClass { public SingletonResourceClass(@Context ServletContext context, @Context ServletConfig context2) {} } {code} h3. Programmatically {code:java} JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setResourceClass(CustomerService.class); sf.setResourceProvider(new SingletonResourceProvider(new CustomerService())); sf.setResourceClass(CustomerService2.class); sf.setResourceProvider(new PerRequestResourceProvider(CustomerService.class)); {code} h3. PostConstruct and PreDestroy Bean methods annotated with @PostConstruct and @PreDestroy annotations will be called as expected by the scope rules. 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. 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". You can also register a custom Spring resource factory by extending org.apache.cxf.jaxrs.spring.SpringResourceFactory or providing a more sophisticated implementation. h2. Locating custom resources in web applications 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. 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'. h2. Multiple endpoints and resource classes 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. h2. How the request URI is matched against a given jaxrs endpoint There's a number of variables involved here. Lets assume you have a web application called 'rest'. CXFServlet's url-pattern is "/test/*". Finally, jaxrs:server's address is "/bar". 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 \@Path("/") should be available, in the latter case - at least \@Path("/") or more specific @Path("/baz"). The same requirement can be expressed by having a CXFServlet with "/*" and jaxrs:server with "/test/bar". When both CXFServlet and jaxrs:server use "/" then it's a root resource class which should provide a \@Path with at least "/test/bar" for the above requests be matched. 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. h2. Combining JAX-WS and JAX-RS 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 : {code:xml} <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:jaxws="http://cxf.apache.org/jaxws" 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"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <!-- JAX-RS --> <jaxrs:server id="customerService" address="/"> <jaxrs:serviceBeans> <ref bean="customerService" /> </jaxrs:serviceBeans> </jaxrs:server> <!-- JAX-WS --> <jaxws:endpoint implementor="#customerService" address="/CustomerWorld" wsdlLocation="..."/> <bean id="customerService" class="demo.jaxrs.server.CustomerService" /> </beans> {code} 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. 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 : {code:java} public class CustomerService { public void doIt(String a, String b) {...}; } {code} 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 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 : {code:java} @Path("/customers/{a}") public class CustomerService { public void doIt(@PathParam("a") String a, String b) {...}; } {code} Note that CXF Continuations API is supported for both JAXWS and JAXRS services. h3. Dealing with contexts 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 : {code:java} @Path("/customers") @WebService public class CustomerService { @Resource WebServiceContext jaxwsContext; @Resource MessageContext jaxrsContext; @WebMethod @POST public void doIt(String b) { isUserInRole(); }; private void isUserInRole() throws WebApplicationException { if (jaxwsContext.getSecurityContext() != null) { // soap invocation jaxwsContext.getSecurityContext().isUserInRole(theRole); } else { // http-only jaxrs one jaxrsContext.getSecurityContext().isUserInRole(theRole); } } } {code} 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. 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. Using individual contexts like JAXRS SecurityContext might be less attractive : {code:java} @WebService public class CustomerService { @Resource WebServiceContext jaxwsContext; // @Resource can be applied too @Context SecurityContext jaxrsSecurityContext; } {code} 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. Note that if you do not share the same service methods between JAXRS and JAXWS invocations then you can directly access corresponding contexts : {code:java} @Path("/customers") @WebService public class CustomerService { @Resource WebServiceContext jaxwsContext; @Resource MessageContext jaxrsContext; @WebMethod public void doItSoap(String b) { isUserInRole(jaxwsContext.getSecurityContext().getPrincipal()); }; @POST public void doItSoap(String b) { isUserInRole(jaxwsContext.getSecurityContext().getPrincipal()); } private void isUserInRole(Principal p) throws WebApplicationException { ... } } {code} 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. h2. JAX-RS and Spring AOP CXF JAX-RS is capable of working with AOP interceptors applied to resource classes from Spring. For example : {code:xml} <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"> <import resource="classpath:META-INF/cxf/cxf.xml"/> <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/> <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/> <jaxrs:server id="bookservice" address="/"> <jaxrs:serviceBeans> <ref bean="bookstore"/> <ref bean="bookstoreInterface"/> </jaxrs:serviceBeans> </jaxrs:server> <bean id="bookstore" class="org.apache.cxf.systest.jaxrs.BookStore"/> <bean id="bookstoreInterface" class="org.apache.cxf.systest.jaxrs.BookStoreWithInterface"/> <aop:config> <aop:aspect id="loggingAspect" ref="simpleLogger"> <aop:before method="logBefore" pointcut="execution(* org.apache.cxf.systest.jaxrs.BookStore*.*(..))"/> <aop:after-returning method="logAfter" pointcut="execution(* org.apache.cxf.systest.jaxrs.BookStore*.*(..))"/> </aop:aspect> </aop:config> <bean id="simpleLogger" class="org.apache.cxf.systest.jaxrs.SimpleLoggingAspect"/> </beans> {code} 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. For example, here's how org.apache.cxf.systest.jaxrs.BookStoreWithInterface looks like : {code:java} public interface BookInterface { @GET @Path("/thosebooks/{bookId}/") @Produces("application/xml") Book getThatBook(Long id) throws BookNotFoundFault; } public class BookStoreWithInterface extends BookStoreStorage implements BookInterface { public Book getThatBook(@PathParam("bookId") Long id) throws BookNotFoundFault { return doGetBook(id); } @Path("/thebook") public Book getTheBook(@PathParam("bookId") Long id) throws BookNotFoundFault { return doGetBook(id); } } {code} 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. 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 : {code:xml} <aop:config proxy-target-class="true"/> {code} h1. Oneway invocations 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. h1. JMS Support 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 : {code:xml} <jaxrs:server serviceName="s:BookService" transportId="http://cxf.apache.org/transports/jms" address="/"> <jaxrs:serviceBeans> <bean class="org.apache.cxf.systest.jaxrs.JMSBookStore"/> </jaxrs:serviceBeans> </jaxrs:server> {code} Additionally, JMS queue or topic [configuration|http://cxf.apache.org/docs/using-the-jmsconfigfeature.html] needs to be done, for example, please see this [beans.xml|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/jms_server_config.xml]. Please note how a serviceName attribute is used to specify a service QName for a jaxrs endpoint (default is \{http://reverse.package.name}ServiceClassName), this service name is used to configure a jms destination. Here is the actual [test|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSJmsTest.java]. Here are JMS properties which can help with matching a required method on the JAXRS endpoint : - "Content-Type" : default is "text/xml" - "Accept" : default is "*/*" - "OnewayMessage" : default is "false" - "org.apache.cxf.message.Message.REQUEST_URI" : default is "/" - "org.apache.cxf.message.Message.HTTP_REQUEST_METHOD" : default is "POST" 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. 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 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. 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 [ProtocolHeaders|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ProtocolHeaders.java] context which will let you get either HTTP or JMS headers. h1. RESTful services without annotations 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. 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. User model schema type is described in the [jaxrs.xsd|http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/resources/schemas/jaxrs.xsd]. 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. 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. 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. Starting from CXF 2.3.2-SNAPSHOT a "oneway" attribute can also be applied to individual operations. Here is an example : {code:xml} <model xmlns="http://cxf.apache.org/jaxrs"> <resource name="org.apache.cxf.systest.jaxrs.BookStoreNoAnnotations" path="bookstore" produces="application/json" consumes="application/json"> <operation name="getBook" verb="GET" path="/books/{id}" produces="application/xml"> <param name="id" type="PATH"/> </operation> <operation name="getBookChapter" path="/books/{id}/chapter"> <param name="id" type="PATH"/> </operation> <operation name="updateBook" verb="PUT"> <param name="book" type="REQUEST_BODY"/> </operation> </resource> <resource name="org.apache.cxf.systest.jaxrs.ChapterNoAnnotations"> <operation name="getItself" verb="GET"/> <operation name="updateChapter" verb="PUT" consumes="application/xml"> <param name="content" type="REQUEST_BODY"/> </operation> </resource> </model> {code} 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. The runtime will introspect the [org.apache.cxf.systest.jaxrs.BookStoreNoAnnotations|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookStoreNoAnnotations.java] class and check the return types for both 'getBook' and 'getBookChapter' methods. BookStoreNoAnnotations.getBookChapter() method's return type is [org.apache.cxf.systest.jaxrs.ChapterNoAnnotations|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/ChapterNoAnnotations.java] 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. 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. 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"). Please also see this [model file|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/resources2.xml] 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. h2. Configuration 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. Please see this [bean|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs/WEB-INF/beans.xml] Spring configuration file, look at jaxrs server beans with 'bookservice6' and 'bookservice7' names. 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. 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. Please have a look at [this Spring bean|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_proxy/WEB-INF/beans.xml]. 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. You can also register a model programmatically, for example : {code:java} JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); sf.setAddress("http://localhost:9080/"); String modelRef = "classpath:/org/apache/cxf/systest/jaxrs/resources/resources2.xml"; sf.setModelRef(modelRef); // or if you have interface classes described in the model already loaded, ex : OSGI // sf.setModelRefWithServiceClass(modelRef, BookStoreNoAnnotationsInterface.class); // register an actual bean only if the model describes interfaces sf.setServiceBeans(new BookStoreNoAnnotationsImpl()); {code} Please also see [this system test|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerUserResourceTest.java] for the example of how model beans like UserResource can be created and registered programmatically. Similarly, you can register a user model on the client side, either from jaxrs:client or programmatically, example : {code:java} JAXRSClientFactoryBean cf = new JAXRSClientFactoryBean(); cf.setAddress("http://localhost:9080/"); String modelRef = "classpath:/org/apache/cxf/systest/jaxrs/resources/resources2.xml"; sf.setModelRef(modelRef); BookStoreNoAnnotations proxy = cf.create(BookStoreNoAnnotations.class); {code} 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 [web.xml|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_non_spring/WEB-INF/web.xml]. See CXFServlet3 and CXFServlet4 servlet declarations. Note that CXFServlet4 registers a model containing interfaces so it also registers a BookStoreNoAnnotationsImpl service class. The workaround is to create a custom servlet : {code:java} public class JAXRSUserModelServlet extends CXFNonSpringJaxrsServlet { @Override public void loadBus(ServletConfig servletConfig) throws ServletException { super.loadBus(servletConfig); JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean(); String address = servletConfig.getInitParameter(SERVICE_ADDRESS_PARAM); //jaxrs.address if (address == null) { address = "/"; } sf.setAddress(address); // modelRef needs to start from 'classpath:', ex 'classpath:/WEB-INF/models/model1.xml String modelRef = servletConfig.getInitParameter("user.model"); sf.setModelRef(modelRef); sf.create(); } {code} h1. Integration with Distributed OSGi Distributed OSGi RI is a CXF [subproject|http://cxf.apache.org/distributed-osgi.html]. DOSGi mandates how registered Java interfaces can be exposed and consumed as remote services. DOSGi single and multi bundle distributions contain all the OSGI bundles required for a CXF endpoint be successfully published. 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. Please see [DOSGI Reference page|http://cxf.apache.org/distributed-osgi-reference.html#DistributedOSGiReference-ServiceProviderproperties] ('org.apache.cxf.rs' properties) and a [greeter_rest|http://svn.apache.org/repos/asf/cxf/dosgi/trunk/samples/greeter_rest/] sample for more information. Note that this demo can be run exactly as a SOAP-based [greeter|http://cxf.apache.org/distributed-osgi-greeter-demo-walkthrough.html] demo as it registers and consumes a similar (but) JAX-RS annotated [GreeterService|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]. In addition, this demo shows how one can register and consume a given interface ([GreeterService2|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]) without using explicit JAX-RS annotations but providing an out-of-band [user model description|http://svn.apache.org/repos/asf/cxf/dosgi/trunk/samples/greeter_rest/interface/src/main/resources/OSGI-INF/cxf/jaxrs/GreeterService2-model.xml]. h1. How to contribute 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. Please check this [list|http://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&mode=hide&pid=12310511&sorter/order=DESC&sorter/field=priority&resolution=-1&component=12311911] and see if you are interested in fixing one of the issues. If you decide to go ahead then the fastest way to start is to * do the fast trunk build using 'mvn install -Pfastinstall' * setup the workspace 'mvn -Psetup.eclipse' which will create a workspace in a 'workspace' folder, next to 'trunk' * import cxf modules from the trunk into the workspace and start working with the cxf-frontend-jaxrs module 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 : > mvn install



Table of Contents

Introduction

JAX-RS: Java API for RESTful Web Services is a Java programming language API that provides support in creating web services according to the Representational State Transfer (REST) architectural style.

CXF supports JAX-RS 2.1 (JSR-370), 2.0 (JSR-339) and 1.1 (JSR-311).

CXF 3.2.0 supports JAX-RS 2.1. All existing JAX-RS 2.0 and 1.1 applications can be run with CXF 3.2.0.

CXF 3.1.x and 3.0.x support JAX-RS 2.0.  Existing JAX-RS 1.1 applications can be run with CXF 3.1.x/3.0.x.

See below for more information about the compliance.

JAX-RS related demos are located under the samples/jax_rs directory.

Outstanding JAX-RS JIRA issues can be found here.

JAX-RS Compliance

Anchor
2_0_FINAL
2_0_FINAL

2.1 Final

CXF 3.2.0 has been updated to implement the JAX-RS 2.1 API’s as completely as possible.

If another TCK licensee that uses CXF’s JAX-RS 2.1 implementation in their products finds issues with CXF’s compliance, we are more than happy to fix bugs that are raised.

2.0 Final

CXF 3.1.x and CXF 3.0.x have been updated to implement the JAX-RS 2.0 API’s as completely as possible without access to the final JAX-RS 2.0 TCK.
We have done extensive testing with JAX-RS 2.0 user applications, samples, and the preliminary TCK to make sure CXF’s implementation is as complete and compatible as we can make it.
CXF makes and will continue making the best possible effort to have JAX-RS 2.0 and new JAX-RS version implementations technically complete and offering an environment for running the portable JAX-RS 2.0 applications.
If the final 2.0 TCK is made available to Apache, we will make sure CXF is updated to pass.
If another TCK licensee that uses CXF’s JAX-RS 2.0 implementation in their products finds issues with CXF’s compliance, we are more than happy to fix bugs that are raised.

1.1

Apache CXF 2.6.x passes the final JAX-RS 1.1 TCK and is formally 1.1 compliant.

Please consult the TomEE documentation on the support of Java EE related JAX-RS 1.1 options in its Apache CXF-based JAX-RS runtime.

CXF 2.7.x and CXF 3.0.0 will fully support and run JAX-RS 1.1 applications but will not pass the JAX-RS 1.1 TCK Signature tests due to

CXF 2.7.x and CXF 3.0.0 depending on 2.0-m10 and 2.0 final versions of JAX-RS 2.0 API.


Project setup and configuration

Migration

From JAX-RS 2.0 to JAX-RS 2.1

JAX-RS 2.1 is backward compatible with JAX-RS 2.0. Please see JAX-RS Basics for more information about JAX-RS 2.1.

All the existing JAX-RS 2.0 and 1.1 applications will run on CXF 3.2.0.

From JAX-RS 1.1 to 2.0

JAX-RS 2.0 is backward compatible with JAX-RS 1.1. Please see JAX-RS Basics for more information about JAX-RS 2.0.

CXF 3.1.x and CXF 3.0.x are expected to support the existing JAX-RS 1.1 applications.

From CXF 2.7.x to CXF 3.0.x or 3.1.x

Please check the CXF 3.0.0 Migration Guide for the information about all the changes
in CXF 3.0.0. Here are more details on the changes specifically affecting JAX-RS users:

1. CXF RequestHandler and ResponseHandler filters have been removed.

These legacy CXF filters are still supported in 2.7.x but no longer in 3.0.0. Please use ContainerRequestFilter and ContainerResponseFilter instead. Also, ReaderInterceptor and WriterInterceptor can be used too.

Note, CXF filters had org.apache.cxf.message.Message available in the signature. If CXF Message is used in the existing CXF RequestHandler or ResponseHandler then use "org.apache.cxf.phase.PhaseInterceptorChain.getCurrentMessage()" or "org.apache.cxf.jaxrs.util.JAXRSUtils.getCurrentMessage()" to get a Message which has all the contextual information available.

For example, instead of

Code Block
java
java
public class CustomRequestHandler implements RequestHandler {
    public Response handleRequest(Message message, ClassResourceInfo cri) {
    }
}

public class CustomResponseHandler implements ResponseHandler {
    public Response handleResponse(Message message, OperationResourceInfo ori, Response response) {
    }
}

do

Code Block
java
java
public class CustomRequestFilter implements ContainerRequestFilter {
    public void filter(ContainerRequestContext context) {
        Message message = JAXRSUtils.getCurrentMessage();
       ClassResourceInfo cri = message.getExchange().get(OperationResourceInfo.class).getClassResourceInfo();

        // or consider using JAX-RS 2.0 ResourceInfo context

        // finally use context.abortWith(Response) if you need to block the request 
    }
}

public class CustomResponseFilter implements ContainerResponseFilter {
    public void filter(ContainerRequestContext inContext, ContainerResponseContext outContext) {
        Message message = JAXRSUtils.getCurrentMessage();
        OperationResourceInfo cri = message.getExchange().get(OperationResourceInfo.class);

        // or consider using JAX-RS 2.0 ResourceInfo context 
        
        // finally, work with ContainerResponseContext to modify specific Response properties
    }
}

The above is only needed to ease the migration of the existing RequestHandler or ResponseHandler implementations. Prefer writing portable JAX-RS 2.0 filter implementations if possible. CXF interceptors can be used to do the CXF specific code if needed.

2. CXF org.apache.cxf.jaxrs.ext.form.Form has been dropped, please use JAX-RS 2.0 Form instead. For example, use:

Code Block
java
java
import javax.ws.rs.core.Form;

Form form = new Form().param("a", "b");

instead of

Code Block
java
java
import org.apache.cxf.jaxrs.ext.form.Form;

Form form = new Form().set("a", "b");

3. CXF WebClient and proxy code has been moved to a new cxf-rt-rs-client module.
Also, jaxrs:client elements for injecting proxies have had the namespace changed from from "http://cxf.apache.org/jaxrs" to "http://cxf.apache.org/jaxrs-client".

Please see JAX-RS Client API page for more information.

4. WADL Auto Generator code has been moved to a new cxf-rt-rs-service-description module.

5. CXF ParameterHandler has been dropped. Please use ParameterConverterProvider instead, it can be used both on the server and client sides.

6. JAX-RS 2.0 introduces a controversial requirement that the default built-in JAX-RS MessageBodyWriter and JAX-RS MessageBodyReader providers are preferred to custom providers supporting the same types unless the custom providers are precisely typed, for example, if you have a custom InputStream reader properly implementing isReadable:

Code Block
java
java
public class MyStreamProvider implements MessageBodyReader<Object> {
    public boolean isReadable(Class<?> cls, ...) {
        return InputStream.class.isAssignableFrom(cls) || Reader.class.isAssignableFrom(cls);
    }
    // other methods
}

then the runtime will ignore it and choose a default InputStream/Reader reader because MyStreamProvider is typed on Object. This was done to deal with the cases where well-known JSON/etc providers are blindly supporting all types in their isReadable methods by always returning 'true' and then failing when asked to actually read the incoming stream into InputStream/etc directly. In case of MyStreamProvider, it will need to be split into MyInputStreamProvider and MyReaderProvider typed on InputStream and Reader respectively.

At CXF level, the users which depend on CXF MultipartProvider to have InputStream or String references to multipart attachments will be affected unless they use @Multipart annotation. For example, if we have a multipart payload with a single part/attachment only then the following code:

Code Block
java
java
@POST
@Consumes("multipart/form-data")
public void upload(InputStream is) {
}

which in CXF 2.7.x or earlier will return a pointer to first/single individual part, will actually return a stream representing the complete unprocessed multipart payload. Adding a @Multipart marker will keep the existing code working as expected:

Code Block
java
java
@POST
@Consumes("multipart/form-data")
public void upload(@Multipart InputStream is) {
}

Alternatively, setting a "support.type.as.multipart" contextual property will do.

7. If the custom code throws JAX-RS WebApplicationException with Response containing a non-null entity then custom WebApplicationException mappers will be bypassed - another problematic requirement, for example, the custom mappers doing the logging will miss on such exceptions.
Set CXF "support.wae.spec.optimization" property to false to disable it.

8. In some cases the matching sub-resource locators will be dropped to precisely meet the current JAX-RS matching algorithm text, please see CXF-5650 for more information. Use a new "keep.subresource.candidates" property to support the existing application if needed.

CXF 3.1.2 Provider Sorting Changes

Starting from CXF 3.1.2 customMessageBodyReader (MBR), MessageBodyWriter (MBW) and ExceptionMapper providers are sorted together with default providers.

Before CXF 3.1.2 if a custom MBR or MBW matches the read or write selection criteria, example, if MBR Consumes matches Content-Type and its isReadable() returns true, then

the default providers are not even checked. The specification however does let the custom providers be selected only if no higher priority matching default provider is available.

For example, suppose you have a custom StringReader which is not typed by String but by Object. In this case the default provider which is typed by String wins. To have the custom String provider winning one needs to type it by String.

Check the specification or ask at the users list for more details.


Maven dependencies

CXF 3.2.0

The cxf-rt-frontend-jaxrs dependency is required:

Code Block
xml
xml
   <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
      <version>3.2.0</version>
   </dependency>

This will in turn pull other CXF modules such cxf-core and cxf-rt-transports-http, check the pom for more information.

javax.ws.rs/javax.ws.rs-api/2.1 dependency provides JAX-RS 2.1 Final API.

CXF 3.1.x

The cxf-rt-frontend-jaxrs dependency is required:

Code Block
xml
xml
   <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
      <version>3.1.12</version>
   </dependency>

This will in turn pull other CXF modules such cxf-core and cxf-rt-transports-http, check the pom for more information.

javax.ws.rs/javax.ws.rs-api/2.0 dependency provides JAX-RS 2.0 Final API.

javax.annotation/javax.annotation-api/1.2 dependency is needed if custom JAX-RS 2.0 filters or interceptors use a javax.annotation.Priority annotation.

Existing JAX-RS 1.1 applications can run in CXF 3.1.x and CXF 3.0.x.

CXF JAX-RS bundle

Note CXF JAX-RS bundle has been removed in CXF 3.0.0. Prefer depending on the JAX-RS frontend directly. In CXF 3.0.0 a complete CXF all-inclusive bundle can still be used if really needed.

Only in CXF 2.7.x or earlier:
A standalone JAX-RS bundle is available which may be of interest to users doing the JAX-RS work only.

Please note that this bundle has a transitive Maven dependency on the Jetty server modules. If you are using Maven and working with other servlet containers such as Tomcat then please add the following exclusion:

Code Block
xml
xml
   <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-bundle-jaxrs</artifactId>
      <version>${cxf.version}</version>
      <exclusions>
          <exclusion>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
          </exclusion>
      </exclusions> 

   </dependency>

What is New

Getting Started with JAX-RS

Understanding the Basics

You are encouraged to read JAX-RS 2.1 JSR-370 specification to find out the information not covered by this documentation. The specification enhances JAX-RS 2.0 by introducing a support for Reactive Client API extensions, Server Sent Events (client and server), returning CompletableFuture from the resource methods and the sub-resource classes (as opposed to instances) from the sub-resource locators.

You are also encouraged to read JAX-RS 2.0 JSR-339 specification to find out the information not covered by this documentation. The specification introduces many terms such as root resources, resource methods, sub-resources and sub-resource locators, message body readers and writers. JAX-RS 2.0 additionally introduces filters, interceptors, new client API, features, new exception classes, server-side support for asynchronous invocations.

Please see the JAX-RS Basics page for more information.

Support for Data Bindings

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

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

Please see the JAX-RS Data Bindings page for more information.

How Request URI is Matched

Lets assume you have a web application called 'rest' (example, a 'rest.war' archive). CXFServlet's url-pattern is "/test/*". Finally, jaxrs:server's address is "/bar".

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 to be handled, a resource class with @Path("/") should be available, in the latter case - at least @Path("/") or a more specific @Path("/baz").

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

When both CXFServlet and jaxrs:server use "/" then it's a root resource class which should provide a @Path with at least "/test/bar" for the above requests to be matched.

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.

Client API

CXF 3.0.0 implements JAX-RS 2.0 Client API.

CXF 2.7.x or earlier provides a comprehensive support for developing RESTful clients by supporting 3 flavors of the client API: proxy-based, HTTP-centric and XML-centric. CXF-specific client API is supported alongside new JAX-RS 2.0 Client API in CXF 3.0.0.

Please see the JAX-RS Client API page for more information.

Bean Validation

Bean Validation 1.1 is supported since CXF 3.0.0-milestone1. Please see the http://cxf.apache.org/docs/validationfeature.html for more information.

Filters, Interceptors and Invokers

It is possible to intercept and modify the inbound and outbound calls with the help of CXF JAX-RS filters and/or CXF interceptors. Additionally, custom invokers offer an option to intercept a call immediately before a service bean is invoked.

Please see the JAX-RS Filters page for more information.

Please see the JAX-RS Basics page for more information about new JAX-RS 2.0 filters and interceptors available in CXF 2.7.x and 3.0.0.

Service listings and WADL support

New: Swagger feature has been introduced.

CXF JAX-RS supports WADL. CXF JAX-RS service endpoints can be listed in the service listings page and users can check the WADL documents.

Please see the JAXRS Services Description page for more information.

Configuring JAX-RS services

JAX-RS services can be configured programmatically, using Blueprint, Spring or CXFNonSpringJAXRSServlet.

Please see the JAXRS Services Configuration page for more information.

Testing

JAX-RS services can be easily tested using the embedded Jetty or CXF Local Transport.
Please see the JAXRS Testing page for more information.

Debugging

One may want to use a browser to test how a given HTTP resource reacts to different HTTP Accept or Accept-Language header values and request methods. For example, if a resource class supports a "/resource" URI then one can test the resource class using one of the following queries :

> GET /resource.xml
> GET /resource.en

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

Code Block
xml
xml
  <jaxrs:server id="customerService" address="/">
    <jaxrs:serviceBeans>
      <bean class="org.apache.cxf.jaxrs.systests.CustomerService" />
    </jaxrs:serviceBeans>
    <jaxrs:extensionMappings>
      <entry key="json" value="application/json"/>
      <entry key="xml" value="application/xml"/>
    </jaxrs:extensionMappings>
    <jaxrs:languageMappings>
       <entry key="en" value="en-gb"/>  
    </jaxrs:languageMappings>
  </jaxrs:server>

CXF also supports a _type query as an alternative to appending extensions like '.xml' to request URIs:

{{ > GET /resource?_type=xml}}

CXF also supports overriding request methods. However note that by default this is not allowed (since CXF 3.3.4) for a CXF service. To enable HTTP method overriding, specify the "org.apache.cxf.jaxrs.allow.http.method.override" endpoint property as "true".

Two options of overriding HTTP request methods are available - via a query parameter:

> GET /resource?_method=POST

Alternatively, one can specify an HTTP header X-HTTP-Method-Override:

> POST /books
> X-HTTP-Method-Override : PATCH

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

Finally, a "_ctype" query allows for overriding Content-Type.

Please see the Debugging and Logging page for more information on how to debug and log service calls in CXF.

Logging

Many of the existing CXF features can be applied either to jaxrs:server or jaxrs:client. For example, to enable logging of requests and responses, simply do:

Code Block
xml
xml
<beans xmlns:cxf="http://cxf.apache.org/core" 
   xsi:schemaLocation="http://cxf.apache.org/core 
      http://cxf.apache.org/schemas/core.xsd">
<jaxrs:server>
<jaxrs:features>
     <cxf:logging/>
</jaxrs:features>
<jaxrs:server>
</beans>

Please make sure the http://cxf.apache.org/core namespace is in scope.

Starting from CXF 2.3.0 it is also possible to convert log events into Atom entries and either push them to receivers or make them available for polling.

Please see the Debugging and Logging page for more information.

Advanced Features

Multiparts

Multiparts can be handled in a number of ways. The CXF core runtime provides advanced support for handling attachments which CXF JAX-RS builds upon.

Please see the JAX-RS Multiparts page for more information.

Secure JAX-RS services

Transport level HTTPS security can be used to protect messages exchanged between CXF JAX-RS endpoints and providers.

Authentication and authorization can be enforced in a number of ways.

Please see the Secure JAX-RS Services page for more information.

Please also check JAX-RS XML Security, JAX-RS SAML, JAX-RS Token Authorization and JAX-RS OAuth2 pages for more information about the advanced security topics.

Failover and Load Distribution Features

Starting from CXF 2.4.1, CXF JAX-RS proxy and WebClient consumers can be backed up by failover and load distribution features.
Please see the JAX-RS Failover page for more information.

Redirection

Starting from CXF 2.2.5 it is possible to redirect the request or response call to other servlet resources by configuring CXFServlet or using CXF JAX-RS RequestDispatcherProvider.

Please see the JAX-RS Redirection page for more information.

XSLT and XPath

XSLT and XPath 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.

Please see the JAX-RS Advanced XML page for more information.

Complex Search Queries

Using query parameter beans provides a way to capture search requirements that can be expressed by enumerating name/value pairs, for example, a query such as '?name=CXF&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 available local data.

Versions 2.3 and later of CXF JAXRS support another option for doing advanced search queries using the Feed Item Query Language(FIQL).

Please see the JAX-RS Search page for more information.

Model-View-Controller support

XSLT
Please see the JAX-RS Advanced XML page for more information. on how XSLTJaxbProvider can be used to generate complex (X)HTML views.

JSP

With the introduction of RequestDispatcherProvider it is now possible for JAXRS service responses be redirected to JSP pages for further processing. Please see the JAX-RS Redirection page for more information.

Combining JAX-WS and JAX-RS

CXF JAX-RS tries to make it easy for SOAP developers to experiment with JAX-RS and combine both JAX-WS and JAX-RS in the same service bean when needed.

Please see the JAX-RS and JAX-WS page for more information.

Integration with Distributed OSGi

Distributed OSGi RI is a CXF subproject. DOSGi mandates how registered Java interfaces can be exposed
and consumed as remote services. DOSGi single and multi bundle distributions contain all the OSGI bundles required for a CXF endpoint be successfully published.

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.

Please see the DOSGI Reference page ('org.apache.cxf.rs' properties) and a greeter_rest sample for more information. Note that this demo can be run exactly as a SOAP-based greeter demo as it registers and consumes a similar (but) JAX-RS annotated GreeterService. In addition, this demo shows how one can register and consume a given interface (GreeterService2) without using explicit JAX-RS annotations but providing an out-of-band user model description.

OData Support

CXF JAX-RS endpoints can support OData in two ways by relying on Apache Olingo.

First, the OData "$filter" query is supported by the Search extension where an endpoint with the application specific API can respond to the filter queries, for example, return a collection of books matching the fillter search criteria.

Second, CXF JAX-RS can be used to interpose over the Olingo, as is demoed here. Effectively such a CXF endpoint becomes an OData server: all it does it delegates to Olingo. The idea is to be able to add CXF specific features and interceptors in front of Olingo.

Other Advanced Features

CXF JAX-RS provides a number of advanced extensions such as the support for the JMS transport, one-way invocations (HTTP and JMS), suspended invocations (HTTP and JMS), making existing code REST-aware by applying external user models, etc.

Please see the JAX-RS Advanced Features page for more information.

Maven Plugins

Please see the JAX-RS Maven Plugins page for more information about the Maven plugins and archetypes which can help with creating CXF JAX-RS applications.

Deployment

CXF JAX-RS applications packaged as WAR archives can be deployed into standalone Servlet containers such as Tomcat or Jetty.
Please see the JAX-RS Deployment page for the tips on how to deploy the CXF JAX-RS applications into various Java EE and OSGI application servers successfully.

Third-party projects

References

How to contribute

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.

Please check the issue list and see if you are interested in fixing one of the issues.

If you decide to go ahead then the fastest way to start is to

  • do the fast trunk build using 'mvn install -Pfastinstall'
  • setup the workspace 'mvn -Psetup.eclipse' which will create a workspace in a 'workspace' folder, next to 'trunk'
  • import cxf modules from the trunk into the workspace and start working with the cxf-frontend-jaxrs module

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 :
> mvn install

You can also check out the general Getting Involved web page for more information on contributing.