JAX-RS has been edited by Sergey Beryozkin (May 04, 2009).

(View changes)

Content:
JAX-RS (JSR-311)

Introduction

CXF supports JAX-RS (JSR-311), Java API for RESTful Web Services. JAX-RS provides a more standard way to build RESTful services in Java. CXF 2.2.x supports the final version of JSR-311 API while CXF 2.1.x currently supports the 0.8 version of JSR-311 API .

JAX-RS related demos are located under samples/jax_rs directory (CXF 2.2 and CXF 2.1 only).
This documentation will refer to JSR-311 API 1.0 .

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

Note that all the fixes applied to the JAX-RS implementation in the trunk will be available for users of 0.8 api, with the exception of 1.0 api specific fixes.

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

  • Spring version have changed from 2.0.8 in 2.1.x to 2.5.6
  • jaxb-api version has changed to javax.xml.bind/jaxb-api/2.1
  • jaxb-impl version has changed to com.sun.xml.bind/jaxb-impl/2.1.7

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

Maven dependencies

The following 3rd-party dependencies are used when building CXF JAX-RS implementation :

1. javax.ws.rs/jsr311-api/1.0

available from either

<repository>
            <id>java.net.2</id>
            <name>Java Net 2 Repository</name>
            <url>http://download.java.net/maven/2</url>
</repository>

or from a central maven repository

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

<repository>
<id>apache.incubating</id>
<name>Apache Incubating Repository</name>
<url>http://people.apache.org/repo/m2-incubating-repository</url>
</repository>

3. org.springframework/spring-core/2.5.6

4. org.codehaus.jettison/jettison/1.0.1

5. org.apache.xmlbeans/xmlbeans/2.3.0 - compile time

Please check the 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/

CXF JAX-RS bundle

A standalone JAX-RS bundle is now available which may be of interest to users doing JAX-RS work only.

Understanding the basics

You are encouraged to read JAX-RS spec to find out information not covered by this documentation.

Resource class

A resource class is a Java class annotated with JAX-RS annotations to represent a Web resource. Two types of resource classes are available : root resource classes and subresource classes. A root resource class is annotated at least with a @Path annotation, while subresource classes typically have no root @Path values. A typical root resource class in JAX-RS looks like this below:

package demo.jaxrs.server;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/customerservice/")
@Produces("application/xml")
public class CustomerService {

    public CustomerService() {
    }

    @GET
    public Customers getCustomers() {
        ......
    }

    @GET
    @Path("/customers/{id}")
    @Produces("application/json")
    public Customer getCustomer(@PathParam("id") String id) {
        ......
    }

    @PUT
    @Path("/customers/{id}")
    @Consumes("application/xml")
    public Response updateCustomer(@PathParam("id") Long id, Customer customer) {
        ......
    }

    @POST
    @Path("/customers")
    public Response addCustomer(Customer customer) {
        ......
    }

    @DELETE
    @Path("/customers/{id}/")
    public Response deleteCustomer(@PathParam("id") String id) {
        ......
    }

    @Path("/orders/{orderId}/")
    public Order getOrder(@PathParam("orderId") String orderId) {
       ......
    }
}

Customer resource class can handle requests starting from /customerservice. When /customerservice request is matched to this class, its getCustomers() method will be selected. updateCustomer(), deleteCustomer() and addCustomer() are used to serve POST, PUT and DELETE requests starting from /customerservice/customer, while getOrder() method delegates the handling of requests like /customerservice/orders/1 to a subresource locator Order.

@Produces annotation is used to specify the format of the response. When not available on the resource method, it's inherited from a class, and if it's not available on the class then it's inherited from a corresponding message body writer, if any. Default value is */*, but it's recommended that some definite value is specified. The same applies to @Consumes, only it's message body readers that are checked as the last resort.

For example, getCustomers() method inherits @Produces annotation from its class, while getCustomer() method overrides it with its own value.

@Path

@Path annotation is applied to resource classes or methods. The value of @Path annotation is a relative URI path and follows the URI Template format and may include arbitrary regular expressions. When not available on the resource method, it's inherited from a class. For example :

