Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java EE CDI interceptor not working inside JAX-RS resource class

I wanted to use a profiling interceptor inside a jax-rs resource class. The interceptor works otherwise, but it causes problems inside a jax-rs resource class. I have put the demo code on github.

Here is a description of the problem.

First, here is a list of the main code.

Profiled

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Profiled {
}

Profiler

@Interceptor
@Profiled
public class Profiler {
    @Inject
    Logger logger;

    @AroundInvoke
    private Object profile( InvocationContext context ) throws Exception {
        long startTime = System.currentTimeMillis();
        try {
            return context.proceed();
        } finally {
            long time = System.currentTimeMillis() - startTime;
            logger.info( context.getMethod() + " took " + time + " milliseconds" );
        }
    }
}

UtilsProducer

public class UtilsProducer {
    @Produces
    private Logger createLogger( InjectionPoint point ) {
        return Logger.getLogger( point.getMember().getDeclaringClass().getName() );
    }

    @Produces
    private Client createClient() {
        return ClientBuilder.newClient();
    }
}

Foobar

public class Foobar {
    public static final int SLEEP_TIME = 1000; // in milliseconds
    @Inject
    Logger logger;

    public String hello() {
        return "hello";
    }

    @Profiled
    public long profiledCall() throws Exception {
        long startTime = System.currentTimeMillis();
        Thread.sleep( SLEEP_TIME );
        return System.currentTimeMillis() - startTime;
    }
}

RestFoobar

@Path("/")
public class RestFoobar {
    public static final int SLEEP_TIME = 1000;
    @Inject
    private Logger logger;

    @Inject
    private Foobar foobar;

    @Context
    private UriInfo context;

    @Path("hello")
    @GET
    public String hello() {
        logger.info("Request from " + context.getRequestUri() );
        return "hello";
    }

    @Path("profile")
    @GET
    @Profiled
    public long profile() throws Exception {
        logger.info("Request from " + context.getRequestUri() );
        long startTime = System.currentTimeMillis();
        Thread.sleep( SLEEP_TIME );
        return System.currentTimeMillis() - startTime ;
    }
}

FoobarTest

public class FoobarTest extends ArquillianWarBase {
    @Inject
    Foobar foobar;

    @Test
    public void shouldGetHello() {
        assertEquals( "hello", foobar.hello() );
    }

    @Test
    public void shouldHaveSlept() throws Exception {
        assertTrue( foobar.profiledCall() >= Foobar.SLEEP_TIME );
    }
}

RestFoobarTest

public class RestFoobarTest extends ArquillianWarBase {
    @Inject
    Client client;

    static final String BASE_URL = "http://localhost:1119/demo/";

    @Test
    public void getHello() {
        String url = BASE_URL + "hello";
        Response response = client.target( url ).request(MediaType.TEXT_PLAIN_TYPE ).get();
        String text = response.readEntity( String.class );
        assertEquals( "hello", text );
    }

    @Test
    public void getProfile() {
        String url = BASE_URL + "profile";
        Response response = client.target( url ).request(MediaType.TEXT_PLAIN_TYPE ).get();
        long time = response.readEntity( Long.class );
        assertTrue( time >= RestFoobar.SLEEP_TIME );
    }
}

I use gradle wrapper to build the code. When I run ./gradlew test, which runs both FoobarTest and RestFoobarTest, I got this output:

demo.FoobarTest STANDARD_OUT
    Found populator: org.glassfish.kernel.embedded.EmbeddedDomainXml

