EzDevInfo.com

weld

Template antimatter for Node.js (Browsers too!)

WELD + GF4 + SessionScoped: Sometimes wrong bean?


TL;DR We get @SessionScoped bean instances injected that have the content of another session


lately we have been experiencing serious problems with two of our customer systems. Our customers are running two independent instances of the same JSF 2.2 application on two machines having a Glassfish 4.0 Server with WELD 2.0.5 (hail to the memory leak!).

Some users have been reporting problems that after e.g. submitting a form the response shows another user name than the one who initially logged in. Since we were unable to reproduce this behaviour in our development and testing environments, we started to grab log data from the productive systems.

What were we logging?

On our first attempt we started logging which user conducted which action from which client at some time. After crawling through the logs we found sequences like this:

Time Client   User   Action
.............................
t=0  ClientA  UserA  Login
t=1  ClientA  UserA  Logoff
t=2  ClientB  UserB  Login
t=3  ClientB  UserB  ActionA
t=4  ClientB *UserA* ActionB
t=5  ClientB  UserB  Logoff

Whereas the session of the replacing user (here User A) was not always over before the replacement happened (sometimes resulting in one user logging out another one...). So where is the currently logged in user stored? We store it as a property in a @SessionScoped bean being injected into @RequestScoped beans wherever we need this information. This led us to the theory that the @SessionScoped beans sometimes get mixed up.

@Named
@javax.enterprise.context.SessionScoped
public class SessionStateBean {
  private User user;

  public void setUser(...) { }
  public User getUser() { }
}

Therefore on our second attempt we extended the log data by the following features:

  • We started storing the user name inside the HTTP session and compared it on every request with the value coming from the @SessionScoped bean.
  • Every instance of the @SessionScoped bean received its own UUID and logged when the bean was constructed & destroyed as well as when the user property was changed. We know that it is possible that @SessionScoped beans can have multiple proxies, be passivated, etc., but we gave it a try.

Regarding the first log feature we started seeing sequences showing actual differences between the user name coming from the session scoped bean and the value being stored inside the HTTP session:

Time Session Client   User   Action
.............................
t=0  SessA   ClientA  UserA  Login
t=1  SessA   ClientA  UserA  Logoff
t=2  SessB   ClientB  UserB  Login
t=3  SessB   ClientB  UserB  ActionA
t=4 |SessB   ClientB *UserA* ActionB
    +->  SessionScope != Session
t=5  SessB   ClientB  UserB  Logoff

Taking all requests being processed into account, the ones where the session scope value does not match the session value are approx. 1 out of 60 to 150 requests.

More interesting is what happened with the @SessionScoped bean instances. Since we are tracking @PostConstruct & @PreDestroy events, sequences like the following were observed:

Time Session Bean   Action     UserValue
................................
t=0  SessA   BeanA  Construct  (null)
t=1  SessA   BeanA  SetUser    UserA  // login
t=2  SessA   BeanA  SetUser    (null) // logout
t=3  SessA   BeanA  Destroy    (null)
// so far so good, now it gets interesting
t=4  SessB   BeanA  SetUser    UserB  // login
t=5  SessB   BeanA  SetUser    (null) // logout
t=6  SessC   BeanA  SetUser    UserC  // login
t=7  SessC   BeanA  SetUser    (null) // logout
t=8  SessD   BeanA  SetUser    UserD  // login
t=9  SessD   BeanA  SetUser    (null) // logout

We did not expect that sometimes after the @PreDestroy event bean instances get reused without going through the life cycle of construction and destruction. Taking all logged bean instances into account this happens with approx. 1 bean out of 500 (System A) to 4000 (System B). This is not always happening when the session scope value and the HTTP session value differ, but always when we see such a bean instance being reused it is when the values are different.

Initially we assumed that these events are more likely to occur after the server has been under load for a while, but this turned out not to be true. Sometimes they occur some hours after the last server restart and sometimes after two weeks.

Searching the internet for these issues we were not able to find actual traces on other people experiencing the same problems or known bugs in either WELD (best trace, but wrong version), Glassfish, Grizzly (best trace, but too old), JSF, etc.

So our question is: Is there anyone who ever has experienced a similar problem? Is this odd behaviour somehow a known bug we just tried to identify in the wrong spot? Is there even an actual fix? Any hint is gladly appreciated!

Update: We found out that if we restart the whole machine the described behaviour is gone for around two weeks. If we just restart Glassfish it's a matter of hours until the odd behaviour is back. Seriously, what can affect Glassfish or the JVM that badly such that only a machine reboot changes the behaviour?


Currently we are bypassing the problem by putting all data we kept in the @SessionScoped bean directly into the HTTP session and so far it seems to work fine. But that approach is so clumsy...


Source: (StackOverflow)