@Path("/customers/{id}")
public class CustomerResource {

    @GET
    public Customer getCustomer(@PathParam("id") Long id) {
        ......
    }

    @GET
    @Path("/order/{orderid}")
    public Order getOrder(@PathParam("id") Long customerId, @PathParam("orderid") Long orderId) {
        ......
    }

    @GET
    @Path("/order/{orderid}/{search:.*}")
    public Item findItem(@PathParam("id") Long customerId, 
                         @PathParam("orderid") Long orderId,
                         @PathParam("search") String searchString,
                         @PathParam("search") List<PathSegment> searchList) {
        ......
    }
}

This example is similar to the one above it, but it also shows that an {id} template variable specified as part of the root @Path expression is reused by resource methods and a custom regular expression is specified by a findItem() method (note that a variable name is separated by ':' from an actual expression).

In this example, a request like 'GET /customers/1/order/2/price/2000/weight/2' will be served by the findItem() method.
List<PathSegment> can be used to get to all the path segments in 'price/2000/weight/2' captured by the regular expression.

More information about Path annotations can be found from JAX-RS spec section 2.3.

HTTP Method

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

package org.apache.cxf.customverb;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
public @interface PATCH { 
}

Return types

Either javax.ws.rs.core.Response or custom type can be returned. javax.ws.rs.core.Response can be used to set the HTTP response code, headers and entity. JAX-RS MessageBodyWriters (see below) are in charge of serializing the response entities, those which are returned directly or as part of javax.ws.rs.core.Response.

Exception handling

One can either throw an unchecked WebApplicationException or return Response with a proper error code set.
The former option may be a better one when no JAX-RS types can be added to method signatures.

For example :

@Path("/customerservice/")
public class CustomerService {

    
    @PUT
    @Path("/customers/{id}")
    public Response updateCustomer(@PathParam("id") Long id, Customer customer) {
        return Response.status(errorCode).build();
    }

    @POST
    @Path("/customers")
    public Customer addCustomer(Customer customer) {
        throw new WebApplicationException(errorCode);
    }

}

Yet another option is to register an ExceptionMapper provider. Ex :

public BookExceptionMapper implements ExceptionMapper<BookException> {
    public Response toResponse(BookException ex) {
        // convert to Response
    }
}

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

Dealing with Parameters

PathParam annotation is used to map a given Path template variable to a method parameter.
For example :

@Path("/customer/{id}")
public class CustomerService {

    
    @PUT
    @Path("{name}")
    public Response updateCustomer(@PathParam("id") Long id, @PathParam("name") String name) {
        ...
    }
}

In this case a template variable id available from a root class annotation is mapped to a parameter of type Long, while a name variable is mapped to a parameter of type String.

@QueryParam, @HttpHeader, @MatrixParam, @FormParam and @CookieParam annotations are also supported.
Parameters can be of type String or of any type that have constructors accepting a String parameter or static valueOf(String s) methods.
Additionally CXF JAXRS checks for static fromString(String s) method, so types with no valueOf(String) factory methods can also be dealt with :

public enum Gender {
   MALE,
   FEMALE;

   public static fromString(String s) {
       if ("1".equals(s)) {
           return FEMALE;
       } else if ("1".equals(s)) {
           return MALE;
       }  
       return valueOf(s); 
   }
}

@Path("/{g}")
public class Service {

    
    @PUT
    @Path("{id}")
    public Response update(@PathParam("g") Gender g, @PathParam("id") UUID u) {
        ...
    }
}

JAX-RS PathSegment is also supported. A sequence of identically named parameters (queries, headers, etc) can be mapped to List or Set or SortedSet.

CXF JAXRS supports ParameterHandler extensions which can be used to deal with method parameters annotated with one of the JAXRS parameter annotations :

public class MapHandler implements ParameterHandler<Map> {
    public Map fromString(String s) {...}
}

@Path("/")
public class Service {

    
    @PUT
    @Path("{id}")
    public Response update(@PathParam("g") Map m, byte[] bytes) {
        ...
    }
}

