You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 144 Next »

Unknown macro: {span}

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

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

To incorporate JAX-RS, you will need:

   <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
      <version>2.2.3</version>
   </dependency>

This will in turn pull in 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.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/

Setting up the classpath in Eclipse or Ant

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

  • cxf-2.3.0-SNAPSHOT.jar
  • jsr311-api-1.0.jar
  • jaxb-impl-2.1.12.jar
  • jaxb-api-2.1.jar
  • geronimo-annotation_1.0_spec-1.1.1.jar
  • geronimo-activation_1.1_spec-1.0.2.jar
  • geronimo-servlet_2.5_spec-1.2.jar
  • commons-logging-1.1.1.jar
  • geronimo-stax_api_1.0_spec-1.0.1.jar
  • woodstox-core-asl-4.0.3.jar
  • stax2-api-3.0.1.jar
  • geronimo-jaxws_2.1_spec-1.0.jar
  • wsdl4j-1.6.2.jar
  • XmlSchema-1.4.5.jar
  • neethi-2.0.4.jar

For CXF 2.2.3 (2.2.4-SNAPSHOT) :

  • add cxf-2.2.3.jar (or cxf-2.2.4-SNAPSHOT.jar) instead of cxf-2.3.0-SNAPSHOT.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 two jetty jars shipped with CXF.

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

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;

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.

Have a look please at this exception mapper which converts Spring Security exceptions into HTTP 403 error code for another example.

Note that when no mappers are found for custom exceptions, they are propogated (wrapped in ServletException) to the underlying container as required by the specification. Thus one option for intercepting the exceptions is to register a custom servlet filter which will catch ServletExceptions and handle the causes. If no custom servlet filter which can handle ServletExceptions is available then most likely only 500 error status will be reported.

This propogation can be disabled by registering a boolean jaxrs property 'org.apache.cxf.propogate.exception' with a false value. If such property is set and no exception mapper can be found for a given exception then it will be wrapped into an xml error response by the CXF XMLFaultOutInterceptor.

One can also register a custom CXF out fault interceptor which can handle all the exceptions by writing directly to the HttpServletResponse stream or XMLStreamWriter (as XMLFaultOutInterceptor does). For example, see this test interceptor.

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

