users@jersey.java.net

Re: [Jersey] Numbers in resource methods

From: Craig McClanahan <craigmcc_at_gmail.com>
Date: Tue, 22 Jun 2010 00:16:05 -0700

On Mon, Jun 21, 2010 at 10:05 PM, Jason Winnebeck
<gillius-ml_at_gillius.org> wrote:
> Hello all,
>
> I am learning Jersey 1.3 and so far have been amazed at the "automagicality"
> provided by JAX-RS -- how little you have to do to set up a powerful REST
> interface.
>
> What I was surprised to learn is that I could not return and take primitive
> types as entities in the resource methods like it can as @PathParam:
>
> @GET @Path( "{name}" ) @Produces( "text/plain" )
> public long getCounter( @PathParam( "name" ) String name )
>
> @POST @Path( "{name}" ) @Consumes( "text/plain" )
> public long addCounter(
>  @PathParam( "name" ) String name,
>  long toAdd )
>
> It's quite possible I missed something, but also possibly not because
> normally people are working with more complicated (JAXB) POJOs so this is
> not a typical case.
>
> I drafted a NumberProvider which can handle the numeric primitive types (not
> char and boolean). Assuming I am not missing something, maybe this is
> something useful for Jersey to support out-of-the-box? The code could
> probably be also made more generic for many more types, but I restricted it
> because I wasn't sure if it's best to try to work automatically with complex
> user types, where String might work technically but not be appropriate in
> the external interface.
>
> It converts the primitives to and from String, and if a nullable type,
> converts "null" to null. It does the same for outgoing, but it appears that
> Jersey treats a null return as 204 code rather than going through the
> provider (seems reasonable, rarely would you want to return null).
>
> I tried to do some error handling by returning 400 (I think that's right?)
> if the number can't be parsed.
>
> Jason

Two quick thoughts:

* I haven't tried this myself, but think about changing the return type
  from "long" to "java.lang.Long" so that it is formally an object. It may
  change what happens in the happy case.

* For handling conversion errors, you'll want to look at a couple of
  alternatives:

  - Have your method return a Response object, where you can set your
    own status code (along with any required headers). A common use case
    would be that, even if the incoming parameter was able to be converted
    to a long, there was some other semantic problem with the value.

  - Have your resource method throw an exception if the incoming value could
    not be converted, optionally providing your own "Provider" method
to determine
    what the actual response to the client should look like.

Craig


>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>