users@jersey.java.net

Injecting JAXBContextProvider (Contextprovider<JAXBContext>) with Guice

From: Francisco A. Lozano <flozano_at_gmail.com>
Date: Tue, 15 Jun 2010 13:54:49 -0400

Hi,

I'm using grizzly stand-alone server, Jersey 1.2, Guice 2.0 and
jersey-guice integration.

I'm trying to make use of JSON natural notation with JAXB, so I've
implemented a ContextResolver<JAXBContext>. The problem is that the
getContext() method never gets called, so I always get the standard
notation of JSON.

I've annotated my ContextResolver with @Provider but I guess I have to
do something to make Guice aware of this component and inject it where
appropriate, and I don't know where to do that. Any hint?

My context resolver:

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {

    private JAXBContext context;
    private Class[] types = { UserBasic.class, UserBasicInformation.class };

    public JAXBContextResolver() throws Exception {
         this.context =
       new JSONJAXBContext(
         JSONConfiguration.natural().build(), types);
     }

    public JAXBContext getContext(Class<?> objectType) {
        /*
        for (Class type : types) {
            if (type == objectType) {
                return context;
            }
        }
        */
        return context;
    }
}

My resource method:

    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public JAXBElement<UserBasic> get(@QueryParam("userName") String userName) {
        ObjectFactory ob = new ObjectFactory();
        UserDTO dto = getUserService().getByUsername(userName);
        if(dto==null) throw new NotFoundException();
        UserBasic ub = new UserBasic();
        ub.setId(dto.getId());
        ub.setEmailAddress(dto.getEmailAddress());
        ub.setName(dto.getName());
        ub.setPhoneNumber(dto.getPhoneNumber());
        return ob.createUserBasic(ub);
    }

My Guice configuration module:

public class MyServletModule extends ServletModule {


    public static Module[] getRequiredModules() {
        return new Module[] {
                new MyServletModule(),
                new ServiceModule(),
                new CaptchaModule()
         };
    }


    @Override
    protected void configureServlets() {
        bind(UserHttpResource.class);
        bind(ContextResolver.class).to(JAXBContextResolver.class); // Wrong?
        serve("/*").with(GuiceContainer.class);
    }
}

In my Grizzly startup code I set
"com.sun.jersey.config.property.packages" to "unbound", but it doesn't
make any difference to set the real package of the resources.

Francisco A. Lozano