Note that ParameterHandlers can not be used to deal with parameters representing a message body, "byte[] byte" in this example. MessageBodyReaders have to deal with this task. That said, a given MessageBodyReader implementation can also implement ParameterHandler.

ParameterHandlers can be registered as providers either from Spring or programmatically.

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

public Response updateCustomer(@DefaultValue("123") @QueryParam("id") Long id, @PathParam("name") String name) { ... }

JAX-RS mandates that only a single method parameter which is not annotated with JAXRS annotations applicable to method parameters is allowed in a resource method. For example :

public Response do(@PathParam("id") String id, String body) {
}

Parameters like 'String body' are expected to represent the request body/input stream. It's the job of JAX-RS MessageBodyReaders to deserialize the request body into an object of the expected type.

There's also a CXF extension which makes it possible to inject a sequence of @PathParam, @QueryParam, @FormParam or @MatrixParam parameters into a bean. For ex :

@Path("/customer/{id}")
public class CustomerService {

    
    @PUT
    @Path("{name}")
    public Response updateCustomer(@PathParam("") Customer customer) {
        ...
    }

    @GET
    @Path("/order")
    public Response getCustomerOrder(@PathParam("id") int customerId, 
                                     @QueryParam("") OrderBean bean,
                                     @MatrixParam("") OrderBean bean) {
        ...
    }

    @POST
    public Response addCustomerOrder(@PathParam("id") int customerId,
                                     @FormParam("") OrderBean bean) {
        ...
    }
}

public class Customer {
   public void setId(Long id) {...}
   public void setName(String s) {...}  
}

public class OrderBean {
   public void setId(Long id) {...}
   public void setWeight(int w) {...}  
}

Note that there's a single @PathParam with an empty value in updateCustomer() - this is an extension bit. The value for a template variable 'id' is injected into Customer.setId(Long id), while the value for 'name' is injected into Customer.setName(String s). The setter methods should have a single parameter, the conversion from the actual value to the parameter instance follows the same procedure as outlined above.

Similarly, in getCustomerOrder(), OrderBean can be injected with corresponding values from a query string like ?id=1&weight=2 or from matrix parameters set as part of one of the path segments : /customer/1/order;id=1;weight=2. Likewise, in addCustomerOrder(), FormParam("") can capture all the values submitted from an HTML form and inject them into OrderBean.

Starting from JAX-RS 0.8, it's also possible to inject all types of parameters into fields or through dedicated setters. For ex, the first code fragment in this section can be rewritten like this :

@Path("/customer/{id}")
public class CustomerService {

    @PathParam("id")
    private Long id; 
    
    private String name;

    @PathParam("name")
    public setName(String name) {
        this.name = name;
    } 

    @PUT
    @Path("{name}")
    public Response updateCustomer() {
        // use id and name
    }
}

Overview of the selection algorithm.

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

Selecting between multiple resource classes

When multiple resource classes match a given URI request, the following algorithm is used :
1. Prefer the resource class which has more literal characters in its @Path annotation.

@Path("/bar/{id}")
public class Test1 {}
@Path("/bar/{id}/baz")
public class Test2 {}
@Path("/foo")
public class Test3 {}
@Path("/foo/")
public class Test4 {}

Both classes match /bar/1/baz requests but Test2 will be selected as it has 9 Path literal characters compared to 5 in Test1. Similarly, Test4 wins against Test3 when a /foo/ request arrives.

2. Prefer the resource class which has more capturing groups in its @Path annotation.

@Path("/bar/{id}/")
public class Test1 {}
@Path("/bar/{id}/{id2}")
public class Test2 {}

Both classes match /bar/1/2 requests and both have the same number of literal characters but Test2 will be selected as it has 2 Path capturing groups (id and id1) as opposed to 1 in Test1.

3. Prefer the resource class which has more capturing groups with arbitrary regular expressions in its @Path annotation.

@Path("/bar/{id:.+}/baz/{id2}")
public class Test1 {}
@Path("/bar/{id}/{bar}/{id2}")
public class Test2 {}