demo.FoobarTest STANDARD_ERROR
    Apr 17, 2014 5:54:44 PM org.glassfish.security.services.impl.authorization.AuthorizationServiceImpl initialize
    INFO: Authorization Service has successfully initialized.
    Apr 17, 2014 5:54:44 PM org.hibernate.validator.internal.util.Version <clinit>
    INFO: HV000001: Hibernate Validator 5.0.0.Final
    Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.services.impl.GrizzlyProxy start
    INFO: Grizzly Framework 2.3.1 started in: 13ms - bound to [/0.0.0.0:1,119]
    Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.services.impl.GrizzlyService createNetworkProxy
    INFO: Network listener https-listener on port 0 disabled per domain.xml
    Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
    INFO: Admin Console Adapter: context root: /admin
    Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
    INFO: Admin Console Adapter: context root: /admin
    Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
    INFO: Admin Console Adapter: context root: /admin
    Apr 17, 2014 5:54:45 PM com.sun.enterprise.v3.server.AppServerStartup postStartupJob
    INFO: Undefined Product Name - define product and version info in config/branding  0.0.0  (0) startup time : Embedded (885ms), startup services(662ms), total(1,547ms)
    Apr 17, 2014 5:54:45 PM org.glassfish.jersey.server.ApplicationHandler initialize
    INFO: Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...
    Apr 17, 2014 5:54:45 PM org.glassfish.admin.mbeanserver.JMXStartupService$JMXConnectorsStarterThread run
    INFO: JMXStartupService has disabled JMXConnector system
    Apr 17, 2014 5:54:45 PM com.sun.enterprise.connectors.jms.util.JmsRaUtil getInstalledMqVersion
    WARNING: RAR7000 : Check for a new version of MQ installation failed : /var/folders/cj/b2rlrrg56ts96zdyc69l59fh002jb1/T/gfembed906146914977552454tmp/lib/install/applications/jmsra/../imqjmsra.rar (No such file or directory):/var/folders/cj/b2rlrrg56ts96zdyc69l59fh002jb1/T/gfembed906146914977552454tmp/lib/install/applications/jmsra/imqjmsra.rar

demo.FoobarTest STANDARD_OUT
    demo.war:
    /WEB-INF/
    /WEB-INF/beans.xml
    /WEB-INF/glassfish-web.xml
    /WEB-INF/web.xml
    /WEB-INF/classes/
    /WEB-INF/classes/demo/
    /WEB-INF/classes/demo/UtilsProducer.class
    /WEB-INF/classes/demo/RestFoobar.class
    /WEB-INF/classes/demo/Profiled.class
    /WEB-INF/classes/demo/Profiler.class
    /WEB-INF/classes/demo/Foobar.class

demo.FoobarTest STANDARD_ERROR
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.SecurityLifecycle <init>
    INFO: security.secmgroff
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.SecurityLifecycle onInitialization
    INFO: sec.service.startup.enter
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.PolicyLoader loadPolicy
    INFO: policy.loading
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.auth.realm.Realm doInstantiate
    INFO: realm.loaded.successfully
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.auth.realm.Realm doInstantiate
    INFO: realm.loaded.successfully
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.auth.realm.Realm doInstantiate
    INFO: realm.loaded.successfully
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.security.SecurityLifecycle onInitialization
    INFO: sec.service.startup.exit
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.web.WebContainer createHttpListener
    INFO: Created HTTP listener http-listener on host/port 0.0.0.0:1119
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.web.VirtualServer addProbes
    SEVERE: Error adding HttpProbes. NetworkListener https-listeners GrizzlyProxy is NULL
    Apr 17, 2014 5:54:46 PM com.sun.enterprise.web.WebContainer createHosts
    INFO: Created virtual server server
    Apr 17, 2014 5:54:47 PM org.apache.catalina.realm.JAASRealm setContainer
    INFO: Setting JAAS app name glassfish-web
    Apr 17, 2014 5:54:47 PM com.sun.enterprise.web.WebContainer loadSystemDefaultWebModules
    INFO: Virtual server server loaded default web module 
    Apr 17, 2014 5:54:47 PM org.jboss.weld.bootstrap.WeldBootstrap <clinit>
    INFO: WELD-000900 SNAPSHOT
    Apr 17, 2014 5:54:48 PM org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer addServletWithDefaultConfiguration
    INFO: Registering the Jersey servlet application, named javax.ws.rs.core.Application, with the following root resource and provider classes: [class demo.RestFoobar]
    Apr 17, 2014 5:54:48 PM org.glassfish.jersey.server.ApplicationHandler initialize
    INFO: Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...
    Apr 17, 2014 5:54:48 PM com.sun.enterprise.web.WebApplication start
    INFO: Loading application [demo] at [/demo]
    Apr 17, 2014 5:54:48 PM org.glassfish.deployment.admin.DeployCommand execute
    INFO: demo was successfully deployed in 2,328 milliseconds.