How to hunt down obscure HA clustering bug in Wildfly 8.2.0.Final

The setup

I have a Wildfly 8.2.0.Final application server running a cluster in domain mode using the full-ha profile. The cluster consists of two instances of wildfly, master and slave, each running on its own virtual machine.

The application

My project is deployed as a war-file on the application server. For test purposes my loadbalancer distributes the requests using round-robin.

Anonymous users can use the service provided by this project using a button, which will call in two steps first register then login. Login will use the session that is created during the register phase providing the credentials created during the register call.

The implementation

The login endpoint is a request scoped CDI bean, which among other members has a member which holds user information. The user information is a SessionScopped EJB Bean which is created during session instantiation and which is injected into the login endpoints CDI bean. The user information is supposed to get distributed among cluster members.

Observed behavior

Now the funny part:

  • Using Firefox:
    1. /rest/register -> 200 OK
    2. /rest/login -> 200 OK
  • Using Firefox in private mode:
    1. /rest/register -> 200 OK
    2. /rest/login -> 200 OK
  • Using Chrome:
    1. /rest/register -> 200 OK
    2. /rest/login -> 200 OK
  • Using Chrome in private mode:
    1. /rest/register -> 200 OK
    2. /rest/login -> 200 OK
  • Using Internet Explorer 11:
    1. /rest/register -> 200 OK
    2. /rest/login -> 200 OK
  • Using Internet Explorer 11 in private mode:
    1. /rest/register -> 200 OK
    2. /rest/login -> 500 Internal Server error

The logs

This is the stack trace of the 500:

    2015-05-07 10:05:31,734 ERROR [io.undertow.request] (default task-11) UT005023: Exception handling request to /testtest/rest/login: org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
        at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:76) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:212) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:149) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:372) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51) [resteasy-jaxrs-3.0.10.Final.jar:]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
        at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:61) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:56) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:45) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:63) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:70) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:261) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:247) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:76) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:166) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.server.Connectors.executeRootHandler(Connectors.java:197) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:759) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_65]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_65]
        at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_65]
Caused by: java.lang.NullPointerException
        at org.jboss.weld.context.beanstore.http.AbstractSessionBeanStore.getLockStore(AbstractSessionBeanStore.java:113) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
        at org.jboss.weld.context.beanstore.AttributeBeanStore.lock(AttributeBeanStore.java:210) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
        at org.jboss.weld.context.AbstractContext.get(AbstractContext.java:90) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
        at org.jboss.weld.context.PassivatingContextWrapper$AbstractPassivatingContextWrapper.get(PassivatingContextWrapper.java:76) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
        at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:98) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
        at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:78) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
        at ru.exampl.testtest.lobby.UserController$Proxy$_$$_WeldClientProxy.toString(Unknown Source) [classes:]
        at org.apache.log4j.spi.LoggingEvent.<init>(LoggingEvent.java:106) [log4j-jboss-logmanager-1.1.0.Final.jar:1.1.0.Final]
        at org.apache.log4j.Category.forcedLog(Category.java:119) [log4j-jboss-logmanager-1.1.0.Final.jar:1.1.0.Final]
        at org.apache.log4j.Category.debug(Category.java:80) [log4j-jboss-logmanager-1.1.0.Final.jar:1.1.0.Final]
        at ru.exampl.testtest.rest.LobbyEndpoint.login(LobbyEndpoint.java:100) [classes:]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_65]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_65]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_65]
        at java.lang.reflect.Method.invoke(Method.java:606) [rt.jar:1.7.0_65]
        at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:137) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:296) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:250) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:237) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:356) [resteasy-jaxrs-3.0.10.Final.jar:]

The code

And this is the relevant code which causes the error (or not in those cases where it just works):

package ru.exampl.testtest.rest;

[... lots of imports ...]

/**
 * The implementation of some general webservice endpoints.
 */
@RequestScoped
@Path("rest")
public class LobbyEndpoint {

    private transient static final Logger log4j = Logger.getLogger(LobbyEndpoint.class);

    @Inject
    private UserController userController;

    [... more injections ...]

    @POST
    @Path("/login")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public LoginResponse login(LoginRequest request) {
        log4j.log(userController);
        [... lots of code to handle login ...]
    }
}

Now the funny thing is, that userController is obviously not null, since log4j knows how to handle and log null objects. The object obviously has a reference but Weld can't access it through the proxy. This in itself would be only half as funny without the list of browsers where this very same rest endpoint just does its job and only one specific browser in one specific browser mode causing the webapp to crash.

Additional information

To be honest, I have NO clue how a browser through its requests could provoke such a behavior. But to make things even more funny, I recorded the actual requests with tshark and then modified Firefox to send the very same request the Internet Explorer 11 sends. And now hold your breath: all things being equal Firefox doesn't crash the webapp while Internet Explorer 11 in private mode does 100% of the time.