Both classes match /bar/1/baz/2 requests and both have the same number of literal characters and capturing groups but Test1 will be selected as it has 1 Path capturing groups with the arbitrary regular expression (id) as opposed to 0 in Test2.

Selecting between multiple resource methods

Once the resource class has been selected, the next step is to choose a resource method. If multiple methods can be matched then the same rules which are used for selecting resource classes are applied. Additionally, one more rule is used.

4. Prefer a resource method to a subresource locator method

@Path("/")
public class Test1 {

 @Path("/bar")
 @GET
 public Order getOrder() {...}

 @Path("/bar")
 public Order getOrderFromSubresource() {...}
}

public class Order {

 @Path("/")
 @GET
 public Order getOrder() { return this; }

}

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

Resource methods and media types

Consider this resource class with 2 resource methods :

@Path("/")
public class Test1 {

 @Path("/bar")
 @POST 
 @Consumes("application/json")
 @Produces("application/json")
 public Order addOrderJSON(OrderDetails details) {...}

 @Path("/bar")
 @POST
 @Consumes("application/xml")
 @Produces("application/xml")
 public Order getOrderXML(OrderDetails details) {...}
 
}

Both methods match /bar requests. If in a given request both Content-Type and Accept are set to application/xml then
getOrderXML will be selected. If both Content-Type and Accept are set to application/json then
getOrderJSON will be chosen instead.

For this specific example, in both cases either JAXB or JSON message body readers and writers will be selected to deserialize the input stream into OrderDetails and serialize Order into the output stream. Message body providers can have @Produces and @Consumes set too, and they have to match those on a chosen resource method.

The above code can be replaced with this one :

@Path("/")
public class Test1 {

 @Path("/bar")
 @POST 
 @Consumes({"application/json", "application/xml"})
 @Produces({"application/json", "application/xml"})
 public Order addOrder(OrderDetails details) {...}

}

TODO : more info

Context annotations

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

A CXF-specific composite context interface, MessageContext is also supported which makes it easier to deal with all the supported JAX-RS contexts (and indeed with the future ones) and also lets check the current message's properties.

Example :

@Path("/customer")
public class CustomerService {
    
    @Context 
    private org.apache.cxf.jaxrs.ext.MessageContext mc; 
    @Context 
    private ServletContext sc;
    private UriInfo ui;
    
    @Context
    public void setUriInfo(UriInfo ui) {
        this.ui = ui;
    }

    @PUT
    public Response updateCustomer(@Context HttpHeaders h, Customer c) {
        mc.getHttpHeaders();
    }
}

Note that all types of supported JAX-RS providers such as MessageBodyWriter, MessageBodyReader, ExceptionMapper and ContextResolver, as well as the list of body providers which can be provided by Providers can have contexts injected too. The only exception is that no parameter level injection is supported for providers due to methods of JAXRS providers being fixed.

Note that Providers and ContextResolver are likely to be of interest to message body providers rather than to the actual application code. You can also inject all the context types into @Resource annotated fields.

URIs calculation using UriInfo and UriBuilder

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

@Path("/customers")
public class CustomerService {

    @GET
    public Customers getCustomers() {
        ......
    }

    @GET
    @Path("/{id}")
    public Customer getCustomer(@PathParam("id") String id) {
        ......
    }

}

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

GET http://foobar.com/api/customers

<customers>
    <customer id="1005">John Doe</customer>
    <customer id="1006">Jane Doe</customer>
    ...
</customers>
    
GET http://foobar.com/api/customers/1005

<customer id="1005">
    <first-name>John</first-name>
    <last-name>Doe</last-name>
    ...
</customer>

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

GET http://foobar.com/api/customers

<customers-list>
    <customer id="1005" url="http://foobar.com/api/customers/1005">John Doe</customer>
    <customer id="1006" url="http://foobar.com/api/customers/1006">Jane Doe</customer>
    ...
</customers-list>

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

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

@Path("/customers")
public class CustomerService {

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

    @GET
    @Path("/{id}")
    public Customer getCustomer(@PathParam("id") String id) {
        ......
    }

}

Annotation inheritance

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

