Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jersey - test rest endpoint service with ejb injection

Tags:

jersey

grizzly

I got a jax-rs resource

@Path("rest/v1/serviceemail")
public class PreviewResource implements Preview
{  
  @EJB
  private Mapper mapper;

I'm creating an IT test with jersey-test-framework-core and jersey-test-framework-grizzly2.

When I launch the test the ejb is not injected in the service and so I receive a NPE.

like image 495
Massimo Ugues Avatar asked Dec 05 '25 09:12

Massimo Ugues


1 Answers

I found a solution by implementing a custom InjectableProvider. The following code is taken from an Oracle article:

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.ext.Provider;

import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;

@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {

    public Scope getScope() {
        return Scope.Singleton;
    }

    public Injectable getInjectable(ComponentContext cc, EJB ejb, Type t) {
        if (!(t instanceof Class)) return null;

        try {
            Class c = (Class)t;        
            Context ic = new InitialContext();

            final Object o = ic.lookup(c.getName());

            return new Injectable<Object>() {
                public Object getValue(HttpContext c) {
                    return o;
                }                    
            };            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

I had to slightly adapt it to fit my environment. Also note that the provider has to be in the same package as your service class, otherwise it won't be picked up (it does not say that in the article).

like image 104
Adrian B. Avatar answered Dec 10 '25 08:12

Adrian B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!