Note that on the trunk enums with fromValue() factory methods are also supported.

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("/map")
public class Service {

    
    @PUT
    @Path("/{mapvalue:(.)+}")
    public Response update(@PathParam("mapvalue") 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.

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

Parameter beans

There's 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.

Nested beans are also supported, which among other things, makes it possible to formulate advanced search queries. For example, given the following bean definitions :

class Name {
    String first;
    String last;
}

class Address {
    String city;
    String state;
}

class Person {
    Name legalName;
    Address homeAddr;
    String race;
    String sex;
    Date birthDate;
}

class MyService
{
    @GET
    @Path("/getPerson")
    Person getPerson(@QueryParam("") Person person);
} 

a query like

> /getPerson?sex=M&legalName.first=John&legalName.last=Doe&homeAddr.city=Reno&homeAddr.state=NV

will result in a Person bean being properly initialized and all the search criteria being captured and easily accessible. Note more enhancements are being planned in this area.

Resource lifecycles

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

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

@Path("/")
public class PerRequestResourceClass {

   public PerRequestResourceClass(@Context HttpHeaders headers, @QueryParam("id") Long id) {}
}

Classes with singleton scopes can only have contexts injected at the construction time and it is only a CXFNonSpringJaxrsServlet which can do it. In most cases you can have contexts injected as bean properties straight after the construction time

See the "Lifecycle management" section for more details.

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

Custom selection between multiple resources

The JAX-RS selection algorithm has been designed with a lot of attention being paid to various possible cases, as far as the selection between multiple matching resource classes or methods is concerned.

However, in some cases, the users have reported the algorithm being somewhat restrictive in the way multiple resource classes are selected. For example, by default, after a given resource class has been matched and if this class has no matching resource method, then the algorithm stops executing, without attempting to check the remaining matching resource classes.

Starting from CXF 2.2.5 it is possible to register a custom ResourceComparator implementation using a jaxrs:server/resourceComparator element.

Custom implementations can check the names of the resource classes or methods being compared and given the current request URI they can make sure that the required class or method is chosen by returning either -1 or 1, as needed. If 0 is returned then the runtime will proceed with executing the default selection algorithm. At the moment the easiest way to get to the details such as the current request URI is to create an instance of the CXF JAXRS UriInfoImpl using a constructor accepting a Message.

Note that by the time a custom ResourceComparator is called the provided resource classes or methods have already been successfully matched by the runtime.

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">
<entry key="jaxb.formatted.output">
   <value type="java.lang.Boolean">true</value>
</entry>
</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.

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

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

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

Marshall, unmarshall and context properties can be configured as well for both JAXB and JSON providers.

JSON support

Default JSON provider relies on Jettison 1.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 is a well known problem in the JSON community which shows itself in the wrong serialization of List objects containing a single value only. To work around this issue, one needs to enable a 'serializeAsArray' feature on a JSONProvider, with the additional option of specifying the individual fields which needs to be processed accordingly using an 'arrayKeys' property. Please see this example for more information.

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

@XmlRootElement()
@XmlType(name = "", propOrder = {"title", "comments" })
public static class Post {
    private String title;
    private List<Comment> comments = new ArrayList<Comment>();
    public void setTitle(String title) {
        this.title = title;
    }
    public String getTitle() {
        return title;
    }
    public void setComments(List<Comment> comments) {
        this.comments = comments;
    }
    public List<Comment> getComments() {
        return comments;
    }
}
   
public static class Comment {
     private String title;

     public void setTitle(String title) {
        this.title = title;
     }

     public String getTitle() {
         return title;
     }
} 

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

> {"post":{"title":"post","comments":[{"title":"comment1"},{"title":"comment2"}]}}

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

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

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

BadgerFish convention

Starting from CXF 2.2.5 it is possible to configure JSONProvider to support a BadgerFish convention. By default a "mapped" convention is supported, set a JSONProvider "convention" property with the value "badgerfish" if you'd like to work with the BadgerFish convention.

Wrapping and Unwrapping JSON sequences

A "wrapperName" string property can be used to append a dropped root element name to an incoming JSON sequence for it to be deserialized properly. A "wrapperMap" map property can be used to nominate wrapper names for individual class names. In both cases, a 'supportUnwrapped' boolean property also has to be set.

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

Automatic JAXBElement conversion during serialization

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

Note that this property is supported for both JAXB and JSON providers.

Handling JAXB beans without XmlRootElement annotations

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

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

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

Handling explicit collections

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

There's also a 'collectionWrapperMap' property available for use in more advanced cases, when collections of different types are used, for example, when mixed collections of objects descended from abstract classes having no @XmlRootElement tags are returned :

<!-- Configure JAXB Provider -->
<bean id="jaxbProvider"
class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
  <property name="collectionWrapperMap">
  <map>
    <entry>
      <key><value>com.foo.bar.MyObject</value></key>
      <value>MyObjects</value>
    </entry>
   </map>
   </property>
</bean> 

JSONProvider can only serialize explicit collections at the moment. If needed, it can be told to drop a collection element name using a boolean 'dropCollectionWrapperElementName'. For example, a 'dropCollectionWrapperElementName' and 'serializeAsArray' properties can be used to make the Dojo JSON RestStore consume the resulting JSON sequence (in CXF 2.2.5).

Customizing JAXB and JSON input and output

The previous sections have already listed a number of properties which can be used by JAXB and/or JSON providers to have the output and input (in some limited cases) customized. For example, "dropRootElement", "writeXsiType", "ignoreNamespaces" and "wrapperName" properties can be used to affect the JSON sequences. Additionally, users can choose to register custom XMLStreamWriter and XMLStreamReader STAX parsers or use XSLTJaxbProvider to affect the input/output for JAXB and the output for JSON.

In CXF 2.2.5, a new feature has been introduced whose goal is to generalize and simplify in a number of cases the way both JAXB and JSON can be customized.

The following configuration properties have been added to the base JAXB/JSON AbstractJAXBProvider :

  • "outElementsMap" map property : can be used to change the output element names and change or drop namespaces; keys are the elements to be changed, values are the new element names. Eamples:

> book:thebook - change "book" to "thebook"
> {http://books}book:book - drop the namespace from "book"
> book:{http://books}thebook - change "book" to a different qualified name

  • "inElementsMap" map property : can be used to change the input element names and change or drop namespaces; see "outElementsMap"
  • "outAppendMap" map property : can be used to append new simple or qualified elements to the output; keys are the new elements, values are the elements the new ones will be appended before. Examples:

> book:thebook - append "book" before "thebook"
> {http://books}book:book - append the namespace to the "book"
> book:{http://books}book - drop the namespace from the "book"

  • "inAppendMap" map property : can be used to append new simple or qualified elements to the input; see "outAppendMap"
  • "outDropElements" list property : can be used to drop elements during the serialization; note that children elements if any of a given dropped element are not affected. Examples:

> index, {http://numbers}number - drop "index" and {http://numbers}number elements

  • "inDropElements" list property : can be used to drop elements during the deserialization; note that children elements if any of a given dropped element are not affected.
  • "attributesAsElements" boolean property : can be used to have attributes be serialized as elements.

The combination of "attributesAsElements" and "outDropElements" properties can be used to have certain attributes ignored in the output.

This feature might be used in a number of cases. For example, one may have rootless JSON array collections such as "a:b},{c:d" deserialized into a bean by using a "wrapperName" JSONProvider property with a value like "list" which identifies a bean field and an "inAppendMap" property with a name of the bean (ex, "book") being appended before the "list", thus effectively turning the original JSON sequence into "{book:{list:a:b},{c:d}}".

// TODO : add more examples

Aegis Data Binding

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

XMLBeans

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

Support for CXF DataBindings

Starting from CXF 2.2.3 it is now possible to register a CXF DataBinding bean using a jaxrs:databinding element and it will be wrappped as a JAXRS MessageBodyReader/Writer DataBindingProvider capable of dealing with XML-based content. It can be of special interest to users combining JAX-RS and JAXWS. Thus CXF JAXB, Aegis, SDO and XMLBeans databindings can be easily plugged in.
JSON support is also provided for all these databindings by DataBindingJSONProvider.
Please see this configuration file for some examples.

Similarly to the default JSONProvider the DataBindingJSONProvider JSON provider can have "namespaceMap", "serializeAsArray", "arrayKeys", "dropRootElement" and "writeXsiType" properties set. Additionally it may also have an "ignoreMixedContent" property set.

Note that at the moment this feature is only available on the trunk. JAXB and Aegis DataBindings (XML only) is supported in CXF 2.2.3.

Customizing request and response XML

Sometimes you may want to adapt an incoming XML request or outgoing XML response. For example, your application has changed but a lot of legacy clients have not been updated yet.
When dealing with XML, the easiest and fastest option is to register a custom STAX XMLStreamWriter or XMLStreamReader and modify XML as needed. You can register a custom STAX
handler from RequestHandler or ResponseHandler filters or input/output CXF interceptors. For example, see XMLStreamWriterProvider and CustomXmlStreamWriter.

Another option is to register a custom JAXB or JSON provider extending CXF JAXBElementProvider or JSONProvider and overriding a method like createStreamWriter().
Typically one would delegate to a super class first and then wrap the returned writer in a custom writer, see CustomXmlStreamWriter for an example.

One can also use XSLTJaxbProvider to produce or modify the incoming XML. In fact, XSLTJaxbProvider can be used to adapt formats like JSON for legacy consumers.

Please also see this overview of various related features available in CXF.

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.

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 or jaxrs:client, whenever it makes sense.
To enable logging of requests and responses, simply do :

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

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

ATOM push-style logging

Since 2.2.6 CXF supports collecting log events, converting them to ATOM Syndication Format and pushing to the client. Logging is based on custom java.util.logging (JUL) handler that can be registered with loggers extending today's publishing protocols.

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

Configuration of ATOM logging can be done in multiple formats and with wide range of details level.

Spring configuration

In simplest case pushing ATOM Feeds can be declared this way:

   <bean class="org.apache.cxf.jaxrs.ext.logging.atom.AtomPushBean" init-method="init">
       <property name="url" value="http://somewhere.com/foo/bar"/>
       <property name="level" value="ALL" />
   </bean>

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:

   <bean class="org.apache.cxf.jaxrs.ext.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>

To push to client events generated by different loggers on different levels, "loggers" property must be used instead of pair "logger" and "level":

   <bean class="org.apache.cxf.jaxrs.ext.logging.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>

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:

   <bean class="org.apache.cxf.jaxrs.ext.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>

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:

   <bean id="soapDeliverer" ...
   ...
   <bean class="org.apache.cxf.jaxrs.ext.logging.atom.AtomPushBean" init-method="init">
       <property name="deliverer">
           <ref bean="soapDeliverer"/>
       </property>
       <property name="loggers" ... />
   </bean>

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:

   <bean id="atom1" class="org.apache.cxf.jaxrs.ext.logging.atom.AtomPushBean" init-method="init">
       <property name="url" value="http://someplace.com/foo/bar"/>
       ...
   </bean>
   <bean id="atom2" class="org.apache.cxf.jaxrs.ext.logging.atom.AtomPushBean" init-method="init">
       <property name="url" value="http://otherplace.com/baz/blah"/>
       ...
   </bean>
   ....

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:

 handlers = org.apache.cxf.jaxrs.ext.logging.atom.AtomPushHandler, java.util.logging.ConsoleHandler
 .level = INFO
 ...
 org.apache.cxf.jaxrs.ext.logging.atom.AtomPushHandler.url = http://localhost:9080
 org.apache.cxf.jaxrs.ext.logging.atom.AtomPushHandler.batchSize = 10
 org.apache.cxf.jaxrs.ext.logging.atom.AtomPushHandler.deliverer = WebClientDeliverer 
 org.apache.cxf.jaxrs.ext.logging.atom.AtomPushHandler.converter = foo.bar.MyConverter
 org.apache.cxf.jaxrs.ext.logging.atom.AtomPushHandler.retry.pause = linear
 org.apache.cxf.jaxrs.ext.logging.atom.AtomPushHandler.retry.pause.time = 10
 org.apache.cxf.jaxrs.ext.logging.atom.AtomPushHandler.retry.timeout = 360
 ...

Programming style

In most complex cases direct programming using org.apache.cxf.jaxrs.ext.logging.atom 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:

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

is equivalent to Spring configuration:

   <bean class="org.apache.cxf.jaxrs.ext.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>

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.

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.

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.

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 :

String s = m.get(Message.REQUEST_URI);
s += "/data/";
m.put(Message.REQUEST_URI, s);

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.

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 :

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.RESPONSE_HEADERS);
        // modify headers  
    }    

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.

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 :

message.getExchange().put("ignore.response.writers", true);

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

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

public class AuthenticationHandler implements RequestHandler {

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

}

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

Client API

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

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 is a utility class which wraps JAXRSClientFactoryBean. JAXRSClientFactory has a number of utility methods but JAXRSClientFactoryBean can be used directly when needed.

For example, given these class definitions :

@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() {}
}

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

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

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.

Customizing proxies

Proxies end up implementing not only the interface requested at the proxy creation time but also a Client 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 utility method for converting a proxy to a base client :

BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class);
WebClient.client(proxy).accept("text/xml");
// continue using the proxy    

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

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 :

BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class);
WebClient client = WebClient.create(proxy);
// continue using the http client    

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

BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class);
WebClient client = WebClient.create(proxy);
BookStore proxy = JAXRSClientFactory.fromClient(client, BookStore.class);

Handling exceptions

There is a couple of ways you can handle remote exceptions with proxies.
One approach is to register a ResponseExceptionMapper 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 a WebApplicationException will be thrown. At this point of time you can check the actual Response and proceed from there :

BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class);
try {
    proxy.getBook();
} catch(WebApplicationException ex) {
  Response r = WebClient.create(proxy).getResponse();
  // check error code, try using WebClient explicitly, etc
}

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 :

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