public interface CustomerService {

    @PUT
    @Path("/customers/{id}")
    Response updateCustomer(@PathParam("id") Long id, Customer customer);

    @POST
    @Path("/customers")
    Customer addCustomer(Customer customer);

}

@Path("/customerservice/")
public class Customers implements CustomerService {

    
    public Response updateCustomer(Long id, Customer customer) {
        return Response.status(errorCode).build();
    }

    public Customer addCustomer(Customer customer) {
        throw new WebApplicationException(errorCode);
    }

}

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

Sub-resource locators.

A method of a resource class that is annotated with @Path becomes a sub-resource locator when no annotation with an HttpMethod designator like @GET is present. Sub-resource locators are used to further resolve the object that will handle the request. They can delegate to other sub-resource locators, including themselves.

In the example below, getOrder method is a sub-resource locator:

@Path("/customerservice/")
public class CustomerService {

    @Path("/orders/{orderId}/")
    public Order getOrder(@PathParam("orderId") String orderId) {
       ......
    }
}

@XmlRootElement(name = "Order")
public class Order {
    private long id;
    private Items items;

    public Order() {
    }

    public long getId() {
        return id;
    }


    @GET
    @Path("products/{productId}/")
    public Product getProduct(@PathParam("productId")int productId) {
       ......
    }

    @Path("products/{productId}/items")
    public Order getItems(@PathParam("productId") int productId) {
       return this;
    }

    @GET
    public Items getItems() {
       ......
    }

}

A HTTP GET request to http://localhost:9000/customerservice/orders/223/products/323 is dispatched to getOrder method first. If the Order resource whose id is 223 is found, the Order 223 will be used to further resolve Product resource. Eventually, a Product 323 that belongs to Order 223 is returned.
The request to http://localhost:9000/customerservice/orders/223/products/323/items will be delivered to getItems() method which in turn will delegate to an overloaded getItems().

Note that a subresource class like Order is often has no root @Path annotations which means that they're delegated to dynamically at runtime, in other words, they can not be invoked upon before one of the root resource classes is invoked first. A root resource class (which has a root @\Path annotation) can become a subresource too if one of its subresource locator methods delegates to it, similarly to Order.getItems() above.

Note that a given subresource can be represented as an interface or some base class resolved to an actual class at runtime. In this case any resource methods which have to be invoked on an actual subresource instance are discovered dynamically at runtime :

@Path("/customerservice/")
public class CustomerService {

    @Path("/orders/{orderId}/")
    public Order getOrder(@PathParam("orderId") String orderId) {
       ......
    }
}

public interface Order {
    @GET
    @Path("products/{productId}/")
    Product getProduct(@PathParam("productId")int productId);
}

@XmlRootElement(name = "Order")
public class OrderImpl implements Order {
    
    public Product getProduct(int productId) {
       ......
    }
}

@XmlRootElement(name = "Order")
public class OrderImpl2 implements Order {
    
    // overrides JAXRS annotations
    @GET
    @Path("theproducts/{productId}/")
    Product getProduct(@PathParam("id")int productId) {...}
}

Static resolution of subresources

By default, subresources are resolved dynamically at runtime. This is a slower procedure, partly due to the fact that a concrete subresource implementation may introduce some JAXRS annotations in addition to those which might be available at the interface typed by a subresource locator method and different to those available on another subresource instance implementing the same interface.

If you know that all the JAXRS annotations are available on a given subresource type (or one of its superclasses or interfaces) returned by a subresource locator method then you may want to disable the dynamic resolution :

<beans>
<jaxrs:server staticSubresourceResolution="true">
<!-- more configuration -->
</jaxrs:server>
</beans>

Message Body Providers

JAX-RS relies on MessageBodyReader and MessageBodyWriter implementations to serialize and de-serialize Java types. JAX-RS requires that certain types has to be supported out of the box.
By default, CXF supports String, byte[], InputStream, Reader, File, JAXP Source, JAX-RS StreamingOutput, JAXB-annotated types with application/xml, text/xml and application/json formats as well as JAXBElement (see below). JAX-RS MultivaluedMap is also supported for form contents.