I recorded both requests to demonstrate (you can view them in wireshark):

The actual question

Now my question: where do I even start to debug this? How can a web browser delivering its requests through a proxy even have the slightest influence on the outcome of my session synchronization in my cluster and thus influencing the request processing on my application server, if the entire request is identical except for the order of the headers? Timing is not involved. Introducing random waits in the requests didn't change anything.


Source: (StackOverflow)

Advertisements

How to avoid BusyConversationException in jsf

I'm getting BusyConversationException while navigating through pages in my jsf project. This mostly happens if the user tries to navigate to another page during an ajax call. This also happens when the user clicks on a link right after clicking on another link without waiting for loading of the page.

For example if the user clicks on more than one link which are generated through a code similar to below one we definitely get this exception. Another example is, lets say the user enter a query on a text field, and our application make an ajax call for searching this query. During that query if the user click on some button to navigate to another page BusyConversationException occurs too.

<h:commandLink value="#{theProfile.profileName}"
               title="#{theProfile.profileName}"
               action="#{profileBean.aProfileSelected}">
               <f:setPropertyActionListener target="#{currentProfileWebBean.theProfile}" value="#{theProfile}"/>
</h:commandLink>

I can catch this type of exception in an ExceptionHandler class which extends ExceptionHandlerWrapper class but I can't save my current state and the best I can do for this case is to redirect to main page when this exception occurs.

Is there any solution for avoiding this? Thanks in advance for answers and comments.


Source: (StackOverflow)

WELD-001519 An InjectionTarget implementation is created for an abstract class 'xxx'. It will not be possible to produce instances of this type

I'm running an application in the following environment.

  • GlassFish Server 4.0
  • Mojarra 2.2.4
  • PrimeFaces 4.0 final
  • PrimeFaces Extension 1.1.0
  • OmniFaces 1.6.3

After adding OmniFaces, the following warnings appear on the server terminal.

WARNING:   WELD-001519 An InjectionTarget implementation is created for an abstract class org.omnifaces.eventlistener.DefaultServletContextListener. It will not be possible to produce instances of this type!    
WARNING:   WELD-001519 An InjectionTarget implementation is created for an abstract class org.omnifaces.filter.HttpFilter. It will not be possible to produce instances of this type!

