users@jersey.java.net

[Jersey] How to tell PerRequestTypeInjectableProvider that a type is not convertible?

From: cowwoc <cowwoc_at_bbs.darktech.org>
Date: Tue, 02 Oct 2012 01:38:50 -0400

Hi,

     I'm attempting to create a PerRequestTypeInjectableProvider that
will enable me to use joda-time's DateTime as a @QueryParam. Here is my
implementation:

import com.google.inject.Inject;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
import java.util.List;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.joda.time.DateTime;

@Provider
public class DateTimeInjector extends
PerRequestTypeInjectableProvider<QueryParam, DateTime>
{
     private final com.google.inject.Provider<UriInfo> uriInfo;

     /**
      * Creates a new DateTimeInjector.
      * <p/>
      * @param uriInfo an instance of {_at_link UriInfo}
      */
     @Inject
     public DateTimeInjector(com.google.inject.Provider<UriInfo> uriInfo)
     {
         super(DateTime.class);
         this.uriInfo = uriInfo;
     }

     @Override
     public Injectable<DateTime> getInjectable(final ComponentContext
cc, final QueryParam a)
     {
         return new Injectable<DateTime>()
         {
             @Override
             public DateTime getValue()
             {
                 final List<String> values =
uriInfo.get().getQueryParameters().get(a.value());
                 if (values.size() > 1)
                 {
                     throw new
WebApplicationException(Response.status(Status.BAD_REQUEST).
                         entity(a.value() + " may only contain a single
value").build());
                 }
                 if (values.isEmpty())
                     return null;
                 return new DateTime(values);
             }
         };
     }
}

     One section that bugs me is the Injectable throwing
WebApplicationException. getInjectable() method says I may return null
if the type is not convertable, but it turns out that uriInfo is not
injectable at that scope so I cannot access the actual HTTP query
parameters in order to make a decision. Returning null from the
Injectable, on the other hand, simply assigns null to the DateTime
reference.

     Is there a better way for me to tell Jersey that String -> DateTime
is not convertible when the query parameter contains multiple values?

Thank you,
Gili