See also a "Support for data bindings" section below.

Custom Message Body Providers

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

Here's an example of a custom MessageBodyReader for InputStream :

@Consumes("application/octet-stream")
@Provider
public class InputStreamProvider implements MessageBodyReader<InputStream> {

    
    public boolean isReadable(Class<InputStream> type, Type genericType, Annotation[] annotations, MediaType mt) {
        return InputStream.class.isAssignableFrom(type);
    }

    public InputStream readFrom(Class<InputStream> clazz, Type t, Annotation[] a, MediaType mt, 
                         MultivaluedMap<String, String> headers, InputStream is) 
        throws IOException {
        return new FilterInputStream(is) {
             @Override
             public int read(byte[] b) throws IOException {
                 // filter out some bytes
             }              
        }     
    }
}

and here's an example of a custom MessageBodyWriter for Long :

@ProduceMime("text/plain")
@Provider
public class LongProvider implements MessageBodyWriter<Long> {

    public long getSize(Long l, Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
        return -1;
    }

    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
        return long.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type);
    }

    public void writeTo(Long l, Class<?> clazz, Type type, Annotation[] a, 
                        MediaType mt, MultivaluedMap<String, Object> headers, OutputStream os) 
        throws IOException {
        os.write(l.toString().getBytes());
        
    }

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

Registering custom providers

Putting @Provider annotation on the provider class is something that should lead to your provider being registered with the runtime. CXF does not support this feature yet.

One can easily register a provider either from the Spring configuration or programmatically :

<beans>
<jaxrs:server id="customerService" address="/">
    <jaxrs:serviceBeans>
      <bean class="org.CustomerService" />
    </jaxrs:serviceBeans>

    <jaxrs:providers>
      <ref bean="isProvider" />
      <ref bean="longProvider" />
    </jaxrs:providers>
    <bean id="isProvider" class="com.bar.providers.InputStreamProvider"/>
    <bean id="longProvider" class="com.bar.providers.LongProvider"/>
</jaxrs:server>
</beans>

Note that instead of the older <jaxrs:entityProviders> it's now <jaxrs:providers>. JAX-RS supports different types of providers and having a single <jaxrs:providers> container is in line with the way other JAX-RS implementations discover providers by checking for @Provider annotations only.

See below a more complete beans.xml definition.

While having @Provider-annotated providers automatically registered is a handy feature indeed, sometimes it might actually be problematic. For ex, in a large project user providers from different libraries might clash.

When using the custom configuration (as shown above) provider instances of different types (handling the same format of request/response bodies) or differently configured instances of the same type can be registered with a different jaxrs:server instance. Yet another requirement might be to have only a given jaxrs:server endpoint among multiple available ones to handle requests with a given media type :

<beans>
<jaxrs:server id="customerService1" address="/1">
   <bean id="serviceBean" class="org.CustomerService" /> 

   <jaxrs:serviceBeans>
      <ref bean="serviceBean"/>
   </jaxrs:serviceBeans>

   <jaxrs:providers>
      <bean class="com.bar.providers.InputStreamProvider"/>
   </jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="customerService2" address="/2">
    <jaxrs:serviceBeans>
      <ref bean="serviceBean"/>
    </jaxrs:serviceBeans>

    <jaxrs:providers>
      <bean id="isProvider" class="baz.foo.jaxrsproviders.InputStreamProvider"/>
    </jaxrs:providers>
</jaxrs:server>

<jaxrs:server id="customerService3" address="/3">
    <jaxrs:serviceBeans>
      <ref bean="serviceBean"/>
    </jaxrs:serviceBeans>

    <jaxrs:providers>
      <ref bean="isProvider"/>
    </jaxrs:providers>
</jaxrs:server>


<bean id="isProvider" class="com.bar.providers.InputStreamProvider">
   <property name="limit" value="5"/>
</bean>

</beans>

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

Customizing media types for message body providers

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

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