//WARNING:   Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled
//WARNING:   Class 'javax.ejb.PrePassivate' not found, interception based on it is not enabled
INFO:   Initializing Mojarra 2.2.4 ( 20131003-1354 https://svn.java.net/svn/mojarra~svn/tags/2.2.4@12574) for context '/Project-war'

WARNING:   WELD-001529 An InjectionTarget implementation is created for a class org.omnifaces.application.OmniApplicationFactory which does not have any appropriate constructor.
WARNING:   WELD-001529 An InjectionTarget implementation is created for a class org.primefaces.context.PrimeFacesContextFactory which does not have any appropriate constructor.
WARNING:   WELD-001529 An InjectionTarget implementation is created for a class org.omnifaces.context.OmniPartialViewContextFactory which does not have any appropriate constructor.
WARNING:   WELD-001529 An InjectionTarget implementation is created for a class org.primefaces.context.PrimePartialViewContextFactory which does not have any appropriate constructor.

INFO:   Running on PrimeFaces 4.0
INFO:   Running on PrimeFaces Extensions null
INFO:   Using OmniFaces version null

INFO:   Loading application [Project#Project-war.war] at [Project-war]
INFO:   Project was successfully deployed in 22,734 milliseconds.

Is there any problem with OmniFaces in the given environment?


Source: (StackOverflow)

How to bootstrap weld-se in a JUnit test

I have a maven project for unit tests and would like to use CDI. I've put the weld-se dependency in pom.xml like this :

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
</dependency>
<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se</artifactId>
    <version>1.1.8.Final</version>
</dependency>
<dependency>
    <groupId>javax.enterprise</groupId>
    <artifactId>cdi-api</artifactId>
    <version>1.0-SP3</version>
</dependency>

I'm bootstrapping weld in a JUnit test runner :

public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {
   private final Class klass;
   private final Weld weld;
   private final WeldContainer container;

   public WeldJUnit4Runner(final Class klass) throws InitializationError {
       super(klass);
       this.klass = klass;
       this.weld = new Weld();
       this.container = weld.initialize();
   }

   @Override
   protected Object createTest() throws Exception {
       final Object test = container.instance().select(klass).get();

       return test;
   }
}

And a unit test that uses this runner. The test is injecting an application scoped bean. The problem is that weld cannot initialize because of an "Unsatisfied dependency" on the only injection point, as if my application scoped bean was totally unknown to weld. But that bean is in src/test/java/... with my test (but in another java package).

I have an empty beans.xml in src/test/resources.

I noticed weld gives warnings when starting but I don't think these are the cause of my problem :

604 [main] WARN org.jboss.weld.interceptor.util.InterceptionTypeRegistry - Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled
605 [main] WARN org.jboss.weld.interceptor.util.InterceptionTypeRegistry - Class 'javax.ejb.PrePassivate' not found, interception based on it is not enabled

Can someone help me with that ?


Source: (StackOverflow)

Is Seam3 and Weld CDI the same thing?

Maybe this seems like a foolish question but I am really confused. Is Seam 3 and Weld CDI the same things? I am reading some posts which refers to "CDI (Weld) / Seam 3", should I consider them as the same thing?


Source: (StackOverflow)

How to programmatically inject a Java CDI managed bean into a local variable in a static method

How can I programmatically inject a Java CDI 1.1+ managed bean into a local variable in a static method?


Source: (StackOverflow)

WARNING: Parameter 1 of type List> from public void org.omnifaces.cdi.eager.EagerBeansRepository.setXxx is not resolvable to a concrete type

I'm using Omnifaces 1.8.1 and Whenever I deploy my application to Glassfish I get the following warning which causes some delay in the deploy process.

Warning:   WELD-001519 An InjectionTarget implementation is created for an abstract class org.omnifaces.eventlistener.DefaultHttpSessionListener. It will not be possible to produce instances of this type!
Warning:   WELD-001519 An InjectionTarget implementation is created for an abstract class org.omnifaces.eventlistener.DefaultServletContextListener. It will not be possible to produce instances of this type!
Warning:   WELD-001519 An InjectionTarget implementation is created for an abstract class org.omnifaces.eventlistener.DefaultServletRequestListener. It will not be possible to produce instances of this type!
Warning:   WELD-001519 An InjectionTarget implementation is created for an abstract class org.omnifaces.filter.HttpFilter. It will not be possible to produce instances of this type!

Warning:   The following warnings have been detected: 

WARNING: Parameter 1 of type java.util.List<javax.enterprise.inject.spi.Bean<?>> from public void org.omnifaces.cdi.eager.EagerBeansRepository.setApplicationScopedBeans(java.util.List<javax.enterprise.inject.spi.Bean<?>>) is not resolvable to a concrete type.   
WARNING: Parameter 1 of type java.util.Map<java.lang.String, java.util.List<javax.enterprise.inject.spi.Bean<?>>> from public void org.omnifaces.cdi.eager.EagerBeansRepository.setRequestScopedBeansViewId(java.util.Map<java.lang.String, java.util.List<javax.enterprise.inject.spi.Bean<?>>>) is not resolvable to a concrete type.
WARNING: Parameter 1 of type java.util.Map<java.lang.String, java.util.List<javax.enterprise.inject.spi.Bean<?>>> from public void org.omnifaces.cdi.eager.EagerBeansRepository.setRequestScopedBeansRequestURI(java.util.Map<java.lang.String, java.util.List<javax.enterprise.inject.spi.Bean<?>>>) is not resolvable to a concrete type.
WARNING: Parameter 1 of type java.util.List<javax.enterprise.inject.spi.Bean<?>> from public void org.omnifaces.cdi.eager.EagerBeansRepository.setSessionScopedBeans(java.util.List<javax.enterprise.inject.spi.Bean<?>>) is not resolvable to a concrete type.

I have upgraded to Omnifaces 2.0 and still getting the same warning which is quite annoying in the development process where deployment is applied frequently. What is causing these warnings?

PS: Development environment:

  • Glassfish 4.1
  • Java 8
  • JSF 2.2.0 (Mojarra)
  • Primefaces 4.0
  • Netbeans 8

Source: (StackOverflow)

When is a @Dependent scoped CDI bean destroyed, if you obtain that bean via Provider.get()?

I am struggling to understand the effective lifecycle of a @Dependent scoped bean in both CDI 1.0 and CDI 1.1. My experiments so far have lead me to the following conclusions:

  • A @Dependent scoped bean is not proxied.
  • No @PreDestroy method is invoked when a @Dependent bean is destroyed.
  • Provider.get() always creates a new instance of a @Dependent bean.
  • With JBoss 6/CDI 1.0, a @Dependent bean that is created by an @ApplicationScoped bean's Provider<> field is "leaked", because it still "belongs" to the Provider.
  • I have seen no evidence (yet!) of @Dependent beans being leaked by similar Providers when using WELD 2.1.2.Final/CDI 1.1. (Although this might be because these particular @Dependent beans are created by @Produces methods...!)

I see that CDI 1.1 has added a destroy() method to Instance<>, presumably to address the memory leak in CDI 1.0. But what about Provider<> - does that still leak in CDI 1.1? (And if it does, then how are you supposed to use Provider.get()?)

Basically, I have several @ApplicationScoped beans / @Singleton EJBs that I @Inject Provider fields into, and I am trying to use Provider.get() as factories for both @Dependent and @RequestScoped "helper" beans. I definitely do not want these beans to "belong" to their Provider fields, as I need the beans to be garbage collected afterwards:

public void updateStuff() {
    Helper helper = helperProvider.get();
    // use helper...
}

For my CDI 1.0 application, I was thinking of fixing the memory leak by "faking" my Providers with code like this:

provider = new Provider<MyBean>() {
    @Override
    public MyBean get() {
        return getReferenceFor(MyBean.class);
    }
};

private <T> T getReferenceFor(Class<T> type) {
    Bean<?> bean = beanManager.resolve(beanManager.getBeans(type));
    CreationalContext<?> context = beanManager.createCreationalContext(bean);
    try {
        return (T) beanManager.getReference(bean, bean.getBeanClass(), context);
    } finally {
        // Destroy this context - which I don't want to exist anyway.
        // I only need a strong reference to a fully @Inject-ed bean!
        context.release();
    }
}

MyBean is a @Dependent scoped bean with no @PreDestroy method that only needs to be garbage collected when I've finished with it. However, I can't find a lot of information about Providers, and so can't tell if I'm arming some kind of time-bomb by doing this.

Some of my @Dependent scoped beans (which I still obtain via Provider.get(), btw) are created by @Produces methods. Are they still in danger of being leaked?

Can anyone advise me, please?
Thanks,
Chris


Source: (StackOverflow)

WELD-000044 Unable to obtain instance from org.jboss.weld.bean-se-module-ProducerField

I am trying to inject an entity manager in a DAO class and test it, using weld container, but i keep getting the following exception:

org.jboss.weld.exceptions.NullInstanceException: WELD-000044 Unable to obtain instance from org.jboss.weld.bean-se-module-ProducerField-com.playground.cdi_tutorial.beans.Resources.em at org.jboss.weld.bean.builtin.CallableMethodHandler.invoke(CallableMethodHandler.java:60) at org.jboss.weld.util.CleanableMethodHandler.invoke(CleanableMethodHandler.java:43) at javax.persistence.EntityManager_$$_javassist_2.createQuery(EntityManager_$$_javassist_2.java) at com.playground.cdi_tutorial.model.EventDAO.getAllEvents(EventDAO.java:22) at com.playground.cdi_tutorial.beans.ValidationService.validateEvenNumbers(ValidationService.java:23) at com.playground.cdi_tutorial.beans.MyFactory.sayHi(MyFactory.java:15) at com.playground.cdi_tutorial.beans.MyFactoryTest.should_say_bye(MyFactoryTest.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

I try to inject the entity manager as follows:

 @Inject
 @EmProducer
 EntityManager em;

where EmProducer looks like this:

@Qualifier
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
public @interface EmProducer {

    public static final String UNIT_NAME = "cdi-tutorial";

}

And the producer class looks like this:

public class Resources {

 @Produces
 @EmProducer
 @PersistenceContext(unitName = EmProducer.UNIT_NAME)
 private EntityManager em;
       ...
    }

In my test, when this line of code is hit Query q = em.createQuery("from Employee"); I get the exception above. The entity manager, em, is not null though.

PS: I use WeldJUnit4Runner (http://www.hostettler.net/blog/2012/04/02/how-to-test-a-jsf-named-bean/) to run my tests.

I would really appreciate your help.

Thanks!


Source: (StackOverflow)

Is interceptor really disabled by default?

I ran into this confusion today. Quote from Weld's documentation (right under Section 9.3),

By default, all interceptors are disabled. We need to enable our interceptor. We can do it using beans.xml descriptor of a bean archive. However, this activation only applies to the beans in that archive.

However, in the project that I am currently working on, I have an interceptor for profiling a method. My META-INF/beans.xml is basically empty:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">
</beans>

Yet I still get expected logs from that profiling interceptor. So, as the title goes, is interceptor really disabled by default?

BTW, I use weld-se for CDI functionality in the project, since CDI is the only thing I need for the project from the Java EE stack.

update

After messing around interceptors today, I find that if the old @Interceptors is used to indicate the interception implementation class, you don't need to specify anything in the beans.xml. However, if you use interceptor binding, i.e., use the @Interceptor annotation to indicate an interceptor class, you must enable interception by adding the interceptor class to the beans.xml. According to my experience, this is still true for CDI 1.1, as indicated by the version in the beans.xml above. BTW, I use org.jboss.weld.se:weld-se:2.0.4.Final for CDI implementation in this case, which I believe implements CDI 1.1.


Source: (StackOverflow)

Checking if class is proxified with CDI 1.2

In CDI 1.2 there is a way to check if a class instance is proxified? I need this because I need to get the name of original class, not the proxy name.

@Inject Bean bean;

public void sysout() {
    // will print something like com.Bean$$Weld9239823
    System.out.println(bean.getClass()); 

    // I don't know how to check if the bean instance if a proxy or real class instance
}

Using Weld classes I can do this job:

public void sysout() {
    // will print true because this is a proxy
    System.out.println(ProxyObject.class.isAssignableFrom(bean)); 

    // will print com.Bean
    System.out.println(((TargetInstanceProxy) bean).getTargetInstance());
}

In CDI 1.1 there is no method to do this. I search inside CDI 1.2 docs if a method was added about this, but I don't found anything.

So... I miss something and CDI 1.2 there is a method to get original class name and instance? Or if not, there is a plain to add this feature in near feature?


Source: (StackOverflow)

Inject @SessionScoped CDI Bean to @Stateless EJB

I'd like to inject a sessionscoped CDI bean into a stateless EJB. At access time of the EJB the correct instance of the sessionscoped cdi bean (i.e. the one in the sessionscope of the caller) should be used. I know that I can solve this with a stateful EJB, however I'd really like to know if this is solvable with CDI also. As the EJB and the Servlet run in the same war I'd assume they share the same thread and the container should be able to figure out the correct sessionscoped bean in the EJB?

For example:

EJB:

@Stateless
@LocalBean
public class StatelessSessionBean {

    @Inject    
    Instance<SessionData> sessionData;    

    public String testMethod() {
        SessionData bean = sessionData.get();
        String result = "Retrieved bean " + bean + " with UUID "+ bean.uuid + ". Created on: " + new SimpleDateFormat("dd.MM.yyyy HH:mm").format(bean.creationDate);
        return result;
    }
}

CDI Bean:

@SessionScoped
public class SessionData implements Serializable {      

    String uuid;
    Date creationDate;

    public SessionData() {
        uuid = UUID.randomUUID().toString();
        creationDate = new Date();
    }    
}

When I now access the stateless EJB e.g. from a servlet, I'd like testMethod to use the CDI bean which is associated with the caller's HTTPSession. So if two clients from different browser/http sessions access the Servlet they should both get different result strings.

Do I need a CDI Provider instead of the Instance and if yes how do I produce the correct instance of the bean for the given session? I thought about maybe getting the BeanManager and searching for instances of the SessionData but I don't know how I'd get the correct one.

Any help is greatly appreciated, thanks !


Source: (StackOverflow)

Mixing Powermock with Weld?

We have a project that uses

  • Weld-SE for dependency injection
  • static native methods to call a native library

When writing unit tests, in order to test managed beans that interact with the native library, we'd like to mock the class on which they're defined. However, PowerMock (specifically, the annotation @PrepareForTest) seems to mess with Weld's initialization. For example, if I have the following:

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticNativeAPI.class)
public class Test {
  @Before
  public void setup() {
    WeldContainer wc = new Weld().initialize();
  }
}

then Weld will fail to initialize with the following error:

org.jboss.weld.exceptions.DeploymentException: WELD-001423 Cannot enable the same alternative bean class [com.mycompany.AltBean in jar:file:/C:/Users/Me/.m2/repository/com/mycompany/project/version-SNAPSHOT/project-version-SNAPSHOT-tests.jar!/META-INF/beans.xml@8, com.mycompany.AltBean in jar:file:/C:/Users/Me/.m2/repository/com/mycompany/project/version-SNAPSHOT/project-version-SNAPSHOT-tests.jar!/META-INF/beans.xml@8] in beans.xml

at org.jboss.weld.manager.Enabled.createMetadataMap(Enabled.java:123)
at org.jboss.weld.manager.Enabled.<init>(Enabled.java:94)
at org.jboss.weld.manager.Enabled.of(Enabled.java:79)
at org.jboss.weld.bootstrap.BeanDeployment.<init>(BeanDeployment.java:114)
at org.jboss.weld.bootstrap.WeldBootstrap$DeploymentVisitor.visit(WeldBootstrap.java:184)
at org.jboss.weld.bootstrap.WeldBootstrap$DeploymentVisitor.visit(WeldBootstrap.java:153)
at org.jboss.weld.bootstrap.WeldBootstrap.startContainer(WeldBootstrap.java:284)
at org.jboss.weld.bootstrap.api.helpers.ForwardingBootstrap.startContainer(ForwardingBootstrap.java:42)
at org.jboss.weld.environment.se.Weld.initialize(Weld.java:129)
at com.mycompany.Test.setup(Test.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.ClassRoadie.runBefores(ClassRoadie.java:56)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:43)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:234)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:133)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:114)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:188)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:166)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:86)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:101)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:74)

