Injecting a bean returns null [duplicate] - jsf

This question already has answers here:
Accessing injected dependency in managed bean constructor causes NullPointerException
(1 answer)
#Inject field is always null [duplicate]
(1 answer)
Closed 6 years ago.
I have two webpages with a bean backing each as well as multiple DAOs running on a Glassfish 4.0 server. The first page is a loginpage - everything works fine here and I can access the injected objects.
On the second page however, every time I try to access one of the injected objects I get a nullpointer-exception.
This is my (working) loginpage:
#ViewScoped
#Named
public class indexController implements Serializable {
private static final Logger log = Logger.getLogger(indexController.class.getName());
private String passwort, growlMsg;
#Inject
Manager manager;
#Inject
PersonalDAO personalDAO;
public indexController() {
}
public String login() {
System.out.println("------------------LOGIN-----------------------\n"
+ "Werk: " + getWerk() + "\n"
+ "Mandant: " + getMandant() + "\n"
+ "Personalnr:" + getPersnr() + "\n"
+ "Passwort: " + passwort + "\n"
+ "----------------------------------------------");
if (isValidUser()) {
manager.setUserVerified(true);
return "main";
} else {
FacesContext ctx = FacesContext.getCurrentInstance();
ctx.addMessage(null, new FacesMessage("Login failed.", "Please verify your login credentials."));
return "index";
}
}
//TODO: Implement hashing and salting
private boolean isValidUser() {
List<Personal> pers = personalDAO.find(getPersnr());
if (pers.isEmpty()) {
return false;
}
Personal personal = pers.get(0);
if (personal.getWerk().getId() != getWerk()) {
return false;
}
if (personal.getMandant().getId() != getMandant()) {
return false;
}
if (!personal.getPasswort().equals(passwort)) {
return false;
}
return true;
}
private boolean isInteger(String n) {
try {
Integer.parseInt(n);
} catch (NumberFormatException ex) {
return false;
}
return true;
}
public int getMandant() {
return manager.getMandant();
}
public void setMandant(int mandant) {
manager.setMandant(mandant);
}
public int getWerk() {
return manager.getWerk();
}
public void setWerk(int werk) {
manager.setWerk(werk);
}
public int getPersnr() {
return manager.getPersnr();
}
public void setPersnr(int persnr) {
manager.setPersnr(persnr);
}
public String getPasswort() {
return passwort;
}
public void setPasswort(String passwort) {
this.passwort = passwort;
}
public String getGrowlMsg() {
return growlMsg;
}
public void setGrowlMsg(String growlMsg) {
this.growlMsg = growlMsg;
}
}
This is the bean I am having issues with:
#RequestScoped
#Named
public class mainController implements Serializable {
private List<Abwesenheit> abwesenheit;
private List<Personal> personal;
#Inject
Manager manager;
#Inject
PersonalDAO personalDAO;
#Inject
AbwesenheitDAO abwesenheitDAO;
public mainController() {
System.out.println("-----MAINCONTROLLER CALLED-----");
System.out.println(manager.isUserVerified());
System.out.println("-----------------------------------");
}
public List<Abwesenheit> getAbwesenheit() {
return abwesenheit;
}
public void setAbwesenheit(List<Abwesenheit> abwesenheit) {
this.abwesenheit = abwesenheit;
}
public List<Personal> getPersonal() {
return personal;
}
public String getVerified() {
return manager.isUserVerified()?"Verified":"Not Verified";
}
}
Manager class:
#SessionScoped
public class Manager implements Serializable {
//TODO: Use an enum for access-levels instead of just access/no access
private boolean userVerified = false;
int werk, mandant, persnr;
public Manager() {
}
public boolean isUserVerified() {
return userVerified;
}
public void setUserVerified(boolean userVerified) {
this.userVerified = userVerified;
}
public int getWerk() {
return werk;
}
public void setWerk(int werk) {
this.werk = werk;
}
public int getMandant() {
return mandant;
}
public void setMandant(int mandant) {
this.mandant = mandant;
}
public int getPersnr() {
return persnr;
}
public void setPersnr(int persnr) {
this.persnr = persnr;
}
}
personalDAO class:
#Stateless
public class PersonalDAO implements Serializable {
#PersistenceContext(unitName="GFOS_AwardPU")
private EntityManager entityManager;
public List<Personal> getPersonal() {
return entityManager.createNamedQuery("Personal.findAll", Personal.class).getResultList();
}
public List<Personal> find(String personalNr) {
Query query = entityManager.createNamedQuery("Personal.findByPersonalnr");
query.setParameter("personalnr", personalNr);
return query.getResultList();
}
public List<Personal> find(int personalNr) {
Query query = entityManager.createNamedQuery("Personal.findByPersonalnr");
query.setParameter("personalnr", personalNr);
return query.getResultList();
}
public List<Personal> find(String personalNr, String name, String vorname, String mandant, String werk) {
String query = "SELECT * FROM Personal WHERE 1=1";
if(personalNr != null && !personalNr.isEmpty()) {
query += " AND Personalnr="+personalNr;
}
if(name != null && !name.isEmpty()) {
query += " AND name='"+name+"'";
}
if(vorname != null && !vorname.isEmpty()) {
query += " AND vorname='"+vorname+"'";
}
if(mandant != null && !mandant.isEmpty()) {
query += " AND mandant="+mandant;
}
if(werk != null && !werk.isEmpty()) {
query += " AND werk="+werk;
}
return entityManager.createNativeQuery(query, Personal.class).getResultList();
}
}
This is the Glassfish server log extract, there are no exceptions prior:
[2016-03-10T19:43:21.303+0100] [glassfish 4.0] [INFO] [] [] [tid: _ThreadID=22 _ThreadName=Thread-3] [timeMillis: 1457635401303] [levelValue: 800] [[
-----MAINCONTROLLER CALLED-----]]
[2016-03-10T19:43:21.304+0100] [glassfish 4.0] [SEVERE] [] [javax.enterprise.resource.webcontainer.jsf.application] [tid: _ThreadID=22 _ThreadName=http-listener-1(5)] [timeMillis: 1457635401304] [levelValue: 1000] [[
Error Rendering View[/main.xhtml]
java.lang.NullPointerException
at controller.mainController.<init>(mainController.java:38)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:79)
at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:63)
at org.jboss.weld.injection.producer.AbstractInstantiator.newInstance(AbstractInstantiator.java:29)
at org.jboss.weld.injection.producer.DefaultInstantiator.newInstance(DefaultInstantiator.java:90)
at org.jboss.weld.injection.producer.BasicInjectionTarget.produce(BasicInjectionTarget.java:86)
at org.jboss.weld.injection.producer.BeanInjectionTarget.produce(BeanInjectionTarget.java:172)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:157)
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.el.AbstractWeldELResolver.lookup(AbstractWeldELResolver.java:133)
at org.jboss.weld.el.AbstractWeldELResolver.getValue(AbstractWeldELResolver.java:96)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:188)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:116)
at com.sun.el.parser.AstValue.getBase(AstValue.java:151)
at com.sun.el.parser.AstValue.getValue(AstValue.java:200)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.LabelRenderer.encodeBegin(LabelRenderer.java:120)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:869)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1854)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
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:188)
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(Unknown Source)
]]
[2016-03-10T19:43:21.358+0100] [glassfish 4.0] [INFO] [] [] [tid: _ThreadID=22 _ThreadName=Thread-3] [timeMillis: 1457635401358] [levelValue: 800] [[
-----MAINCONTROLLER CALLED-----]]
[2016-03-10T19:43:21.375+0100] [glassfish 4.0] [FATAL] [jsf.context.exception.handler.log] [javax.enterprise.resource.webcontainer.jsf.context] [tid: _ThreadID=22 _ThreadName=http-listener-1(5)] [timeMillis: 1457635401375] [levelValue: 1100] [[
JSF1073: java.lang.NullPointerException erfasst w?hrend Verarbeitung von RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=null]]
[2016-03-10T19:43:21.376+0100] [glassfish 4.0] [FATAL] [] [javax.enterprise.resource.webcontainer.jsf.context] [tid: _ThreadID=22 _ThreadName=http-listener-1(5)] [timeMillis: 1457635401376] [levelValue: 1100] [[
java.lang.NullPointerException
at controller.mainController.<init>(mainController.java:38)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:79)
at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:63)
at org.jboss.weld.injection.producer.AbstractInstantiator.newInstance(AbstractInstantiator.java:29)
at org.jboss.weld.injection.producer.DefaultInstantiator.newInstance(DefaultInstantiator.java:90)
at org.jboss.weld.injection.producer.BasicInjectionTarget.produce(BasicInjectionTarget.java:86)
at org.jboss.weld.injection.producer.BeanInjectionTarget.produce(BeanInjectionTarget.java:172)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:157)
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.el.AbstractWeldELResolver.lookup(AbstractWeldELResolver.java:133)
at org.jboss.weld.el.AbstractWeldELResolver.getValue(AbstractWeldELResolver.java:96)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:188)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:116)
at com.sun.el.parser.AstValue.getBase(AstValue.java:151)
at com.sun.el.parser.AstValue.getValue(AstValue.java:200)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.LabelRenderer.encodeBegin(LabelRenderer.java:120)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:869)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1854)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
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:188)
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(Unknown Source)
]]
Why doesn't it work in the mainController class? I've tried changing the scopes of both classes but that did not help. Netbeans does not show any errors. I have also tried starting Glassfish trough both Netbeans or manual. The last thing I tried is changing the imports from
import javax.faces.bean.RequestScoped
(and the SessionScoped of the manager-class) to
import javax.enterprise.context.RequestScoped
yet none of it fixed my problem.