Injecting proxies

See this bean for an example how jaxrs:client can be used to inject a proxy

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.

Proxies are currently not thread-safe.

HTTP-centric clients

HTTP centric clients are WebClient instances which also implement the Client 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 :

WebClient client = WebClient.create("http://books");
Book book = client.path("bookstore/books").accept("text/xml").get(Book.class);

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

WebClient client = WebClient.create("http://books");
Response r = client.path("bookstore/books").type("text/xml").accept("text/xml").post(new Book());
InputStream is = (InputStream)r.getEntity();
Book b = getFromInputStreamUsingJaxb(is);

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 :

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

The above code will send requests like "GET http://books/1", "GET http://books/2", etc.

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 a WebApplicationException and get a Response from it.

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.

XML-centric clients

XML-centric clients are WebClients using an XMLSource 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 :

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

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

Configuring Clients at Runtime

Proxy and http-centric clients are typically created by JAXRSClientFactory or WebClient factory methods but JAXRSClientFactoryBean 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 :

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

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 :

<http:conduit name="http://books:9095/bookstore.*"/> 

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 for more examples.

Alternatively you can just do :

<http:conduit name="*.http-conduit"/> 

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:

<http:conduit name="{http://foo.bar}BookService.http-conduit"/> 

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

Similarly, for WebClients you can do :