In other words, it appears to be parsing beans.xml twice. Does anybody know how to get these two libraries to play nicely together?


Source: (StackOverflow)

BeanManager on Apache Tomcat 7.0.47 cannot create resource instance

running on: Apache Tomcat 7.0.47 OmniFaces 1.6.3 JSF Mojarra 2.1.26 CDI Weld 2.1.0.Final

Threre is an RuntimeException on Apache Tomcat 7.0.47 by accessing JNDI "java:comp/BeanManager". The CDI BenManager is bound to "java:comp/env/BeanManager" vut not reached in your BeanManager Class.

  /**
         * Perform automatic initialization whereby the bean manager is looked up from the JNDI. If the bean manager is
         * found, then invoke {@link #init(Object)} with the found bean manager.
         */
        private void init() {
                if (!initialized.getAndSet(true)) {
                        try {
                                Class.forName("javax.enterprise.inject.spi.BeanManager"); // Is CDI present?
                                Class.forName("javax.naming.InitialContext"); // Is JNDI present? (not on Google App Engine)
                        }
                        catch (Exception e) {
                                return; // CDI or JNDI not supported on this environment.
                        }
                    try {
                            Object beanManager = JNDI.lookup("java:comp/BeanManager"); // CDI spec.

                            if (beanManager == null) {
                                    beanManager = JNDI.lookup("java:comp/env/BeanManager"); // Tomcat.
                            }

                            if (beanManager == null) {
                                    return; // CDI not registered on this environment.
                            }

                            this.beanManager = beanManager;
                            Class<?> beanManagerClass = beanManager.getClass();
                            Class<?> contextualClass = Class.forName("javax.enterprise.context.spi.Contextual");
                            Class<?> beanClass = Class.forName("javax.enterprise.inject.spi.Bean");
                            Class<?> creationalContextClass = Class.forName("javax.enterprise.context.spi.CreationalContext");
                            getBeans = beanManagerClass.getMethod("getBeans", Type.class, Annotation[].class);
                            resolve = beanManagerClass.getMethod("resolve", Set.class);
                            createCreationalContext = beanManagerClass.getMethod("createCreationalContext", contextualClass);
                            getReference = beanManagerClass.getMethod("getReference", beanClass, Type.class, creationalContextClass);
                    }
                    catch (Exception e) {
                            logger.log(Level.SEVERE, LOG_INITIALIZATION_ERROR, e);
                            throw new RuntimeException(e);
                    }
            }
    }

