java 6 and guice?

99 views
Skip to first unread message

nino martinez wael

unread,
Mar 4, 2010, 8:58:03 AM3/4/10
to google-guice
Hi Guys

First of all thank you for creating guice, it's much more light weight than spring (or at least as spring was before version 2.5).

I need to use this http://docs.sun.com/app/docs/doc/820-7627/giqdq java's restfull framework, the grizzly version  together with guice. But can't really see howto integrate? Anyone would know how?

Bob wrote something on it here : http://crazybob.org/2009/05/announcing-javaxinjectinject.html I guess just announcing stuff. But how do I actually integrate?

The Grizzly archetype produces some different thins, but most interesting this start up main.java:

    protected static SelectorThread startServer() throws IOException {
        final Map<String, String> initParams = new HashMap<String, String>();

        initParams.put("com.sun.jersey.config.property.packages",
                "com.netdesign.rest");

        System.out.println("Starting grizzly...");
        SelectorThread threadSelector = GrizzlyWebContainerFactory.create(BASE_URI, initParams);
        return threadSelector;
    }
   
    public static void main(String[] args) throws IOException {
        SelectorThread threadSelector = startServer();
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...",
                BASE_URI));
        System.in.read();
        threadSelector.stopEndpoint();
    }   
}

Or should I choose the archetype that builds a war file and add guice as a filter the ordinary way?

Regards Nino

Christian

unread,
Mar 4, 2010, 9:24:10 AM3/4/10
to google...@googlegroups.com
If you have the choice to run in a servlet container you can go with installing a GuiceFilter the regular way

http://code.google.com/p/google-guice/wiki/ServletModule

Then you serve the urls that you want with guice-jersey's com.sun.jersey.guice.spi.container.servlet.GuiceContainer servlet.

It will know mount with jersey all valid resources that have binding in the injector. (And they are created by guice)

As far as I know guice does not know about Jersey injection annotations. It has never been a problem to me since you can
get ServletRequest and Response from ServletModule itself.


For the Grizzly way, I got no knowledge. There's a GuiceComponentFactory in jersey-guice so maybe you can feed jersey with that directly.











2010/3/4 nino martinez wael <nino.mart...@gmail.com>

--
You received this message because you are subscribed to the Google Groups "google-guice" group.
To post to this group, send email to google...@googlegroups.com.
To unsubscribe from this group, send email to google-guice...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.

Eelco Hillenius

unread,
Mar 4, 2010, 1:06:57 PM3/4/10
to google...@googlegroups.com
I'm using a tweaked version of contribs/jersey-guice, part of the
jersey project. See
https://jersey.dev.java.net/nonav/apidocs/1.1.5/contribs/jersey-guice/index.html

Eelco

Eelco Hillenius

unread,
Mar 4, 2010, 1:19:24 PM3/4/10
to google...@googlegroups.com
> I'm using a tweaked version of contribs/jersey-guice, part of the
> jersey project. See
> https://jersey.dev.java.net/nonav/apidocs/1.1.5/contribs/jersey-guice/index.html

Here is the an example of code that I use to setup JAXRS/ Jersey with
Guice, but you have to read through the fluff a bit since we built a
mini framework around Guice.

Settings settings = new Settings();
settings.setSetting("com.sun.jersey.config.property.packages",
ErrorTrapTest.class.getPackage().getName());

Dependencies dependencies = new Dependencies(settings,
new ServletModule(), new LocalServiceRegistryModule(),
testModule, new SchedulerModule(settings),
new ErrorTrapModule());

ServletAdapter adapter = new ServletAdapter();
JerseyGuiceContainer container = dependencies
.getInstance(JerseyGuiceContainer.class);
adapter.setServletInstance(container);
GuiceFilter filter = new GuiceFilter();
adapter.addFilter(filter, "guiceFilter", null);

SelectorThread threadSelector = GrizzlyServerFactory.create(
"http://localhost:9998/", adapter);