Instead of constructor
public mainController() {
System.out.println("-----MAINCONTROLLER CALLED-----");
System.out.println(manager.isUserVerified());
System.out.println("-----------------------------------");
}
use method with annotation #PostConstruct.
#PostConstruct
private void init() {
System.out.println("-----MAINCONTROLLER INITIALIZED-----");
System.out.println(manager.isUserVerified());
System.out.println("-----------------------------------");
}
Dependencies are not yet injected in constructor, they can be accessed after object is created.

Related

Binding attribute in #ViewScoped causes remote EJB to throw java.io.NotSerializableException

When I send an object of class which doesn't implement Serializable to remote EJB it handles it, but things change when one field of this class is a programmatic UIComponent used in binding attribute from a #ViewScoped backing bean. In second case java.io.NotSerializableException is thrown.
Form
<h:form>
<p:panel binding="#{bean.notSerializableObj.pfPanel}"/>
<h:inputText value="#{bean.notSerializableObj.someString}" />
<p:commandButton value="GO" action="#{bean.sendToEjb}"/>
</h:form>
Backing bean
#Named(value = "bean")
#ViewScoped
public class Bean implements Serializable {
#EJB
private RemoteEjbService service;
private NotSerializableClass notSerializableObj;
public NotSerializableClass getNotSerializableObj() {
return notSerializableObj;
}
public void setNotSerializableObj(NotSerializableClass notSerializableObj) {
this.notSerializableObj = notSerializableObj;
}
#PostConstruct
private void init() {
Panel p = new Panel();
System.out.println("INIT Panel: " + p);
notSerializableObj = new NotSerializableClass("myObject", p);
}
public void sendToEjb() {
System.out.println("Sending to EJB");
trySending();
System.out.println("Second try with new object");
Panel p = new Panel();
notSerializableObj.setPfPanel(p);
trySending();
}
private void trySending() {
try {
System.out.println("Panel: " + notSerializableObj.getPfPanel());
service.notSerializableTest(notSerializableObj);
System.out.println("Sent correctly");
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
NotSerializableClass
public class NotSerializableClass {
private String someString;
private Panel pfPanel; // PrimeFaces panel not implementing Serializable
public NotSerializableClass(String someString, Panel pfPanel) {
this.someString = someString;
this.pfPanel = pfPanel;
}
//getters setters
}
Results
Info: INIT Panel: org.primefaces.component.panel.Panel#9f68a9
Info: Sending to EJB
Info: Panel: org.primefaces.component.panel.Panel#9f68a9
Info: Exception: javax.ejb.EJBException: java.rmi.MarshalException: CORBA BAD_PARAM 1398079494 Maybe; nested exception is:
java.io.NotSerializableException: WARNING: 00100006: Class test.NotSerializableClass is not Serializable
Info: Second try with new object
Info: Panel: org.primefaces.component.panel.Panel#e59fd7
Info: Sent correctly
On the first try exception is thrown, on the second try object was successfully send despite not implementing Serializable. When I removed binding attribute there wasn't any exception thrown in the first trySending().
There is no difference if I set javax.faces.STATE_SAVING_METHOD to server or client. But it works if bean is #RequestScoped or #SessionScoped or remote interface is replaced with local one.
The question is: What changes in object when it is connected to binding attribute because somehow EJB can't handle it afterwards?
Panel wasn't serialized after creation because hashcode in #PostConstruct and submitting method is the same.
Full stack trace
Severe: javax.ejb.EJBException: java.rmi.MarshalException: CORBA BAD_PARAM 1398079494 Maybe; nested exception is:
java.io.NotSerializableException: WARNING: 00100006: Class test.NotSerializableClass is not Serializable
at mot.services._RemoteEjbService_Wrapper.notSerializableTest(mot/services/_RemoteEjbService_Wrapper.java)
at test.MyBean.trySending(MyBean.java:104)
at test.MyBean.sendToEjb(MyBean.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at test.CountingFilter.doFilter(CountingFilter.java:35)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
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:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.rmi.MarshalException: CORBA BAD_PARAM 1398079494 Maybe; nested exception is:
java.io.NotSerializableException: WARNING: 00100006: Class test.NotSerializableClass is not Serializable
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:300)
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.wrapException(Util.java:695)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:257)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:150)
at com.sun.corba.ee.impl.presentation.rmi.codegen.CodegenStubBase.invoke(CodegenStubBase.java:226)
at mot.services.__RemoteEjbService_Remote_DynamicStub.notSerializableTest(mot/services/__RemoteEjbService_Remote_DynamicStub.java)
... 54 more
Caused by: java.io.NotSerializableException: WARNING: 00100006: Class test.NotSerializableClass is not Serializable
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:292)
... 59 more
Caused by: org.omg.CORBA.BAD_PARAM: WARNING: 00100006: Class test.NotSerializableClass is not Serializable vmcid: SUN minor code: 6 completed: Maybe
at com.sun.proxy.$Proxy209.notSerializable(Unknown Source)
at com.sun.corba.ee.impl.misc.ORBUtility.throwNotSerializableForCorba(ORBUtility.java:783)
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.writeAny(Util.java:360)
at com.sun.corba.ee.impl.io.ValueHandlerImpl.write_Array(ValueHandlerImpl.java:498)
at com.sun.corba.ee.impl.io.ValueHandlerImpl.writeValueInternal(ValueHandlerImpl.java:232)
at com.sun.corba.ee.impl.io.ValueHandlerImpl.writeValueWithVersion(ValueHandlerImpl.java:215)
at com.sun.corba.ee.impl.io.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:179)
at com.sun.corba.ee.impl.encoding.CDROutputStream_1_0.callWriteValue(CDROutputStream_1_0.java:711)
at com.sun.corba.ee.impl.encoding.CDROutputStream_1_0.writeArray(CDROutputStream_1_0.java:627)
at com.sun.corba.ee.impl.encoding.CDROutputStream_1_0.write_value(CDROutputStream_1_0.java:808)
at com.sun.corba.ee.impl.encoding.CDROutputStream_1_0.write_value(CDROutputStream_1_0.java:834)
at com.sun.corba.ee.impl.encoding.CDROutputObject.write_value(CDROutputObject.java:500)
at com.sun.corba.ee.impl.copyobject.ORBStreamObjectCopierImpl.copy(ORBStreamObjectCopierImpl.java:73)
at org.glassfish.pfl.dynamic.copyobject.impl.FallbackObjectCopierImpl.copy(FallbackObjectCopierImpl.java:64)
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.copyObject(Util.java:770)
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.copyObjects(Util.java:741)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.copyArguments(DynamicMethodMarshallerImpl.java:438)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:225)
... 57 more

