users@jersey.java.net

Re: [Jersey] Optional JAXB Parameters

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Fri, 14 Aug 2009 08:41:20 +0200

H Jon,

You can do use EntityHolder:

   https://jersey.dev.java.net/nonav/apidocs/1.1.1-ea/jersey/com/sun/jersey/core/provider/EntityHolder.html

For example:

     @POST
     @Consumes(MediaType.APPLICATION_XML)
     @Path("/{name}")
     public Response getSummary(EntityHolder<Animal> ah,
             @PathParam(MessageConstants.NAME_PARAM) final String name
@DefaultValue("none") {
       Animal a = (ah.hasEntity()) ? ah.getEntity() : new Animal();
     }


For compliance with JAX-RS we need to ensure that the JAXB providers
require that an XML document be present. The semantics of dealing with
the presence or not of an entity really need to be determined by the
application and EntityHolder provides a generic solution to help in
that regard.

Paul.

On Aug 13, 2009, at 10:32 PM, Jonathan Holloway wrote:

> Hi,
>
> Please excuse the silly example, but I'm wondering whether it's
> possible to have JAXB annotated objects that are optional with
> Jersey/JAX-RS.
> In the example below I have an animal object which I bind to based
> on the XML present in the body of the POST request.
>
> @POST
> @Consumes(MediaType.APPLICATION_XML)
> @Path("/{name}")
> public Response getSummary(Animal animal,
> @PathParam(MessageConstants.NAME_PARAM) final String
> name @DefaultValue("none")
>
> However, what I want to do is to be able to cope with the body not
> containing an XML block. In this case I don't want it to attempt to
> find a reader for
> Animal, it would be great if I could just have it construct an empty
> Animal instance using the default constructor. At present this
> fails with:
>
> A message body reader for Java type, class com.test.Animal and MIME
> media type, application/octet-stream, was not found
>
> Is there a way to do this?
>
> Many thanks,
> Jon.