<http:conduit name="{http://localhost:8080}WebClient.http-conduit"/> 

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

Please see this configuration file for more examples.

Also see this wiki page on how to configure HTTPConduits.

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.

XPath support

XPath is supported on the server and client sides with the help of XMLSource utility class. Please see above how http-centric WebClients can use XPath, here is an example for the server side :

@Path("/root")
public class Root {
   @POST
   public void post(XMLSource source) {
       String value = source.getProperty("/books/book/@name");
   }    
}

Users have an option to hide XPath expressions, by registering an XPathProvider, either on client or server sides. For example :

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

XSLT support

XSLT is currently supported by XSLTJaxbProvider. 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 :

@Path("/root")
public class Root {
   @GET
   @Path("{id}") 
   public Book get(@PathParam("id") String id, @QueryParam("name") String name) {
       return getBook(id, name);
   }    
}

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 :

WebClient client = WebClient.create("http://books");
client.path("/store/1").get();

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 :

WebClient client = WebClient.create("http://books");
client.path("/store/{id}", 1).get();

Redirection

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

With RequestDispatcherProvider

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

With CXFServlet

Please see the "Redirection" section on the 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.

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.

Model-View-Controller support

XSLT

Please see this blog entry on how XSLTJaxbProvider can be used to generate complex (X)HTML views.

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.

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

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.