In the code above, Settings is a boosted properties loader and
Dependencies a wrapper around Injector (which is created in the
constructor) that amongst other things binds settings to Names
(Names.bindProperties(binder(), settings.getProperties());).
JerseyGuiceContainer is a slightly tweaked version of GuiceContainer
(https://jersey.dev.java.net/nonav/apidocs/1.1.5/contribs/jersey-guice/com/sun/jersey/guice/spi/container/servlet/GuiceContainer.html).

Hope that helps,

Eelco

nino martinez wael

unread,
Mar 5, 2010, 2:55:18 AM3/5/10
to google...@googlegroups.com
Hi Eelco

Thanks for the response :)

Distilling it, it becomes something like this:


        ServletAdapter adapter = new ServletAdapter();
        Injector injector =Guice.createInjector(MyModule);
        GuiceContainer container=new GuiceContainer(injector);

        adapter.setServletInstance(container);
        GuiceFilter filter = new GuiceFilter();
        adapter.addFilter(filter, "guiceFilter", null);

        SelectorThread threadSelector = GrizzlyServerFactory.create(
                        "http://localhost:9998/", adapter);

Right?

\/\/
-Nino

2010/3/4 Eelco Hillenius <eelco.h...@gmail.com>

--

nino martinez wael

unread,
Mar 5, 2010, 3:32:31 AM3/5/10
to google...@googlegroups.com
Theres something wrong, worked fine with no guice bindings, but as soon as I got one I get this:

Starting grizzly...
2010-03-05 09:27:08 com.sun.jersey.server.impl.application.WebApplicationImpl initiate
INFO: Initiating Jersey application, version 'Jersey: 1.1.4.1 11/24/2009 01:30 AM'
2010-03-05 09:27:08 com.sun.jersey.server.impl.application.WebApplicationImpl processRootResources
SEVERE: The ResourceConfig instance does not contain any root resource classes.
2010-03-05 09:27:08 com.sun.grizzly.http.servlet.ServletAdapter service
SEVERE: service exception:
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
    at com.sun.jersey.server.impl.application.WebApplicationImpl.processRootResources(WebApplicationImpl.java:849)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:718)
    at com.sun.jersey.guice.spi.container.servlet.GuiceContainer.initiate(GuiceContainer.java:112)
    at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:253)
    at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:521)
    at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:199)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:308)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:471)
    at javax.servlet.GenericServlet.init(GenericServlet.java:241)
    at com.sun.grizzly.http.servlet.ServletAdapter.loadServlet(ServletAdapter.java:327)
    at com.sun.grizzly.http.servlet.ServletAdapter.service(ServletAdapter.java:268)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:165)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:659)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:577)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:829)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:162)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:136)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:103)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:89)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:67)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:269)
    at java.util.concurrent.FutureTask.run(FutureTask.java:123)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:595)

And the code:


    protected static SelectorThread startServer() throws IOException {
        final Map<String, String> initParams = new HashMap<String, String>();

        initParams.put("com.sun.jersey.config.property.packages",
                "com.netdesign.rest");

        System.out.println("Starting grizzly...");

        ServletAdapter adapter = new ServletAdapter();
        Injector injector = Guice.createInjector(new MyModule());
       
        GuiceContainer container = new GuiceContainer(injector);

        adapter.setServletInstance(container);
        GuiceFilter filter = new GuiceFilter();
        adapter.addFilter(filter, "guiceFilter", null);

        SelectorThread threadSelector = GrizzlyServerFactory.create(
                BASE_URI, adapter);


        return threadSelector;
    }

    public static void main(String[] args) throws IOException {
        SelectorThread threadSelector = startServer();
        System.out.println(String.format(
                "Jersey app started with WADL available at "
                        + "%sapplication.wadl\nHit enter to stop it...",
                BASE_URI));
        System.in.read();
        threadSelector.stopEndpoint();
    }


2010/3/5 nino martinez wael <nino.mart...@gmail.com>

Eelco Hillenius

unread,
Mar 5, 2010, 3:58:38 AM3/5/10
to google...@googlegroups.com
> com.sun.jersey.server.impl.application.WebApplicationImpl
> processRootResources
> SEVERE: The ResourceConfig instance does not contain any root resource
> classes.

Ah yes, I've seen that before. For some funny reason, Jersey refuses
to start up if it doesn't find anything to work with in the packages
you give it to scan. If you add a service, you should be good. At
least for that error :-)

