users@jersey.java.net

Re: [Jersey] Numbers in resource methods

From: Jason Winnebeck <gillius-ml_at_gillius.org>
Date: Tue, 22 Jun 2010 08:18:47 -0400

On 6/22/2010 3:16 AM, Craig McClanahan wrote:
>> @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 )
>
> 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.

I tested that the code works with returning both long and Long. Of course only
in the latter case can you return null, and in that case when you do Jersey
seems to be sending back a 204 No Content response. So if you want more
control than that, it seems that you would probably need to return a Response.

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

This suggestion I don't quite get. There is no possibility of conversion error
on the @GET method, since String.valueOf( long ) cannot fail. And if I
returned Response from getCounter, then it wouldn't use me NumberProvider at
all and you need to manually convert (although that's trivial on the response
side) -- however, it makes the object less like a "real" object you might use
elsewhere (internally, unit test, etc).

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

I know in Jersey you can map exceptions to responses, but I haven't played
with it yet. But from what I understand the conversion happens before my
method starts, so the exception declared on the addCounter method would not
matter? It seems the "disadvantage" to using a MessageReader is that it
chooses how to handle the conversion error, but I would think this is an
advantage because you don't have repeated boilerplate checking if a String is
a valid long. But since the MessageReader can only throw RuntimeExceptions,
Errors, and IOExceptions, I don't quite understand what you are suggesting?

Jason