@Inject using Jersey don't work

448 views
Skip to first unread message

Gabriel Cardelli

unread,
Jun 19, 2011, 7:56:38 PM6/19/11
to google...@googlegroups.com
I'm trying to set up a project using Google Guice 3.0 JAX-RS and Jersey 1.7 for the server side however google guice is not injecting any class.

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
version="2.4">

<display-name>Institucional Eventos - Wicket Application</display-name>

<listener>
<listener-class>br.impa.apps.eventos.config.servlet.listener.ImpaGuiceServletContextListener</listener-class>
</listener>

<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>br.impa.apps.eventos.ws</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/ws/*</url-pattern>
</servlet-mapping>

</web-app>

ImpaGuiceServletContextListener

public class ImpaGuiceServletContextListener extends GuiceServletContextListener{

private final transient Logger log = Logger.getLogger(ImpaGuiceServletContextListener.class);
@Override
protected Injector getInjector() {
log.info("getInject() - Executando");
return Guice.createInjector(new EventosModule());
 
}
}

EventosModule 
public class EventosModule extends ServletModule {

private final transient Logger log = Logger.getLogger(EventosModule.class.getName());
public final static String PERSISTENCE_UNIT = "eventosImpa";

public void configureServlets() {
log.info("Configurando Modulo - Eventos");
final Map<String, String> params = new HashMap<String, String>();
params.put("javax.ws.rs.Application", "br.impa.apps.eventos.config.module.JerseyApp");
install(new JpaPersistModule(PERSISTENCE_UNIT));
filter("/*").through(PersistFilter.class);
bind(EventoService.class).to(EventoServiceImpl.class).in(Singleton.class);
filter("/*").through(GuiceFilter.class);
log.info("Cofigurando Modulo JPA");
}

}

Web Service Rest
@Path("/evento")
@RequestScoped
public class EventoWS {

private final transient Logger log = Logger.getLogger(EventoWS.class);
@Inject
private EventoService eventoService;
@GET 
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Evento> list() {
log.info("Executando método list()");
log.info("EventoService: " + eventoService );
        return eventoService.list(null);
    }

public void setEventoService(EventoService eventoService) {
this.eventoService = eventoService;
}
}


When I try to run the web service
 eventoService is null,
 I am not able to understand why?

thks all!

Gabriel Cardelli
Software Developer


Mischa Dasberg

unread,
Jun 20, 2011, 2:42:00 AM6/20/11
to google...@googlegroups.com
Hi Gabriel,

Try adding the following in your Module:

bind(EventoWS.class);

That should work.

Regards,

Mischa

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

Gabriel Cardelli

unread,
Jun 21, 2011, 5:50:28 PM6/21/11
to google...@googlegroups.com
I have two projects, server and client.

The server has the Jersey and Guice, the 
client has Wicket and Guice (Inject OK)
I'm trying to expose my web service to be consumed by wicket

The big problem is that server-side Guice does not work.

When I call the web service it returns java.lang.NullPointerException
         at br.impa.apps.eventos.ws.EventoWS.list (EventoWS.java: 34)

Line 34 is: return eventoService.list ();

eventoService should be injected by Guice but is not.

Someone tell me what's going on?




-----------------------------------
   Gabriel Cardelli
   Software Developer
   gabrcardelli.appspot.com
-----------------------------------





2011/6/20 Mischa Dasberg <mis...@dasberg.nl>

Gabriel Cardelli

unread,
Jun 21, 2011, 5:51:46 PM6/21/11
to google...@googlegroups.com
Mischa Dasberg, added what you said and the error continues

thz
-----------------------------------
   Gabriel Cardelli
   Software Developer
   gabrcardelli.appspot.com
-----------------------------------





2011/6/21 Gabriel Cardelli <gabrielcasti...@gmail.com>

Christopher Currie

unread,
Jun 21, 2011, 6:21:40 PM6/21/11
to google...@googlegroups.com
Gabriel,

On github there is a minimal working Jersey + Guice application that
might serve as a starting point for modification for your service.

https://github.com/sunnygleason/j4-minimal

In particular, I think that the reason your Resource class isn't
getting injected is because you are using the Jersey ServletContainer
as your servlet in your web.xml. Guice servlet is different; the
request is handled at the filter level, and any servlets configured in
the web.xml should (ideally) never be called.

I think you will need, at the end of EventosModule, after the "filter"
line, to add:

Map<String,String> jerseyParams = new HashMap<String,String>();
jerseyParams.put("com.sun.jersey.config.property.packages",
"br.impa.apps.eventos.ws");
serve("/ws/*").with(GuiceContainer.class, jerseyParams);

Also note that if you declare all of your Resource classes with
"bind()" calls as Mischa suggests, then you don't need the
jerseyParams argument.

Please carefully read the docs on Guice Servlet:
http://code.google.com/p/google-guice/wiki/ServletModule

Good luck,
Christopher

Gabriel Cardelli

unread,
Jun 21, 2011, 6:30:44 PM6/21/11
to google...@googlegroups.com
Christopher, thanks for your tips, I will check now


-----------------------------------
   Gabriel Cardelli
   Software Developer
   gabrcardelli.appspot.com
-----------------------------------





2011/6/21 Christopher Currie <chris...@currie.com>

Gabriel Cardelli

unread,
Jun 21, 2011, 7:21:28 PM6/21/11
to google...@googlegroups.com
When I delete the mapping of the web.xml I get the following error
 HTTP Status 404 - /eventos / ws / evento

With the WEB.XML mapping ( Success but not inject )

INFO  - uiceServletContextListener - getInject() - Executando
INFO  - EventosModule              - Configurando Modulo - Eventos
INFO  - EventosModule              - Cofigurando Modulo JPA
21/06/2011 18:53:49 com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
21/06/2011 18:53:49 com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class br.impa.apps.eventos.ws.EventoWS
21/06/2011 18:53:49 com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
21/06/2011 18:53:50 com.sun.jersey.server.impl.application.WebApplicationImpl _i
nitiate
INFO: Initiating Jersey application, version 'Jersey: 1.7 05/20/2011 11:04 AM'

Without the WEB.XML mapping ( 404 )

INFO  - uiceServletContextListener - getInject() - Executando
INFO  - EventosModule              - Configurando Modulo - Eventos
21/06/2011 20:15:58 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory docs
21/06/2011 20:15:58 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory examples
21/06/2011 20:15:59 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory host-manager
21/06/2011 20:15:59 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory manager

Estou tentando resolver o problema, qualquer avanço eu digo.
-----------------------------------
   Gabriel Cardelli
   Software Developer
   gabrcardelli.appspot.com
-----------------------------------

Gabriel Cardelli

unread,
Jun 21, 2011, 7:30:29 PM6/21/11
to google...@googlegroups.com
When I delete the mapping of the web.xml I get the following error
 HTTP Status 404 - /eventos / ws / evento

With the WEB.XML mapping ( Success but not inject )

INFO  - uiceServletContextListener - getInject() - Executando
INFO  - EventosModule              - Configurando Modulo - Eventos
INFO  - EventosModule              - Cofigurando Modulo JPA
21/06/2011 18:53:49 com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
21/06/2011 18:53:49 com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class br.impa.apps.eventos.ws.EventoWS
21/06/2011 18:53:49 com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
21/06/2011 18:53:50 com.sun.jersey.server.impl.application.WebApplicationImpl _i
nitiate
INFO: Initiating Jersey application, version 'Jersey: 1.7 05/20/2011 11:04 AM'

Without the WEB.XML mapping ( 404 )

public class EventosModule extends ServletModule {

private final transient Logger log = Logger.getLogger(EventosModule.class
.getName());

public final static String PERSISTENCE_UNIT = "eventosImpa";

public void configureServlets() {

log.info("Configurando Modulo - Eventos");

final Map<String, String> params = new HashMap<String, String>();

install(new JpaPersistModule(PERSISTENCE_UNIT));
filter("/*").through(PersistFilter.class);

Map<String, String> jerseyParams = new HashMap<String, String>();
jerseyParams.put("com.sun.jersey.config.property.packages",
serve("/ws/*").with(GuiceContainer.class, jerseyParams);

}

}

INFO  - uiceServletContextListener - getInject() - Executando
INFO  - EventosModule              - Configurando Modulo - Eventos
21/06/2011 20:15:58 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory docs
21/06/2011 20:15:58 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory examples
21/06/2011 20:15:59 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory host-manager
21/06/2011 20:15:59 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory manager

I'm trying to solve the problem, any progress I say.

Christopher Currie

unread,
Jun 21, 2011, 7:34:04 PM6/21/11
to google...@googlegroups.com
You need to have *some* servlet in web.xml, or the filter won't get
called. Typical practice is to have a simple servlet, bound to '/' (as
the default servlet), that logs an error, since it should not be
called if the Guice Filter is handling the requests. Look at the
j4-minimal project I referenced for an example.

C

Gabriel Cardelli

unread,
Jun 21, 2011, 7:43:11 PM6/21/11
to google...@googlegroups.com
Ok Chris, sorry.

I'm configuring.
-----------------------------------
   Gabriel Cardelli
   Software Developer
   gabrcardelli.appspot.com
-----------------------------------





2011/6/21 Christopher Currie <chris...@currie.com>

Christopher Currie

unread,
Jun 21, 2011, 8:04:45 PM6/21/11
to google...@googlegroups.com
No need to apologize. The setup is a bit mysterious until you see it
work together. Good luck.


On 6/21/11, Gabriel Cardelli <gabrielcasti...@gmail.com> wrote:
> Ok Chris, sorry.
>
> I'm configuring.

> *-----------------------------------*
> * Gabriel Cardelli
> ** Software Developer
> ** **gabrcardelli.appspot.com*
> *
> -----------------------------------
> *
> *
>
>
> *

--
Sent from my mobile device

Gabriel Cardelli

unread,
Jun 22, 2011, 7:46:09 AM6/22/11
to google...@googlegroups.com

when I put the GuiceFilter in web.xml.I get the following message in terminal:
 
INFO  - uiceServletContextListener - getInject() - Executando
INFO  - EventosModule              - Configurando Modulo - Eventos
INFO  - Version                    - Hibernate Annotations 3.4.0.GA
INFO  - Environment                - Hibernate 3.3.0.SP1
INFO  - Environment                - hibernate.properties not found
INFO  - Environment                - Bytecode provider name : javassist
INFO  - Environment                - using JDK 1.4 java.sql.Timestamp handling
INFO  - Version                    - Hibernate Commons Annotations 3.1.0.GA
INFO  - Version                    - Hibernate EntityManager 3.4.0.GA
22/06/2011 08:33:53 org.apache.catalina.core.StandardContext startInternal
GRAVE: Error filterStart
22/06/2011 08:33:53 org.apache.catalina.core.StandardContext startInternal
GRAVE: Context [/eventos] startup failed due to previous errors
22/06/2011 08:33:53 org.apache.catalina.loader.WebappClassLoader clearReferences
Threads
GRAVE: The web application [/eventos] appears to have started a thread named [co
m.google.inject.internal.util.$Finalizer] but has failed to stop it. This is ver
y likely to create a memory leak.

 
when I put the filter in ServletModule. I get the following message on the console:
 
INFO  - uiceServletContextListener - getInject() - Executando
INFO  - EventosModule              - Configurando Modulo - Eventos

 

web.xml
 
 <?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="
http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
 version="2.4">
 <display-name>Institucional Eventos - Wicket Application</display-name>
 <listener>
  <listener-class>br.impa.apps.eventos.config.servlet.listener.ImpaGuiceServletContextListener</listener-class>
 </listener>
 <servlet>
 
  <servlet-name>servlet</servlet-name>
  <servlet-class>br.impa.apps.eventos.config.servlet.listener.EmptyServlet</servlet-class>
 
 </servlet>
 
 <servlet-mapping>
 
  <servlet-name>servlet</servlet-name>
  <url-pattern>/*</url-pattern>
 
 </servlet-mapping>
</web-app>
 
Module:
 
 public class EventosModule extends ServletModule {
 
 private final transient Logger log = Logger.getLogger(EventosModule.class
   .getName());
 
 public final static String PERSISTENCE_UNIT = "eventosImpa";
 
 public void configureServlets() {
 
  log.info("Configurando Modulo - Eventos");
  final Map<String, String> params = new HashMap<String, String>();
  install(new JpaPersistModule(PERSISTENCE_UNIT));
  filter("/*").through(PersistFilter.class);
  Map<String, String> jerseyParams = new HashMap<String, String>();

  jerseyParams.put("com.sun.jersey.config.property.packages","br.impa.apps.eventos.ws");
  serve("/ws/*").with(GuiceContainer.class, jerseyParams);
  
  filter("/*").through(GuiceFilter.class);
  
 }
}
 
thx
-----------------------------------------------

   Gabriel Cardelli
   opengti.com.br - Software Developer
 
-----------------------------------------------
 
 

Christopher Currie

unread,
Jun 23, 2011, 1:31:58 AM6/23/11
to google...@googlegroups.com
You definitely do *not* want to put Guice Filter in the Servlet
Module; the Guice Filter needs to be in your web.xml as documented in
the Guice Servlet documentation.

At this point I don't know what might be causing your startup errors.
I recommend starting with a working example such as the j4-minimal
sample, and slowly replacing it with your own code.

Good luck,
Christopher

Gabriel Cardelli

unread,
Jul 3, 2011, 8:00:54 PM7/3/11
to google...@googlegroups.com
I solved the problem, 

My Classes:

public class GuiceServletConfig extends GuiceServletContextListener {

    @Override
    protected Injector getInjector() {
        Injector i = Guice.createInjector(new ServletModule() {

            @Override
            protected void configureServlets() {
                // Bind classes
                bind(PerRequestResource.class);
                bind(EventoWS.class);
                bind(EventoService.class).to(EventoServiceImpl.class);
                bind(EventoDAO.class).to(EventoDAOImpl.class);
                bind(Principal.class).toProvider(PrincipalProvider.class);
                bind(SecurityContext.class).to(MySecurityContext.class);
                
                install(new JpaPersistModule("eventosImpa"));
                serve("/*").with(GuiceContainer.class);

                
            }
        });
        
        
        return i;
    }
}

<?xml version="1.0" encoding="UTF-8"?>
    <listener>
        <listener-class>com.sun.jersey.samples.guice.GuiceServletConfig</listener-class>
    </listener>
    
    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    
          
</web-app>


but i have another problem.

JPA + Guice + EntityManager Injection

I go posting in another topic.

Thanks for the help.
Reply all
Reply to author
Forward
0 new messages