Stacktrace: added

Nov 08, 2013 12:10:01 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: .
Nov 08, 2013 12:10:01 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Nov 08, 2013 12:10:01 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Nov 08, 2013 12:10:01 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 607 ms
Nov 08, 2013 12:10:01 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Nov 08, 2013 12:10:01 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
Nov 08, 2013 12:10:01 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor E:\Tomcats\apache-tomcat-7.0.47\conf\Catalina\localhost\
Nov 08, 2013 12:10:09 PM com.sun.faces.config.ConfigureListener contextInitialized
INFO: Mojarra 2.1.26 ( 20130905-1451 https://svn.java.net/svn/mojarra~svn/tags/2.1.26@12478) für Kontext '/a' wird initialisiert.
Nov 08, 2013 12:10:09 PM com.sun.faces.spi.InjectionProviderFactory createInstance
INFO: JSF1048: PostConstruct/PreDestroy-Annotationen vorhanden.  Verwaltete Bean-Methoden, die mit diesen Annotationen markiert sind, lassen die entsprechenden Annotationen verarbeiten.
Nov 08, 2013 12:10:10 PM org.primefaces.webapp.PostConstructApplicationEventListener processEvent
Nov 08, 2013 12:10:10 PM org.omnifaces.VersionLoggerEventListener processEvent
INFO: Using OmniFaces version 1.6.3
Nov 08, 2013 12:10:10 PM com.sun.faces.config.ConfigureListener$WebConfigResourceMonitor$Monitor <init>
INFO: Monitoring jndi:/localhost/../WEB-INF/faces-config.xml for modifications
Nov 08, 2013 12:10:10 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory E:\Tomcats\apache-tomcat-7.0.47\webapps\host-manager
Nov 08, 2013 12:10:11 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory E:\Tomcats\apache-tomcat-7.0.47\webapps\manager
Nov 08, 2013 12:10:11 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory E:\Tomcats\apache-tomcat-7.0.47\webapps\ROOT
Nov 08, 2013 12:10:11 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Nov 08, 2013 12:10:11 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Nov 08, 2013 12:10:11 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 9572 ms
Nov 08, 2013 12:10:32 PM org.omnifaces.config.BeanManager init
SEVERE: BeanManager enum singleton failed to initialize.
java.lang.IllegalStateException: javax.naming.NamingException: Cannot create resource instance
    at org.omnifaces.util.JNDI.lookup(JNDI.java:87)
    at org.omnifaces.config.BeanManager.init(BeanManager.java:79)
    at org.omnifaces.config.BeanManager.getReference(BeanManager.java:115)
    at org.omnifaces.application.OmniApplication.createValidator(OmniApplication.java:105)
    at org.jboss.weld.environment.servlet.jsf.ForwardingApplication.createValidator(ForwardingApplication.java:152)
    at com.sun.faces.component.validator.ComponentValidators.addValidatorsToComponent(ComponentValidators.java:280)
    at com.sun.faces.component.validator.ComponentValidators.addDefaultValidatorsToComponent(ComponentValidators.java:147)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.processValidators(ComponentTagHandlerDelegateImpl.java:541)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.privateOnComponentPopulated(ComponentTagHandlerDelegateImpl.java:522)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:194)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:187)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at com.sun.faces.facelets.tag.jsf.core.FacetHandler.apply(FacetHandler.java:104)
    at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:166)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:320)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:379)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:358)
    at com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199)
    at com.sun.faces.facelets.tag.ui.IncludeHandler.apply(IncludeHandler.java:120)
    at com.sun.faces.facelets.tag.ui.DefineHandler.applyDefinition(DefineHandler.java:106)
    at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:178)
    at com.sun.faces.facelets.impl.DefaultFaceletContext$TemplateManager.apply(DefaultFaceletContext.java:395)
    at com.sun.faces.facelets.impl.DefaultFaceletContext.includeDefinition(DefaultFaceletContext.java:366)
    at com.sun.faces.facelets.tag.ui.InsertHandler.apply(InsertHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:187)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:187)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:187)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:187)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:187)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
    at com.sun.faces.facelets.tag.jsf.core.ViewHandler.apply(ViewHandler.java:188)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:187)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:320)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:379)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:358)
    at com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199)
    at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:155)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
    at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:164)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:914)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.omnifaces.filter.FacesExceptionFilter.doFilter(FacesExceptionFilter.java:56)
    at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:75)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.omnifaces.filter.GzipResponseFilter.doFilter(GzipResponseFilter.java:149)
    at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:75)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