ClassCastException with CDI producer method and groovy class from script

I am learning about Groovy Language and possibilities to integrate it with CDI.
In java class path, a have a interface called Product. I created a CDI Producer Method that returns a Product type.
At another class, I performs a injection of a Product, that comes from the CDI Producer Method.
Out of classpath, I wrote a groovy script, with a simple groovy class, that implements the Product interface.
Inside CDI Producer Method, I use GroovyScriptEngine to retrieve the Class object from script, to create a CDI Bean.
I am using
Weld version 2.2.8.Final as CDI implementation.
Groovy at version 2.3.9.
The Tomcat server 7.
Using JSF 2.2.8 as well.
(thinking that problem is related only to Weld Implementation of CDI eh Groovy)
All works fine at first time. It is possible using the created bean inside JSF pages, clicking in button and performs actions at the server side, and refresh the page on browser. All declared methods and fields on groovy script class can be accessd and used with JSF pages. The CDI container performs the calling of #PostConstruct as well. The CDI Producer Method is can be called many time, and all works.
As said, all works fine at the first time. But when the groovy script changes, a ClassCastException is thrown.
Someone can help me to about this? Is this a Weld/Groovy issue, or simply not possible?
The Product interface:
package test;
/**
*
* #author Welyab
*/
#ProductMethodIntercetor
public interface Product {
public void a();
public void b();
}
The groovy script that implements the Product interface:
package test
class ProductImplWithGroovy implements test.Product {
#javax.annotation.PostConstruct
def void init(){
println "call init()"
}
def void a(){
println "call a()";
}
def void b(){
println "call b()";
}
def void c(){
println "call c()";
}
}
The producer class/method:
package test;
import groovy.util.GroovyScriptEngine;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.CDI;
import javax.enterprise.inject.spi.InjectionTarget;
import javax.enterprise.util.AnnotationLiteral;
/**
*
* #author Welyab
*/
public class ProductsTest {
private static GroovyScriptEngine se;
static {
try {
se = new GroovyScriptEngine(new URL[]{
new File("c:/users/welyab/desktop").toURI().toURL()
});
}
catch (IOException ex) {
ex.printStackTrace();
}
}
#Produces
#ProductProducer
public Product criarProduto() {
BeanManager bm = CDI.current().getBeanManager();
final Class klazz;
try {
klazz = se.loadScriptByName("script_test.groovy");
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
Class finalKlazz = klazz;
AnnotatedType annotatedType = bm.createAnnotatedType(finalKlazz);
InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
Bean bean = new Bean() {
#Override
public Class getBeanClass() {
return finalKlazz;
}
#Override
public Set getInjectionPoints() {
return injectionTarget.getInjectionPoints();
}
#Override
public boolean isNullable() {
return false;
}
#Override
public Object create(CreationalContext creationalContext) {
Object instance = injectionTarget.produce(creationalContext);
injectionTarget.inject(instance, creationalContext);
injectionTarget.postConstruct(instance);
return instance;
}
#Override
public void destroy(Object instance, CreationalContext creationalContext) {
injectionTarget.preDestroy(instance);
injectionTarget.dispose(instance);
creationalContext.release();
}
#Override
public Set<?> getTypes() {
Set<Type> types = new HashSet<>();
types.add(finalKlazz);
types.add(Product.class);
types.add(Object.class);
return types;
}
#Override
public Set getQualifiers() {
Set<Annotation> qualifiers = new HashSet<Annotation>();
qualifiers.add(new AnnotationLiteral<Default>() {
});
qualifiers.add(new AnnotationLiteral<Any>() {
});
return qualifiers;
}
#Override
public Class getScope() {
return ApplicationScoped.class;
}
#Override
public String getName() {
return "product";
}
#Override
public Set getStereotypes() {
return Collections.emptySet();
}
#Override
public boolean isAlternative() {
return false;
}
};
CreationalContext ctx = bm.createCreationalContext(bean);
Product produto = (Product) bm.getReference(bean, finalKlazz, ctx);
return produto;
}
}
The bean to JSF page:
package test;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
/**
*
* #author Welyab
*/
#Named
#RequestScoped
public class TestBean {
#Inject
#ProductProducer
private Product product;
public Product getProduct() {
return product;
}
}
A simple fraggmento of JSF page that uses the bean.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
template="/install/ayszu-template.xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:jsf="http://xmlns.jcp.org/jsf"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<ui:define name="body">
<form jsf:id="form" >
<h:commandButton value="a" action="#{testBean.product.a}" />
<h:commandButton value="b" action="#{testBean.product.b}" />
<h:commandButton value="c" action="#{testBean.product.c}" />
</form>
</ui:define>
</ui:composition>
The stacktrace with the error [all exception looks like caused by the class casting exception]
30-Dec-2014 18:59:37.944 WARNING [http-nio-8082-exec-24] com.sun.faces.lifecycle.InvokeApplicationPhase.execute #{testBean.product.c}: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
javax.faces.FacesException: #{testBean.product.c}: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
call init()
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:226)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.welyab.ayszu.core.MainFilter.doFilter(MainFilter.java:72)
at com.welyab.ayszu.core.MainFilter.doFilter(MainFilter.java:67)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 35 more
Caused by: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
at test.ProductImplWithGroovy$Proxy$_$$_WeldClientProxy.c(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.el.parser.AstValue.invoke(AstValue.java:275)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 36 more
30-Dec-2014 18:59:38.182 FATAL [http-nio-8082-exec-24] com.sun.faces.context.ExceptionHandlerImpl.log JSF1073: javax.faces.FacesException obtido durante o processamento de INVOKE_APPLICATION 5: UIComponent-ClientId=, Message=#{testBean.product.c}: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
30-Dec-2014 18:59:38.191 FATAL [http-nio-8082-exec-24] com.sun.faces.context.ExceptionHandlerImpl.log #{testBean.product.c}: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
javax.faces.FacesException: #{testBean.product.c}: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:89)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:226)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.welyab.ayszu.core.MainFilter.doFilter(MainFilter.java:72)
at com.welyab.ayszu.core.MainFilter.doFilter(MainFilter.java:67)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.FacesException: #{testBean.product.c}: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
... 31 more
Caused by: javax.faces.el.EvaluationException: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 35 more
Caused by: java.lang.ClassCastException: test.ProductImplWithGroovy cannot be cast to test.ProductImplWithGroovy
at test.ProductImplWithGroovy$Proxy$_$$_WeldClientProxy.c(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.el.parser.AstValue.invoke(AstValue.java:275)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 36 more

Using Map to populate multiple SelectManyCheckboxes - ClassCastException

In my controller, there is a Collection of "questions" with possible answer-options. My view iterates the questions with an ui:repeat. When I try to read the selected options, I get a java.lang.ClassCastException:
javax.faces.FacesException: #{cbtestController.submit}: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.util.List
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.omnifaces.facesviews.FacesViewsForwardingFilter.doFilter(FacesViewsForwardingFilter.java:130)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
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:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.util.List
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 41 more
Caused by: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.util.List
at de.zulu.zuluvoting.controller.cbtestController.submit(cbtestController.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 42 more
Controller:
#ManagedBean
#ViewScoped
public class cbtestController implements Serializable, Converter {
private Map<Long, List<SelectItem>> availableItems;
private Map<Long, List<String>> selectedItems;
// ... getters and setters
public List<Long> getIds() {
List<Long> result = new ArrayList<>(availableItems.keySet());
return result;
}
public List<SelectItem> availableItemsById(Long id) {
return availableItems.get(id);
}
#PostConstruct
private void init() {
selectedItems = new HashMap<>();
availableItems = new HashMap<>();
availableItems.put(0L, new ArrayList<SelectItem>());
availableItems.get(0L).add(new SelectItem("option0_1", "Option 0.1"));
availableItems.get(0L).add(new SelectItem("option0_2", "Option 0.2"));
availableItems.put(1L, new ArrayList<SelectItem>());
availableItems.get(1L).add(new SelectItem("option1_1", "Option 1.1"));
availableItems.get(1L).add(new SelectItem("option1_2", "Option 1.2"));
}
public void submit() {
System.out.println("selectedItems = " + selectedItems); // (1)
for (Long id : selectedItems.keySet()) {
System.out.println("selectedItems[" + id + "] = " + selectedItems.get(id)); // (2)
for (String selectedItem : selectedItems
.get(id)) // ClassCastException here
{
System.out.println(" > " + selectedItem);
}
}
}
(1) prints "selectedItems = {0=[Ljava.lang.String;#30185d04, 1=[Ljava.lang.String;#661abe68}"
(2) prints "selectedItems[0] = [Ljava.lang.String;#30185d04"
View:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<head>
<title>TODO supply a title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<h:form>
<ui:repeat value="#{cbtestController.ids}"
var="id">
<h:selectManyCheckbox value="#{cbtestController.selectedItems[id]}"
layout="pageDirection">
<f:selectItems value="#{cbtestController.availableItemsById(id)}" />
</h:selectManyCheckbox>
</ui:repeat>
<h:commandButton action="#{cbtestController.submit}"
value="Submit"/>
</h:form>
</body>
</html>
I have been trying to get this working for some time now, and this it's getting really frustrating. I have also tried to write a converter, but I still get a ClassCastException (Not sure if this is correct):
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
for (Long id : availableItems.keySet()) {
List<SelectItem> items = availableItems.get(id);
for (SelectItem item : items) {
if (((String)item.getValue()).equals(value)) {
return item;
}
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return (String)value;
}
Do I even need the converter? What am I doing wrong?
I've experienced a somewhat similar problem. I had a Map with a List of Integers as value. Much like you. And I was using the Map value with a h:selectManyCheckbox inside a ui:repeat as well. But I kept getting ClassCastExceptions because the Map value for some reason was a List of Strings instead, when I submitted my form.
I ended up using a IntegerArray class instead of a List as value in my Map. That class then held the (in my case) array of Integers.
IntegerArray:
public class IntegerArray implements Serializable {
private Integer[] array;
public IntegerArray() {
}
public IntegerArray(Integer[] array) {
this.array = array;
}
public Integer[] getArray() {
return array;
}
public void setArray(Integer[] array) {
this.array = array;
}
}
That worked.

transaction aborted error message notification change

I have added unique constraints to my database table to prevent duplicate entries. I have tested it and its working fine, On my page when when I try to submit the same values I get a message saying transaction aborted which means its working fine, is there a way to change the message:
Transaction aborted
To something like:
Task already assigned to user!
If so how would I change it?
If Possible to only change the message for unique constraint violation that would be great.
I choose the values and save them with create method:
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("webConstants/Bundle").getString("TimeLoggingDetailCreated"));
recreateModel();
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("webConstants/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
And display the message on the page like this:
<h:panelGroup id="messagePanel" layout="block" >
<h:messages infoClass="alert alert-success" errorClass="alert alert-danger" layout="row col-12" warnClass="alert alert-info" fatalClass="alert"/>
</h:panelGroup>
Stacktrace:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1-1-1-1' for key 'logging_unique'
Error Code: 1062
Call: INSERT INTO MY_LOGGING (CUSTOMERS_ID, EMPLOYEES_EMPLOYEE_NO, PROJECTS_ID, TASKS_ID) VALUES (?, ?, ?, ?)
bind => [4 parameters bound]
Query: InsertObjectQuery(za.co.company.entity.Logging[ id=null ])
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl$1.handleException(EntityManagerSetupImpl.java:692)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.handleException(AbstractSynchronizationListener.java:275)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:170)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:854)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:719)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4475)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2009)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1979)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy2187.create(Unknown Source)
at za.co.company.session.__EJB31_Generated__LoggingFacade__Intf____Bean__.create(Unknown Source)
at za.co.company.controller.LoggingController.create(LoggingController.java:89)
at za.co.company.controller.LoggingController$Proxy$_$$_WeldClientProxy.create(Unknown Source)
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 com.sun.el.parser.AstValue.invoke(AstValue.java:275)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
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:188)
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:744)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1-1-1-1' for key 'logging_unique'
Error Code: 1062
web.xml:
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
SHORT VERSION : Just remove the "e, " in your JsfUtil.addErrorMessage(...)
It seems you are using generated Code from Netbeans like me :-)
I ran into the same problem, but I found the problems source ..
in Class JSFUtil is a method addErrorMessage(...) which is called by your Exception which looks up for a localized String of your Exception (EJBException) and also found it.
The Problem - your second Parameter "String defaultMsg" is not used in this case
public static void addErrorMessage(Exception ex, String defaultMsg) {
String msg = ex.getLocalizedMessage();
System.out.println("DefaultMsg: " + defaultMsg);
System.out.println("LocalMsg: " + msg);
if (msg != null && msg.length() > 0) {
addErrorMessage(msg);
} else {
addErrorMessage(defaultMsg);
}
}
So you can rewrite that method or or just use addErrorMessage(String msg) in your try..catch-block which directly returns your own String from Bundle.properites file
public void create() {
try {
getFacade().create(current);
recreateModel();
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("StandortCreated"));
} catch (EJBException e) {
JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Bundle").getString("YourOwnFromBundle"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
Regards Chris

Error pages for exceptions during page rendering

In the backing beans of my JSF application, certain exceptions may be thrown at any time, and I want to react to this by redirecting to an error page. I have included the omnifaces FullAjaxExceptionHandler, and my web.xml contains
<error-page>
<exception-type>my.own.ResourceNotFoundException</exception-type>
<location>/error/error404.xhtml</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/error500.xhtml</location>
</error-page>
In most cases, including Ajax requests, this works fine: ResourceNotFoundException leads me to the error page. However, when the exception is thrown in a method annotaded with #PostConstruct, I always get the generic page for error code 500.
Is this because JSF wraps the exception in something else and the mechanism in web.xml does not recognize it? If yes, how can I get this to work as expected?
Here is the exception trace I see in the server log:
Feb 07, 2013 11:08:32 AM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
SEVERE: Error Rendering View[/my/projects/details/details.xhtml]
javax.el.ELException: //P:/codebase/code/portal/jsf-impl/target/classes/META-INF/resources/common/title.xhtml: Bei der Ressourcen-Einspeisung auf dem verwalteten Bean projectDetailsController ist ein Fehler aufgetreten.
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:90)
at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:309)
at com.sun.faces.renderkit.html_basic.GroupRenderer.encodeChildren(GroupRenderer.java:105)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1779)
at com.sun.faces.renderkit.html_basic.CompositeRenderer.encodeChildren(CompositeRenderer.java:78)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1779)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
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:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at my.own.filters.SecurityFilter.doFilter(SecurityFilter.java:48)
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:224)
at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:185)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.__invoke(StandardHostValve.java:151)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at my.own.UTF8Valve.invoke(UTF8Valve.java:34)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: com.sun.faces.mgbean.ManagedBeanCreationException: Bei der Ressourcen-Einspeisung auf dem verwalteten Bean projectDetailsController ist ein Fehler aufgetreten.
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:229)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:105)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
at org.apache.el.parser.AstValue.getValue(AstValue.java:147)
at org.apache.el.parser.AstDeferredExpression.getValue(AstDeferredExpression.java:44)
at org.apache.el.parser.AstCompositeExpression.getValue(AstCompositeExpression.java:50)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.UIComponentBase$AttributesMap.get(UIComponentBase.java:2362)
at com.sun.faces.el.CompositeComponentAttributesELResolver$ExpressionEvalMap.get(CompositeComponentAttributesELResolver.java:345)
at javax.el.MapELResolver.getValue(MapELResolver.java:52)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:227)
at com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(ELText.java:150)
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:85)
... 43 more
Caused by: com.sun.faces.spi.InjectionProviderException
at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:119)
at com.sun.faces.vendor.WebContainerInjectionProvider.invokePostConstruct(WebContainerInjectionProvider.java:99)
at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:223)
... 66 more
Caused by: java.lang.reflect.InvocationTargetException
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 com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:117)
... 68 more
Caused by: my.own.ResourceNotFoundException: Did not find project
at my.own.projects.details.ProjectDetailsController.createModel(ProjectDetailsController.java:198)
As your log suggests, ResourceNotFoundException is wrapped in four other exceptions.
You could develop your own CustomExceptionHandler like the one in Duke's Forest example instead of using omnifaces FullAjaxExceptionHandler or even extend it and go down causes until you reach ResourceNotFoundException then use NavigationHandler to redirect to the desired error page.
Here is edited version of related classes and faces-config.xml from Duke's Forest example. This should work as you expect even if the exception occurs in #PostConstruct method:
CustomExceptionHandlerFactory.java
package com.forest.exception;
public class CustomExceptionHandlerFactory extends ExceptionHandlerFactory {
private ExceptionHandlerFactory parent;
// this injection handles jsf
public CustomExceptionHandlerFactory(ExceptionHandlerFactory parent) {
this.parent = parent;
}
#Override
public ExceptionHandler getExceptionHandler() {
ExceptionHandler handler = new CustomExceptionHandler(parent.getExceptionHandler());
return handler;
}
}
CustomExceptionHandler.java
package com.forest.exception;
public class CustomExceptionHandler extends ExceptionHandlerWrapper {
private static final Logger log = Logger.getLogger(CustomExceptionHandler.class.getCanonicalName());
private ExceptionHandler wrapped;
CustomExceptionHandler(ExceptionHandler exception) {
this.wrapped = exception;
}
#Override
public ExceptionHandler getWrapped() {
return wrapped;
}
private boolean includesResourceNotFoundException(Throwable t) {
if(t == null) {
return false;
else {
return t instanceof ResourceNotFoundException || includesResourceNotFoundException(t.getCause());
}
}
#Override
public void handle() throws FacesException {
final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
while (i.hasNext()) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context =
(ExceptionQueuedEventContext) event.getSource();
// get the exception from context
Throwable t = context.getException();
final FacesContext fc = FacesContext.getCurrentInstance();
final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
final NavigationHandler nav = fc.getApplication().getNavigationHandler();
//here you do what ever you want with exception
if(hasResourceNotFoundException(t) {
try {
//log error ?
log.log(Level.SEVERE, "Critical Exception!", t);
//redirect error page
requestMap.put("exceptionMessage", t.getMessage());
nav.handleNavigation(fc, null, "/error/error500?face-redirect=true");
fc.renderResponse();
} finally {
//remove it from queue
i.remove();
}
}
}
//parent hanle
getWrapped().handle();
}
}
faces-config.xml (partial)
<factory>
<exception-handler-factory>
com.forest.exception.CustomExceptionHandlerFactory
</exception-handler-factory>
</factory>

Resources