In such cases it's possible to override the default @Produces and/or @Consumes types supported by a given provider. It only currently works for JAXBElementProvider and JSONProvider, but any custom provider can avail of this support by simply having setter/getter pairs for either produce and/or consume types and the JAXRS runtime will use them instead.
See this example on how to provide custom media types from Spring.

Support for data bindings

JAXB support

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

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

For example:

@XmlRootElement(name = "Customer")
public class Customer {
    private String name;
    private long id;

    public Customer() {
    }

    public void setName(String n) {
        name = n;
    }

    public String getName() {
        return name;
    }

    public void setId(long i) {
        id = i;
    }

    public long getId() {
        return id;
    }
}

In the example below, the Customer object returned by getCustomer is marshaled using JAXB data binding:

@Path("/customerservice/")
public class CustomerService {
    @GET
    @Path("/customers/{customerId}/")
    public Customer getCustomer(@PathParam("customerId") String id) {
        ....
    }
}

The wire representation of Customer object is:

<Customer>
    <id>123</id>
    <name>John</name>
</Customer>

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

@XmlRootElement(name = "Customers")
public class Customers {
    private Collection<Customer> customers;

    public Collection<Customer> getCustomer() {
        return customers;
    }

    public void setCustomer(Collection<Customer> c) {
        this.customers = c;
    }
}
@Path("/customerservice/")
public class CustomerService {
    @GET
    @Path("/customers/")
    public Customers getCustomers() {
        ....
    }
}

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

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

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

Configuring JAXB provider

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

<beans xmlns:util="http://www.springframework.org/schema/util">
<bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
<property name="marshallerProperties" ref="propertiesMap"/>
</bean>
<util:map id="propertiesMap" map-class="java.util.Hashtable">
<entry key="jaxb.formatted.output" value="true"/>
</util:map>
/<beans>

Individual marshal properties can be injected as simple properties. At the moment, Marshaller.JAXB_SCHEMA_LOCATION can be injected as "schemaLocation" property. Schema validation can be enabled and custom @Consume and @Produce media types can be injected, see this example and "Customizing media types for message body providers" and "Schema Validation Support" sections for more information.

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

JSON support

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

Following code returns a Customer object that is marshaled to JSON format:

@Path("/customerservice/")
public class CustomerService {
    @Produces("application/json")
    @GET
    @Path("/customers/{customerId}/")
    public Customer getCustomer(@PathParam("customerId") String id) {
        ....
    }

Configuring JSON provider

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

<beans xmlns:util="http://www.springframework.org/schema/util">
<bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JSONProvider">
<property name="namespaceMap" ref="jsonNamespaceMap"/>
</bean>
<util:map id="jsonNamespaceMap" map-class="java.util.Hashtable">
<entry key="http://www.example.org/books" value="b"/>
</util:map>
/<beans>

Schema validation can be enabled and custom @Consume and @Produce media types can be injected, see this example and "Customizing media types for message body providers" and "Schema Validation Support" sections for more information.

Dealing with JSON array serialization issues

There's a well known problem in the JSON community which shows itself in the wrong serialization of List objects containing a single value only. To work around this issue, one needs to enable a 'serializeAsArray' feature on a JSONProvider, with the additional option of specifying the individual fields which needs to be processed accordingly using an 'arrayKeys' property. Please see this example for more information.

Aegis Data Binding

Use org.apache.cxf.provider.AegisElementProvider to start doing Aegis with JAX-RS

XMLBeans

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

Schema validation support

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

1. Using jaxrs:schemaLocations element :

<beans xmlns:util="http://www.springframework.org/schema/util">
<jaxrs:server address="/">
  <jaxrs:schemaLocations>
     <jaxrs:schemaLocation>classpath:/schemas/a.xsd</jaxrs:schemaLocation>
     <jaxrs:schemaLocation>classpath:/schemas/b.xsd</jaxrs:schemaLocation>
  </jaxrs:schemaLocations>
</jaxrs:server>
/<beans>

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

2. Configuring providers individually

Please see this example of how both JAXB and JSON providers are using a shared schema validation configuration.

Content type negotiation

One of the coolest thing of REST is that the same resource can be served using multiple representations. @Produces and @Consumes annotations are used to declare the supported request and response media types.

TODO : more content here

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 :

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

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

Logging

Existing CXF features can be applied to jaxrs:server, whenever it makes sense.
To enable logging of requests and responses, simply do :

<jaxrs:server>
<jaxrs:features>
     <cxf:logging/>
</jaxrs:features>
<jaxrs:server>

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 :

public interface RequestHandler {
    