Caused by: javax.naming.NamingException: Cannot create resource instance
    at org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:117)
    at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:843)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:154)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:831)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:154)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:831)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:168)
    at org.apache.naming.SelectorContext.lookup(SelectorContext.java:158)
    at javax.naming.InitialContext.lookup(InitialContext.java:411)
    at org.omnifaces.util.JNDI.lookup(JNDI.java:83)
    ... 92 more

Faces-Config:

<factory>    
    <exception-handler-factory>org.omnifaces.exceptionhandler.FullAjaxExceptionHandlerFactory</exception-handler-factory>
</factory>

web.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"  
  metadata-complete="true">


  <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>server</param-value>
  </context-param>

  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>    
  </context-param>  
  <context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/taglib.xml;/WEB-INF/functions.taglib.xml</param-value>
  </context-param>

  <filter>
    <filter-name>facesExceptionFilter</filter-name>
    <filter-class>org.omnifaces.filter.FacesExceptionFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>facesExceptionFilter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
  <listener>
    <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
  </listener>    

  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
  <error-page>
    <exception-type>javax.faces.application.ViewExpiredException</exception-type>
    <location>/WEB-INF/errorpages/expired.xhtml</location>
  </error-page>
  <error-page>
    <exception-type>com.sun.faces.context.FacesFileNotFoundException</exception-type>
    <location>/WEB-INF/errorpages/expired.xhtml</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/errorpages/500.xhtml</location>
  </error-page>
  <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/errorpages/404.xhtml</location>
  </error-page>
  <filter>
    <filter-name>gzipResponseFilter</filter-name>
    <filter-class>org.omnifaces.filter.GzipResponseFilter</filter-class>
  </filter>
        <filter-mapping>
                <filter-name>gzipResponseFilter</filter-name>
                <url-pattern>*</url-pattern>
                <dispatcher>REQUEST</dispatcher>
                <dispatcher>ERROR</dispatcher>
        </filter-mapping>


  <resource-env-ref>
    <resource-env-ref-name>BeanManager</resource-env-ref-name>   
    <resource-env-ref-type>javax.enterprise.inject.spi.BeanManager</resource-env-ref-type>        
  </resource-env-ref>

<session-config><tracking-mode>COOKIE</tracking-mode></session-config>      
</web-app>

Addeded context.xml under META-INF:

<Context>
   <Resource name="BeanManager" 
      auth="Container"
      type="javax.enterprise.inject.spi.BeanManager"
      factory="org.jboss.weld.resources.ManagerObjectFactory"/>
    <Manager pathname="" />
</Context>

Source: (StackOverflow)