demo.FoobarTest > shouldGetHello PASSED

demo.FoobarTest > shouldHaveSlept STANDARD_ERROR
    Apr 17, 2014 5:54:49 PM demo.Profiler profile
    INFO: public long demo.Foobar.profiledCall() throws java.lang.Exception took 1000 milliseconds

demo.FoobarTest > shouldHaveSlept PASSED

demo.FoobarTest STANDARD_OUT
    PlainTextActionReporterSUCCESSNo monitoring data to report.

demo.RestFoobarTest STANDARD_ERROR
    Apr 17, 2014 5:54:50 PM org.glassfish.jersey.servlet.init.JerseyServletContainerInitializer addServletWithDefaultConfiguration
    INFO: Registering the Jersey servlet application, named javax.ws.rs.core.Application, with the following root resource and provider classes: [class demo.RestFoobar]
    Apr 17, 2014 5:54:50 PM org.glassfish.jersey.server.ApplicationHandler initialize
    INFO: Initiating Jersey application, version Jersey: 2.0 2013-05-03 14:50:15...
    Apr 17, 2014 5:54:50 PM com.sun.enterprise.web.WebApplication start
    INFO: Loading application [demo] at [/demo]
    Apr 17, 2014 5:54:50 PM org.glassfish.deployment.admin.DeployCommand execute
    INFO: demo was successfully deployed in 666 milliseconds.

demo.RestFoobarTest > getProfile STANDARD_ERROR
    Apr 17, 2014 5:54:51 PM org.apache.catalina.core.StandardWrapperValve log
    WARNING: StandardWrapperValve[javax.ws.rs.core.Application]: Servlet.service() for servlet javax.ws.rs.core.Application threw exception
    org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=Logger,parent=RestFoobar,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,998142827)
        at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
        at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:771)
        at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:790)
        at org.glassfish.jersey.gf.cdi.CdiComponentProvider$1.inject(CdiComponentProvider.java:316)
        at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:158)
        at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
        at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:716)
        at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:738)
        at org.glassfish.jersey.gf.cdi.CdiComponentProvider$CdiFactory$1.getInstance(CdiComponentProvider.java:174)
        at org.glassfish.jersey.gf.cdi.CdiComponentProvider$CdiFactory.provide(CdiComponentProvider.java:143)
        at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:96)
        at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:448)
        at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:69)
        at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2204)
        at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:579)
        at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:566)
        at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
        at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
        at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:105)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:118)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
        at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:102)
        at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:62)
        at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
        at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:215)
        at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
        at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
        at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
        at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
        at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
        at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
        at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
        at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
        at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
        at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
        at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
        at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
        at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
        at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
        at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
        at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
        at java.lang.Thread.run(Thread.java:745)


demo.RestFoobarTest > getProfile FAILED
    org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException at RestFoobarTest.java:32