    Response handleRequest(Message inputMessage, 
                           ClassResourceInfo resourceClass);

}

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 :

OperationResourceInfo ori = exchange.get(OperationResourceInfo.class);

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 :

InputStream is = message.getContent(InputStream.class);
message.setContent(new MyFilterInputStream(is));
message.put(Message.ACCEPT_CONTENT_TYPE, "custom/media");
public interface ResponseHandler {
    
    Response handleResponse(Message outputMessage,
                           OperationResourceInfo invokedOperation, 
                           Response response);

}

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 :

// 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));
}

Please see this blog entry 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 :

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

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 :

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

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

Custom invokers

Using custom JAXR-RS invokers is yet another way to pre or post process a given invocation. For example, this invoker 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 :

<beans>

<jaxrs:server address="/"> 
 <jaxrs:invoker>
   <bean class="org.apache.cxf.systest.jaxrs.CustomJAXRSInvoker"/>
 </jaxrs:invoker>
</jaxrs:server>

</beans>

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.

Support for Continuations

Please see this blog entry describing how JAXRS (and indeed) JAXWS services can rely on the CXF Continuations API. Currently, only Jetty based services can rely on this option.

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

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 with the following permission :

grant codeBase "file:${catalina.home}/webapps/yourwebapp/lib/cxf.jar" {
    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
};

Configuring JAX-RS services

Configuring JAX-RS services programmatically

You can create a JAX-RS RESTful service by using JAXRSServerFactoryBean from the cxf-rt-frontend-jaxrs package:

JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(CustomerService.class);
sf.setAddress("http://localhost:9000/");
sf.create();

A couple 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:
    sf.setResourceProvider(BookStore.class, new SingletonResourceProvider());
  • If you prefer not to let the JAX-RS runtime to handle the resource class lifecycle for you (for example, it might be the case that your resource class is created by other containers such as Spring), you can do following:
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    CustomerService cs = new CustomerService();
    sf.setServiceBeans(cs);
    sf.setAddress("http://localhost:9080/");
    sf.create();

Configuring JAX-RS services in container with Spring configuration file.

web.xml

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

Using Spring ContextLoaderListener

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

The application context configuration is shared between all the CXFServlets

Using CXFServlet init parameters

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

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

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

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.

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.

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 :

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

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 :

public class CustomerService {
   public void doIt(String a, String b) {...};
}

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 :

@Path("/customers/{a}")
public class CustomerService {
   public void doIt(@PathParam("a") String a, String b) {...};
}

Note that CXF Continuations API is supported for both JAXWS and JAXRS services.

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 :

@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);
       }  
   }
}

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 :

@WebService
public class CustomerService {
   @Resource WebServiceContext jaxwsContext;
   // @Resource can be applied too
   @Context SecurityContext jaxrsSecurityContext;  
}

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 :

@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 {
       ...  
   }
}

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.

JAX-RS and Spring AOP

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

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

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 :

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);
    }
}

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 :

<aop:config proxy-target-class="true"/>

Areas for improvement and TODO list.

Optional auto-discovery of providers (classpath scanning) - needed for TCK
Support for Spring lifecycles (prototype, etc)

ASM-generate XmlJavaTypeAdapters when needed
Provide JAXP-Source provider capable of applying preconfigured XSLT templates or XPath expressions
Create some useful request filter implementations : JavaScript code generation, WADL or JavaDocs generation

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 and see if you are interested in fixing one of the issues.

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 :
> mvn test -Dtest=JAXRS*

Powered by Atlassian Confluence (Version: 2.2.9 Build:#527 Sep 07, 2006) - Bug/feature request

Unsubscribe or edit your notifications preferences