Eelco

nino martinez wael

unread,
Mar 5, 2010, 3:59:54 AM3/5/10
to google...@googlegroups.com
Okay forgot the init params code now looks like this:


        ServletAdapter adapter = new ServletAdapter();
        Injector injector = Guice.createInjector(new MyModule());

        GuiceContainer container = new GuiceContainer(injector);
        adapter.setServletInstance(container);
        GuiceFilter filter = new GuiceFilter();
        adapter.addFilter(filter, "guiceFilter", null);
        adapter.addInitParameter("com.sun.jersey.config.property.packages",
                "com.netdesign.rest");
        SelectorThread threadSelector = GrizzlyServerFactory.create(BASE_URI,
                adapter);

But I get a null pointer where the injected property should have been called:


SEVERE: service exception:
java.lang.NullPointerException
    at com.netdesign.rest.MyResource.getIt(MyResource.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:156)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:208)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:75)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:115)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:67)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:775)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:740)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:731)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:372)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:452)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:633)

And a little code :

@Path("/myresource")
public class MyResource {

    private MessageDao myTest;
    // TODO: update the class to suit your needs
   
    // The Java method will process HTTP GET requests
    @GET
    // The Java method will produce content identified by the MIME Media
    // type "text/plain"
    @Produces("text/plain")
    public String getIt() {
        return myTest.getMessage();
    }
    @Inject
    public void setMyTest(MessageDao myTest) {
        this.myTest = myTest;
    }
   
   
}

and the module:

    @Override
    protected void configure() {
        bind(MessageDao.class).to(MyTest.class);

Eelco Hillenius

unread,
Mar 5, 2010, 4:20:39 AM3/5/10
to google...@googlegroups.com
> SEVERE: service exception:
> java.lang.NullPointerException
>     at com.netdesign.rest.MyResource.getIt(MyResource.java:58)
>     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
>     at
> sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
>     at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
>     at java.lang.reflect.Method.invoke(Method.java:585)
>     at
>

Not sure what's wrong, but you may be best of trying to follow the
documentation you can find here:
https://jersey.dev.java.net/nonav/apidocs/1.1.5/contribs/jersey-guice/index.html


Eelco

nino martinez wael

unread,
Mar 5, 2010, 4:41:01 AM3/5/10
to google...@googlegroups.com
Thanks i'll digg into it. And come back with the result..

2010/3/5 Eelco Hillenius <eelco.h...@gmail.com>
Eelco

nino martinez wael

unread,
Mar 5, 2010, 5:04:08 AM3/5/10
to google...@googlegroups.com
Ok got it semi working:

By doing this in my module:

        install(new ServletModule() {

            @Override
            protected void configureServlets() {
                bind(MyResource.class);

                Map<String, String> params = new HashMap<String, String>();
                params.put(PackagesResourceConfig.PROPERTY_PACKAGES, "unbound");
                serve("/*").with(GuiceContainer.class, params);

            }

But notice I have to register myResource, would've been nice if it could be picked up automaticly..

Again thanks for the help.

Now on to JDBC with guice. Have a case where I have to be able to look in "generic" tables... Meaning my application should be able to hook into any database and provide table content via REST ..


regards
Nino

2010/3/5 nino martinez wael <nino.mart...@gmail.com>
Thanks i'll digg into it. And come back with the result..

Eelco Hillenius

unread,
Mar 5, 2010, 10:46:04 AM3/5/10
to google...@googlegroups.com
> But notice I have to register myResource, would've been nice if it could be
> picked up automaticly..

Yeah, mine do get picked up automatically. I guess the debugger is
your friend. I also vaguely remember that either servlets or jaxrs
resources need to be annotated with @Singleton. Not sure if it would
help, but you could give that a spin.

Eelco

nino martinez wael

unread,
Mar 9, 2010, 5:28:04 AM3/9/10
to google...@googlegroups.com
Thanks, first shoot with singleton did not work.. :/ For now I'll work with what I have..


2010/3/5 Eelco Hillenius <eelco.h...@gmail.com>

Eelco

Reply all
Reply to author
Forward
0 new messages