demo.RestFoobarTest > getHello STANDARD_ERROR
    Apr 17, 2014 5:54:51 PM org.apache.catalina.core.StandardWrapperValve log
    WARNING: StandardWrapperValve[javax.ws.rs.core.Application]: Servlet.service() for servlet javax.ws.rs.core.Application threw exception
    org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=Logger,parent=RestFoobar,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,436148362)
        at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
        at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:771)
        at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:790)
        at org.glassfish.jersey.gf.cdi.CdiComponentProvider$1.inject(CdiComponentProvider.java:316)
        at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:158)
        at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
        at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:716)
        at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:738)
        at org.glassfish.jersey.gf.cdi.CdiComponentProvider$CdiFactory$1.getInstance(CdiComponentProvider.java:174)
        at org.glassfish.jersey.gf.cdi.CdiComponentProvider$CdiFactory.provide(CdiComponentProvider.java:143)
        at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:96)
        at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:448)
        at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:69)
        at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2204)
        at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:579)
        at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:566)
        at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
        at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
        at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:105)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:118)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
        at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:121)
        at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:102)
        at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:62)
        at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
        at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:215)
        at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
        at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
        at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
        at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
        at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
        at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
        at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:198)
        at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:946)
        at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:323)
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
        at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
        at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
        at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
        at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
        at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
        at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
        at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
        at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
        at java.lang.Thread.run(Thread.java:745)


demo.RestFoobarTest > getHello FAILED
    org.junit.ComparisonFailure at RestFoobarTest.java:25

demo.RestFoobarTest STANDARD_OUT
    PlainTextActionReporterSUCCESSNo monitoring data to report.

4 tests completed, 2 failed

As shown above, the @Profiled annotation works in Foobar, but causes problems in RestFoobar. If remove the @Profiled above RestFoobar.profile(), the test will pass, except there is no longer the profiling output.

BTW, I use Arquillian and embedded Glassfish to run the tests. Here is a full list of the dependencies:

dependencies {
    providedCompile 'javax:javaee-api:7.0'
    testCompile 'junit:junit:4.11'
    testCompile 'org.jboss.arquillian:arquillian-bom:1.1.4.Final'
    testCompile 'org.jboss.arquillian.junit:arquillian-junit-container:1.1.4.Final'
    testRuntime 'org.glassfish.main.extras:glassfish-embedded-all:4.0'
    testRuntime 'org.jboss.arquillian.container:arquillian-glassfish-embedded-3.1:1.0.0.CR4'
}

The Arquillian war wrapper is as follows

ArquillianWarBase

public abstract class ArquillianWarBase {
    private static WebArchive war;
    @Deployment
    public static WebArchive createDeployment() {
        if( war == null ) {
            war = ShrinkWrap.create( WebArchive.class, "demo.war" )
                    .addPackages( true, Filters.exclude( ".*Test.*" ),
                            "demo" )
                    .addAsWebInfResource( "beans-test.xml", "beans.xml" )
                    .addAsWebInfResource( "glassfish-web-test.xml", "glassfish-web.xml" )
                    .addAsWebInfResource( "web-test.xml", "web.xml" );
            System.out.println( war.toString( true ) );
        }
        return war;
    }
}

So, it looks like the interceptor annotation @Profiled doesn't work inside a jax-rs resource class (i.e., RestFoobar). But why? Is there a simple way to make it work?

Thank you very much.

like image 975
JBT Avatar asked Apr 18 '14 01:04

JBT


1 Answers

So, it looks like the interceptor annotation @Profiled doesn't work inside a jax-rs resource class (i.e., RestFoobar). But why?

Because your class (i.e RestFooBar) is not a CDI-managed-bean. Interceptors only work with this sort of beans.

Is there a simple way to make it work?

Yes, annotate your class (i.e RestFooBar) with @Stateless from the javax.ejb package, this will also give you the opportunity to inject other services with @EJB.

There are some other options:

  1. Separate your service and REST classes in such a way that only the service classes need to be intercepted.
  2. There seems to be a module named jersey-gf-cdi which implemtens a bridge between Glassfish CDI and Jersey, but I didn't get that to work and I'm not sure if this is a solution for the problem.

See also:

  • CDI interceptor injected into a jersey RS service(resource) not working?
  • Package org.glassfish.jersey.gf.cdi.spi
  • Package org.glassfish.jersey.gf.cdi.hk2ban
like image 148
unwichtich Avatar answered Nov 17 '22 15:11

unwichtich