Reading attachments

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

For example :

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

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 with Attachment making it easy to deal with a given part :

@POST
public void addAttachments(List<Attachment> atts) throws Exception {
}

For example, Attachment class can be used to get to a Content-Disposition header, when dealing with the form submission of files.

Similarly, the whole request body can be represented as a MultipartBody :

@POST
public void addAttachments(MultipartBody body) throws Exception {
body.getAllAtachments();
body.getRootAttachment();
}

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 :

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

When a user code has MessageContext injected, AttachmentUtils can also be used by the application code.

Please see these test resource class and blog entry for more examples.

Forms and multiparts

The Forms in HTML documents recommendation suggests 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 can be handled by a method with the following signature :

@POST
@Path("/books/jsonform")
@Consumes("multipart/form-data")
public Response addBookJsonFromForm(Book b1)  {...}

Similarly, this request can be handled by a method with the following signature :

@POST
@Path("/books/jsonjaxbform")
@Consumes("multipart/form-data")
public Response addBookJaxbJsonForm(@Multipart("jsonPart") Book b1,
                                        @Multipart("bookXML") Book b2) {}

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 can be handled by a method with the signature like :

@POST
@Path("/books/filesform")
@Produces("text/xml")
@Consumes("multipart/form-data")
public Response addBookFilesForm(@Multipart("owner") String name,
                                 @Multipart("files") List<Book> books) {} 

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.

Writing attachments

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

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

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

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 :

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

}

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 :

public class Resource {
   @Produces("multipart/form-data")
   @Multipart(value = "root", type = "application/octet-stream") 
   public File testGetImageFromForm() {
      return getClass().getResource("image.png").getFile();
   }
}

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 :


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

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 :

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

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.

Uploading files

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


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

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

Reading large attachments

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

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

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

Service listings and WADL support

CXF JAX-RS now supports the auto-generation of 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

Base address : 'http://localhost:8080'
WAR name : 'store'
CXFServlet : '/books/*'
jaxrs:server/@address = '/orders'
jaxrs:server/@staticSubresourceResoulution = 'true'

and 2 root resource classes registered with this endpoint, say

@Path("/fiction") 
public class FictionBookOrders {
}
@Path("/sport") 
public class SportBookOrders {
}

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

Documenting resource classes and methods in WADL

WADL documents can include doc fragments. Users may want to use Description annotations which can be attached to resource classes and methods.

Configuring JAX-RS services

Configuring JAX-RS services programmatically 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 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:
    sf.setResourceProvider(BookStore.class, new SingletonResourceProvider(new BookStore()));
    
  • 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 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 :

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

Configuring JAX-RS clients programmatically without Spring

Example :

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

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>

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 :

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

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 :

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

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.

Attaching JAXRS endpoints to an existing Jetty server

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

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, "/*");

Configuring JAX-RS services programmatically with Spring configuration file.

When using Spring explicitly in your code, you may want to follow this example :

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

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

<!--
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
-->
<import resource="classpath:META-INF/cxf/cxf-extension-http-jetty.xml" />

Lifecycle management

From Spring

The singleton scope is applied to all service beans which are injected like this :

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

You can support prototypes by either using a beanNames attribute or schemaFactories element :

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

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 :

@Path("/")
public class SingletonResourceClass {
   public SingletonResourceClass(@Context ServletContext context, @Context ServletConfig context2) {}
}

Programmatically

JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClass(CustomerService.class);
sf.setResourceProvider(new SingletonResourceProvider(new CustomerService()));
sf.setResourceClass(CustomerService2.class);
sf.setResourceProvider(new PerRequestResourceProvider(CustomerService.class));

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.

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

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

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.

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.

Here is an example :

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

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

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

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

Please also see this system test 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 :

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

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

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

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

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

  • No labels