EJB3 - JSF cannot update entity it excute insert statement why? - jsf

hello all new problem i cant solved
i have 1 entity below
package com.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author Kency
*/
#Entity
#Table(name = "about")
#NamedQueries({
#NamedQuery(name = "About.findAll", query = "SELECT a FROM About a"),
#NamedQuery(name = "About.findByAboutTitle", query = "SELECT a FROM About a WHERE a.aboutTitle = :aboutTitle")})
public class About implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "about_title")
private String aboutTitle;
#Basic(optional = false)
#Lob
#Column(name = "content")
private String content;
public About() {
}
/* public About(String aboutTitle) {
this.aboutTitle = aboutTitle;
}*/
public About(String aboutTitle, String content) {
this.aboutTitle = aboutTitle;
this.content = content;
}
public About(String aboutTitle) {
this.aboutTitle = aboutTitle;
}
public String getAboutTitle() {
return aboutTitle;
}
public void setAboutTitle(String aboutTitle) {
this.aboutTitle = aboutTitle;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Override
public int hashCode() {
int hash = 0;
hash += (aboutTitle != null ? aboutTitle.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof About)) {
return false;
}
About other = (About) object;
if ((this.aboutTitle == null && other.aboutTitle != null) || (this.aboutTitle != null && !this.aboutTitle.equals(other.aboutTitle))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.About[aboutTitle=" + aboutTitle + "]";
}
}
my stateless bean
package com.DAO;
import com.entity.About;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author Kency
*/
#Stateless
#LocalBean
public class AboutDAO {
#PersistenceContext(unitName = "mcGrawLibPro-ejbPU")
private EntityManager em;
public About retrieveAbout(){
Query query = em.createNamedQuery("About.findAll");
return (About) query.getSingleResult();
}
public void persist(Object object) {
em.persist(object);
}
public About updateAbout(About abouts){
return em.merge(abouts);
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
my JSF managed bean controller
package com.mcgraw.controller;
import com.DAO.AboutDAO;
import com.entity.About;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
/**
*
* #author Kency
*/
#ManagedBean
#SessionScoped
public class AboutController implements Serializable{
#EJB
private AboutDAO aboutDAO;
private About about ;
private String toolbar = "maxi";
public String getToolbar() {
return toolbar;
}
public void setToolbar(String toolbar) {
this.toolbar = toolbar;
}
public About getAbout() {
return aboutDAO.retrieveAbout();
}
public void setAbout(About about) {
this.about = about;
}
/** Creates a new instance of AboutController */
public AboutController() {
about = new About();
}
public void updateAbout(){
about = aboutDAO.updateAbout(about);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"", "Update ok"));
}
}
my JSF page code
<p:dialog widgetVar="about" header="About">
<f:view>
<h:form>
<h:inputText value="#{aboutController.about.aboutTitle}"/>
<p:editor value="#{aboutController.about.content}" widgetVar="editor"/>
<p:commandButton value="Submit" onclick="editor.saveHTML()" action="#{aboutController.updateAbout}"/>
<p:messages/>
</h:form>
</f:view>
</p:dialog>
my problem is when i click submit button it not update it throw exception null in insert statement
i want update but why it insert to database??
everybody have idea for solve it ? thank you
my stacktrace
WARNING: Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'about_title' cannot be null
Error Code: 1048
Call: INSERT INTO about (about_title, content) VALUES (?, ?)
bind => [null, null]
Query: InsertObjectQuery(com.entity.About[aboutTitle=null])
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:801)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:867)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:587)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:530)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeCall(AbstractSession.java:914)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:205)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:191)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:334)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:461)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:286)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:675)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:589)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:109)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:86)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2857)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1225)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1207)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1167)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:197)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:103)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3260)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1403)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:547)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1508)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3128)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:268)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:157)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:412)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:837)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5040)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4805)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2004)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1955)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:198)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:84)
at $Proxy114.updateAbout(Unknown Source)
at com.DAO.__EJB31_Generated__AboutDAO__Intf____Bean__.updateAbout(Unknown Source)
at com.mcgraw.controller.AboutController.updateAbout(AboutController.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:98)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
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:775)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at com.mcgraw.controller.UserLoginFilter.doFilter(UserLoginFilter.java:60)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at com.mcgraw.controller.UserLoginFilter.doFilter(UserLoginFilter.java:60)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:619)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'about_title' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2409)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2327)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2312)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:792)
... 91 more
column content in database type is TEXT

You've bound your JSF input element to #{aboutController.about}. This invokes the getter:
public About getAbout() {
return aboutDAO.retrieveAbout();
}
Which in turn invokes the DB query:
public About retrieveAbout(){
Query query = em.createNamedQuery("About.findAll");
return (About) query.getSingleResult();
}
So you are getting a new About object every time the getter is invoked. What you should be doing is binding to a specific "about" instance, then sending that instance back to your Stateless Session Bean to be updated. You store this "about" instance as the property of your Managed Bean, and return that with the Managed Bean's getter.

Related

Bug with omnifaces 1.10 when OmniPartialViewContext#startDocument performs transparent redirection

I am using the following stack :
PrimeFaces 5.3.1
MyFaces 2.2.8
OpenWebBeans 1.6.2
OmniFaces 1.10
DeltaSpike 1.5.1
Tomcat 8.0.28
AFAI understand, only MyFaces and OmniFaces are important there.
I have a bug when an ajax request is performed by a client whose session is expired and when the access to the page is controlled by a <security-constraint> in the webapp web.xml.
In that case, OmniPartialViewContext#startDocument perform a "transparent redirect", to provide a better explanation (see https://github.com/omnifaces/omnifaces/blob/master/src/main/java/org/omnifaces/context/OmniPartialViewContext.java#L275 ) (this function is unchanged from version 1.10 to current 1.11).
#Override
public void startDocument() throws IOException {
wrapped.startDocument();
String loginURL = WebXml.INSTANCE.getFormLoginPage();
if (loginURL != null) {
FacesContext facesContext = FacesContext.getCurrentInstance();
String loginViewId = normalizeViewId(facesContext, loginURL);
if (loginViewId.equals(getViewId(facesContext))) {
String originalURL = getRequestAttribute(facesContext, "javax.servlet.forward.request_uri");
if (originalURL != null) {
redirect(originalURL);
}
}
}
}
This is a problem because, higher in the stack, org.apache.myfaces.context.servlet.PartialViewContextImpl.processPartialRendering does lines 466 and following :
{
String currentEncoding = writer.getCharacterEncoding();
writer.writePreamble("<?xml version=\"1.0\" encoding=\""+
(currentEncoding == null ? "UTF-8" : currentEncoding) +"\"?>");
writer.startDocument();
writer.writeAttribute("id", viewRoot.getContainerClientId(_facesContext),"id");
So, an exception like the following is raised when trying to write the id, because no element is currently opened.
16-Nov-2015 16:36:35.980 SEVERE [http-apr-8444-exec-10] org.omnifaces.exceptionhandler.FullAjaxExceptionHandler.logException FullAjaxExceptionHandler: An exception occurred during rendering JSF ajax response. Error page '/error.xhtml' will be shown.
java.lang.IllegalStateException: Must be called before the start element is closed (attribute 'id')
at org.apache.myfaces.shared.renderkit.html.HtmlResponseWriterImpl.writeAttribute(HtmlResponseWriterImpl.java:816)
at javax.faces.context.ResponseWriterWrapper.writeAttribute(ResponseWriterWrapper.java:109)
at org.apache.myfaces.context.PartialResponseWriterImpl.writeAttribute(PartialResponseWriterImpl.java:407)
at javax.faces.context.ResponseWriterWrapper.writeAttribute(ResponseWriterWrapper.java:109)
at javax.faces.context.ResponseWriterWrapper.writeAttribute(ResponseWriterWrapper.java:109)
at org.apache.myfaces.context.servlet.PartialViewContextImpl.processPartialRendering(PartialViewContextImpl.java:473)
at org.apache.myfaces.context.servlet.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:415)
at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:85)
at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:516)
at javax.faces.component.UIComponentBase.encodeAll(UIComponentBase.java:541)
at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1891)
at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:313)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:58)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:116)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:267)
at org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeLifecycleWrapper.render(DeltaSpikeLifecycleWrapper.java:111)
at javax.faces.lifecycle.LifecycleWrapper.render(LifecycleWrapper.java:31)
at org.apache.deltaspike.jsf.impl.listener.request.JsfClientWindowAwareLifecycleWrapper.render(JsfClientWindowAwareLifecycleWrapper.java:160)
at org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeLifecycleWrapper.render(DeltaSpikeLifecycleWrapper.java:111)
at javax.faces.lifecycle.LifecycleWrapper.render(LifecycleWrapper.java:31)
at org.apache.deltaspike.jsf.impl.listener.request.JsfClientWindowAwareLifecycleWrapper.render(JsfClientWindowAwareLifecycleWrapper.java:160)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:200)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
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.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:720)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.catalina.authenticator.FormAuthenticator.forwardToLoginPage(FormAuthenticator.java:384)
at org.apache.catalina.authenticator.FormAuthenticator.authenticate(FormAuthenticator.java:229)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:577)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java:291)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2503)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2492)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
How can I correct that (appart from dropping OmniFaces, which is really cool, and that I would really like to keep. :-) ) ?
Eventually, I am using the following solution, which can be seen as a work around, as patching MyFaces or OmniFaces is out of my reach...
I am adding my own PartialViewContext at the top of the processing chain. This way, I can perform a clean redirect on an ajax request when I can see it is trying to get the login page.
To do so, one has to :
implement a PartialViewContextFactory
implement a PartialViewContext
declare the PartialViewContextFactory in the faces-config.xml file
So, in my webapp faces-config.xml, I put :
<factory>
<partial-view-context-factory>fr.senat.context.SenatPartialViewContextFactory</partial-view-context-factory>
</factory>
My PartialViewContextFactory is dead simple :
package fr.senat.context;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialViewContext;
import javax.faces.context.PartialViewContextFactory;
import lombok.Getter;
/**
*
* #author lpenet
*/
public class SenatPartialViewContextFactory extends PartialViewContextFactory {
#Getter
private final PartialViewContextFactory wrapped;
public SenatPartialViewContextFactory(PartialViewContextFactory wrapped) {
this.wrapped = wrapped;
}
#Override
public PartialViewContext getPartialViewContext(FacesContext context) {
return new SenatPartialViewContext(wrapped.getPartialViewContext(context));
}
}
and the PartialViewContext is quite simple too :
package fr.senat.context;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.context.PartialViewContext;
import javax.faces.context.PartialViewContextWrapper;
import javax.faces.event.PhaseId;
import javax.servlet.http.HttpServletRequest;
import lombok.Getter;
import org.apache.myfaces.context.servlet.PartialViewContextImpl;
import org.omnifaces.config.WebXml;
import static org.omnifaces.util.FacesLocal.getRequestAttribute;
import static org.omnifaces.util.FacesLocal.getViewId;
import static org.omnifaces.util.FacesLocal.normalizeViewId;
/**
*
* #author lpenet
*/
public class SenatPartialViewContext extends PartialViewContextWrapper {
#Getter
private final PartialViewContext wrapped;
public SenatPartialViewContext(PartialViewContext wrapped) {
this.wrapped = wrapped;
}
private void processPartialRendering() throws IOException
{
FacesContext facesContext = FacesContext.getCurrentInstance();
UIViewRoot viewRoot = facesContext.getViewRoot();
String loginURL = WebXml.INSTANCE.getFormLoginPage();
if (loginURL != null) {
String loginViewId = normalizeViewId(facesContext, loginURL);
if (loginViewId.equals(getViewId(facesContext))) {
String originalURL = getRequestAttribute(facesContext, "javax.servlet.forward.request_uri");
if (originalURL != null) {
PartialResponseWriter writer = facesContext.getPartialViewContext().getPartialResponseWriter();
writer.startDocument();
HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest();
writer.redirect(request.getContextPath() + loginURL);
writer.endDocument();
return;
}
}
}
wrapped.processPartial(PhaseId.RENDER_RESPONSE);
}
#Override
public void processPartial(PhaseId phaseId)
{
if (phaseId == PhaseId.RENDER_RESPONSE)
{
try {
processPartialRendering();
}
catch (IOException ex)
{
Logger log = Logger.getLogger(PartialViewContextImpl.class.getName());
if (log.isLoggable(Level.SEVERE))
{
log.log(Level.SEVERE, "", ex);
}
}
} else {
wrapped.processPartial(phaseId);
}
}
}

WELD-001408: Unsatisfied dependencies for type Employee with qualifiers #Default

I got the following error when deploying to Glassfish on Netbeans. This is the first time I am trying to CDI. I have read all the post on this issue up to no help.
Log:
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: visiting unvisited references
Info: Enity.Test.Employee actually got transformed
Info: EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
Info: file:/C:/Users/Bala/Documents/NetBeansProjects/TestAppl/dist/gfdeploy/TestAppl/TestAppl-ejb_jar/_TestAppl-ejbPU login successful
Info: Portable JNDI names for EJB EmployeeEJB: [java:global/TestAppl/TestAppl-ejb/EmployeeEJB, java:global/TestAppl/TestAppl-ejb/EmployeeEJB!SessionlessEmployee.EmployeeEJB]
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] public org.glassfish.jms.injection.JMSCDIExtension.processAnnotatedType(#Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using #WithAnnotations or a generic type with bounds.
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] org.glassfish.sse.impl.ServerSentEventCdiExtension.processAnnotatedType(#Observes ProcessAnnotatedType<Object>, BeanManager) receives events for all annotated types. Consider restricting events using #WithAnnotations or a generic type with bounds.
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.gf.cdi.internal.CdiComponentProvider.processAnnotatedType(#Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using #WithAnnotations or a generic type with bounds.
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] public org.glassfish.jms.injection.JMSCDIExtension.processAnnotatedType(#Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using #WithAnnotations or a generic type with bounds.
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] org.glassfish.sse.impl.ServerSentEventCdiExtension.processAnnotatedType(#Observes ProcessAnnotatedType<Object>, BeanManager) receives events for all annotated types. Consider restricting events using #WithAnnotations or a generic type with bounds.
WARN: WELD-000411: Observer method [BackedAnnotatedMethod] private org.glassfish.jersey.gf.cdi.internal.CdiComponentProvider.processAnnotatedType(#Observes ProcessAnnotatedType<Object>) receives events for all annotated types. Consider restricting events using #WithAnnotations or a generic type with bounds.
Severe: Exception during lifecycle processing
org.glassfish.deployment.common.DeploymentException: CDI deployment failure:WELD-001408: Unsatisfied dependencies for type Employee with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private Managedbean.Testapp.employeeController.employee
at Managedbean.Testapp.employeeController.employee(employeeController.java:0)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:234)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:496)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
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: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Employee with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private Managedbean.Testapp.employeeController.employee
at Managedbean.Testapp.employeeController.employee(employeeController.java:0)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:370)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:291)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:165)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:529)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:515)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:490)
at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:419)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:225)
... 41 more
Severe: Exception while loading the app
Severe: Undeployment failed for context /TestAppl-war
Info: file:/C:/Users/Bala/Documents/NetBeansProjects/TestAppl/dist/gfdeploy/TestAppl/TestAppl-ejb_jar/_TestAppl-ejbPU logout successful
Severe: Exception while loading the app : CDI deployment failure:WELD-001408: Unsatisfied dependencies for type Employee with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private Managedbean.Testapp.employeeController.employee
at Managedbean.Testapp.employeeController.employee(employeeController.java:0)
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Employee with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private Managedbean.Testapp.employeeController.employee
at Managedbean.Testapp.employeeController.employee(employeeController.java:0)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:370)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:291)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:165)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:529)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:515)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:490)
at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:419)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:225)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:496)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
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)
My program code:
TestAppl-war
Index.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2" >
<h:outputLabel value="First Name : "/>
<h:inputText value="#{employeeController.employee.firstname}" />
<h:outputLabel value="Last Name : "/>
<h:inputText value="#{employeeController.employee.lastName}"/>
<h:outputLabel value="Date of Birth : "/>
<h:inputText value="#{employeeController.employee.dob}">
<f:convertDateTime pattern="dd/mm/yyyy"/>
</h:inputText>
<h:outputLabel value="Phone : "/>
<h:inputText value="#{employeeController.employee.phone}"/>
<h:outputLabel value="Email : "/>
<h:inputText value="#{employeeController.employee.email}"/>
</h:panelGrid>
<h:commandButton value="Add New Employee"
action="#{employeeController.addNewEmployee()}"/>
</h:form>
</h:body>
</html>
employeeController.java
package Managedbean.Testapp;
import Enity.Test.Employee;
import SessionlessEmployee.EmployeeEJB;
import java.io.Serializable;
import java.util.Date;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
/**
*
* #author Bala
*/
#Named(value = "employeeController")
#RequestScoped
public class employeeController implements Serializable {
private Employee employee = new Employee();
#Inject private EmployeeEJB employeeEJB;
/**
* Creates a new instance of employeeController
*/
private static final long serialVersionUID = 1L;
private String firstname;
private String middlename;
private String lastname;
private Date dob;
private String phone;
private String email;
public employeeController() {
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setDob(Date dob) {
this.dob = dob;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setEmail(String email) {
this.email = email;
}
public void addNewEmployee() {
employee = employeeEJB.addNew(employee);
}
}
EmployeeEJB
package SessionlessEmployee;
import Enity.Test.Employee;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
#Stateless
#LocalBean
public class EmployeeEJB {
#PersistenceContext(unitName = "TestAppl-ejbPU")
private EntityManager entityManager;
public List<Employee> findEmployees(){
TypedQuery<Employee> query = entityManager.createNamedQuery("findAllEmployees", Employee.class);
return query.getResultList();
}
public Employee addNew(Employee employee) {
entityManager.persist(employee);
return employee;
}
}
Employee
package Enity.Test;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "EMPLOYEE")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e"),
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.id = :id"),
#NamedQuery(name = "Employee.findByFirstname", query = "SELECT e FROM Employee e WHERE e.firstname = :firstname"),
#NamedQuery(name = "Employee.findByMiddlename", query = "SELECT e FROM Employee e WHERE e.middlename = :middlename"),
#NamedQuery(name = "Employee.findByLastname", query = "SELECT e FROM Employee e WHERE e.lastname = :lastname"),
#NamedQuery(name = "Employee.findByDob", query = "SELECT e FROM Employee e WHERE e.dob = :dob"),
#NamedQuery(name = "Employee.findByPhone", query = "SELECT e FROM Employee e WHERE e.phone = :phone"),
#NamedQuery(name = "Employee.findByEmail", query = "SELECT e FROM Employee e WHERE e.email = :email")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private Integer id;
#Size(max = 100)
#Column(name = "FIRSTNAME")
private String firstname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "MIDDLENAME")
private String middlename;
#Size(max = 100)
#Column(name = "LASTNAME")
private String lastname;
#Column(name = "DOB")
#Temporal(TemporalType.DATE)
private Date dob;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 10)
#Column(name = "PHONE")
private String phone;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Size(max = 100)
#Column(name = "EMAIL")
private String email;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Employee(Integer id, String middlename) {
this.id = id;
this.middlename = middlename;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Enity.Test.Employee[ id=" + id + " ]";
}
}
Table
create table "Database".EMPLOYEE
(
ID INTEGER not null primary key,
FIRSTNAME VARCHAR(100),
MIDDLENAME VARCHAR(100) not null,
LASTNAME VARCHAR(100),
DOB DATE,
PHONE VARCHAR(10),
EMAIL VARCHAR(100)
)
beans.xml
<?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"
bean-discovery-mode="all">
</beans>
This is auto generated source when I deploy
Employee_.java
package Enity.Test;
import java.util.Date;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
#Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2015-04-06T09:18:49")
#StaticMetamodel(Employee.class)
public class Employee_ {
public static volatile SingularAttribute<Employee, Integer> id;
public static volatile SingularAttribute<Employee, String> phone;
public static volatile SingularAttribute<Employee, String> middlename;
public static volatile SingularAttribute<Employee, String> email;
public static volatile SingularAttribute<Employee, Date> dob;
public static volatile SingularAttribute<Employee, String> lastname;
public static volatile SingularAttribute<Employee, String> firstname;
}
Any ideas?
This line of code in EmployeeController is causing the exception to be thrown
private #Inject Employee employee = new Employee();. You are trying to inject Employee but this isn't a bean which CDI can inject. If you drop the #Inject annotation it should resolve the problem.
As a side note private #Inject EmployeeEJB employeeEJB; should be annotated with #EJB rather than #Inject

A persistence error occurred in JSF application

I'm getting a persistence error when trying to submit a form in a jsf application. I'm using a glassfish server and a mysql database. When i try to add to the database i keep getting the error.
here is the code from the jsf page
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:body>
<--code omitted for clarity--->
<div id="cdscreatecontrol">
<div align="center"><h:commandButton action="#{cdsController.create}" immediate="true" value="#{bundle.CreateCdsSaveLink}"/></div>
<br /><div align="center"><h:commandButton action="#{cdsController.prepareList}" value="#{bundle.CreateCdsShowAllLink}" immediate="true"/></div>
<br /><div align="center"><h:link outcome="/index" value="Back to Login Page"/></div></div>
</h:form>
</ui:define>
</ui:composition>
</div>
<div id="footer" style="margin-top: 1100px"><div style="margin-top: 10px">
Copyright © David McGuinness IT Development DPD Athlone</div>
<div id="button">
<h:form><h:commandButton action="/mainmenu.xhtml"
image="menu.png" style="height: 20px; width: 90px; float: left;
margin-left: 15px;" onmouseover="this.src = 'menupress.png'"
onmouseout="this.src = 'menu.png'"></h:commandButton></h:form>
<h:form><h:commandButton onclick="window.opener=null;window.open('','_self');window.close();"
image="exit.png" style="height: 20px; width: 90px; float: right;
margin-right: 15px;" onmouseover="this.src = 'exitpress.png'"
onmouseout="this.src = 'exit.png'"></h:commandButton></h:form>
</div>
</div>
</div>
</h:body>
</html>
here the code form the java file
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jpa.entities;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author david.mcguinness
*/
#Entity
#Table(name = "cds")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Cds.findAll", query = "SELECT c FROM Cds c"),
#NamedQuery(name = "Cds.findByDatecreated", query = "SELECT c FROM Cds c WHERE c.datecreated = :datecreated"),
#NamedQuery(name = "Cds.findByDpdaccountno", query = "SELECT c FROM Cds c WHERE c.dpdaccountno = :dpdaccountno"),
#NamedQuery(name = "Cds.findByCustname", query = "SELECT c FROM Cds c WHERE c.custname = :custname"),
#NamedQuery(name = "Cds.findByExistingcust", query = "SELECT c FROM Cds c WHERE c.existingcust = :existingcust"),
#NamedQuery(name = "Cds.findByDepot", query = "SELECT c FROM Cds c WHERE c.depot = :depot"),
#NamedQuery(name = "Cds.findByItcontact", query = "SELECT c FROM Cds c WHERE c.itcontact = :itcontact"),
#NamedQuery(name = "Cds.findByConspernight", query = "SELECT c FROM Cds c WHERE c.conspernight = :conspernight"),
#NamedQuery(name = "Cds.findByDomestic", query = "SELECT c FROM Cds c WHERE c.domestic = :domestic"),
#NamedQuery(name = "Cds.findByUk", query = "SELECT c FROM Cds c WHERE c.uk = :uk"),
#Column(name = "datecreated" )
#Temporal(TemporalType.DATE)
private Date datecreated;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 225)
#Column(name = "dpdaccountno")
private String dpdaccountno;
#Size(max = 225)
#Column(name = "custname")
private String custname;
#Size(max = 4)
#Column(name = "existingcust")
private String existingcust;
#Size(max = 225)
#Column(name = "depot")
private String depot;
#Size(max = 225)
#Column(name = "itcontact")
private String itcontact;
#Column(name = "conspernight")
private Integer conspernight;
#Size(max = 4)
#Column(name = "domestic")
private String domestic;
#Size(max = 4)
#Column(name = "uk")
private String uk;
public Cds() {
}
public Cds(String dpdaccountno) {
this.dpdaccountno = dpdaccountno;
}
public Date getDatecreated() {
return datecreated;
}
public void setDatecreated(Date datecreated) {
this.datecreated = datecreated;
}
public String getDpdaccountno() {
return dpdaccountno;
}
public void setDpdaccountno(String dpdaccountno) {
this.dpdaccountno = dpdaccountno;
}
public String getCustname() {
return custname;
}
public void setCustname(String custname) {
this.custname = custname;
}
public String getExistingcust() {
return existingcust;
}
public void setExistingcust(String existingcust) {
this.existingcust = existingcust;
}
public String getDepot() {
return depot;
}
public void setDepot(String depot) {
this.depot = depot;
}
public String getItcontact() {
return itcontact;
}
public void setItcontact(String itcontact) {
this.itcontact = itcontact;
}
public Integer getConspernight() {
return conspernight;
}
public void setConspernight(Integer conspernight) {
this.conspernight = conspernight;
}
public String getDomestic() {
return domestic;
}
public void setDomestic(String domestic) {
this.domestic = domestic;
}
public String getUk() {
return uk;
}
public void setUk(String uk) {
this.uk = uk;
}
#Override
public int hashCode() {
int hash = 0;
hash += (dpdaccountno != null ? dpdaccountno.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Cds)) {
return false;
}
Cds other = (Cds) object;
if ((this.dpdaccountno == null && other.dpdaccountno != null) || (this.dpdaccountno != null && !this.dpdaccountno.equals(other.dpdaccountno))) {
return false;
}
return true;
}
#Override
public String toString() {
return "jpa.entities.Cds[ dpdaccountno=" + dpdaccountno + " ]";
}
}
here is the code from the abstractFacade Class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jpa.session;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* #author david.mcguinness
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
here is the entire stack trace
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
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.$Proxy237.create(Unknown Source)
at jpa.session.__EJB31_Generated__CdsFacade__Intf____Bean__.create(Unknown Source)
at jsf.CdsController.create(CdsController.java:84)
at jsf.CdsController$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.processDecodes(UIViewRoot.java:931)
at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
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: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:90)
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.prePersist(Be anValidationListener.java:62)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:748)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:691)
at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:229)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:4310)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4287)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4229)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:287)
at jpa.session.AbstractFacade.create(AbstractFacade.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:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
at sun.reflect.GeneratedMethodAccessor130.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
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.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 50 more
#NamedQuery(name = "Cds.findByNorthernirelandb", query = "SELECT c FROM Cds c WHERE #NamedQuery(name = "Cds.findBySwapit", query = "SELECT c FROM Cds c WHERE c.swapit = :swapit"),
Of course, with such a mistake, you will get a compilation error (of the persistence layer). Can you spot your mistake ?
Edit :
OK, as you have re-edited your question and as the problem is not coming from the above named query, I can now tell you that you are most probably forgetting to set the id of the entity while trying to persist it, or that one or some of the entries do not respect fixed constraints.
Try to commit the transaction in a try catch block of statements (catch with ConstraintViolationException).
To know the constraint violations before the commit , you can insert this block of code
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Cds>> constraintViolations = validator.validate(theObjectInQuestion);
if (constraintViolations.size() > 0 ) {
System.out.println("Constraint Violations occurred..");
for (ConstraintViolation<Cds> contraints : constraintViolations) {
System.out.println(contraints.getRootBeanClass().getSimpleName()+
"." + contraints.getPropertyPath() + " " + contraints.getMessage());
}
}
As reported in the exception log, the method at jsf.CdsController.create(CdsController.java:84) is trying to create an entity of type Cds that doesn't pass the validation constraints:
javax.validation.ConstraintViolationException: Bean Validation constraint(s)
violated while executing Automatic Bean Validation on callback event:'prePersist'
Since you haven't yet posted the way you have initialized the entity, and since the exception is not telling anything about which property is failing the validation, it's hard to tell more, but you can debug in many ways, like:
by removing one by one all the properties and changing the db table structure accordingly, until the exception goes away
by removing one by one the #NotNull and #Size constraints until the exception goes away (be careful, if the db table structure is not updated accordingly, you might have db errors)
as suggested in the comment by SujanSivagurunathan, by catching the ConstraintViolationException in order to get more infos about the exception itself.
See also:
The Java EE 7 Tutorial: Using Bean Validation Constraints

How to Inject EJB3.1 session bean into JSF2.2 managed bean in JEE Enterprise application with Glassfish 4.0 server

I created a new Java EE 6 Enterprise-Application in Netbeans 7.4. So I have three Projects:
EAR
EJB
WAR
In order to implement the login functionality. I created the following.
In the EJB-Project, I have created a an entity bean(Useraccount) and stateless session Bean(UseraccoountManager) as follows:
Entity bean: Useraccount
package com.wms.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "useraccount")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Useraccount.findAll", query = "SELECT u FROM Useraccount u"),
#NamedQuery(name = "Useraccount.findById", query = "SELECT u FROM Useraccount u WHERE u.id = :id"),
#NamedQuery(name = "Useraccount.findByUsername", query = "SELECT u FROM Useraccount u WHERE u.username = :username"),
#NamedQuery(name = "Useraccount.findByPassword", query = "SELECT u FROM Useraccount u WHERE u.password = :password"),
#NamedQuery(name = "UserAccount.findUseraccount", query = "SELECT a FROM Useraccount a WHERE a.username = :username AND a.password = :password"),
#NamedQuery(name = "Useraccount.findByUserType", query = "SELECT u FROM Useraccount u WHERE u.userType = :userType")})
public class Useraccount implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "username")
private String username;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "password")
private String password;
#Size(max = 45)
#Column(name = "userType")
private String userType;
public Useraccount() {
}
public Useraccount(Integer id) {
this.id = id;
}
public Useraccount(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Useraccount)) {
return false;
}
Useraccount other = (Useraccount) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.wms.entities.Useraccount[ id=" + id + " ]";
}
}
Session bean: UseraccountManager
package com.wms.sessions;
import com.wms.entities.Useraccount;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
#Stateless
public class UseraccountManager implements UseraccountManagerRemote{
#PersistenceContext
private EntityManager em;
public List<Useraccount> getAllUseraccount() {
Query query=em.createNamedQuery("Useraccount.findAll");
return query.getResultList();
}
public Useraccount update(Useraccount useraccount) {
return em.merge(useraccount);
}
#Override
public void persist(Object object) {
em.persist(object);
}
public Useraccount find(Useraccount useraccount){
Query query=em.createNamedQuery("Useraccount.findByUsername").setParameter("username", useraccount.getUsername());
List<Useraccount> acts=query.getResultList();
if(acts.isEmpty())
return null;
Useraccount act=acts.get(0);
if(!act.getPassword().equals(useraccount.getPassword()))
return null;
return act;
}
#Override
public String validateUser(String username, String password){
System.out.println("\n\n\nheloooo\n\n\n");
Query query=em.createNamedQuery("Useraccount.findByUsername").setParameter("username", username);
List<Useraccount> acts=query.getResultList();
if(acts.isEmpty())
return "unknown";
Useraccount act=acts.get(0);
if(act.getPassword().equals(password))
return act.getUserType();
return "unknown";
}
}
2.In the Web application project, I created the Managed bean(LoginBean) and Login page(login.xhtml) as follows
Managed bean: LoginBean
package com.wms.managedbeans;
import com.wms.sessions.UseraccountManager;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
#Named
#RequestScoped
public class LoginBean implements Serializable {
private static final long serialVersionUID = 1L;
private String password;
private String message, username;
private String userType;
#EJB
private UseraccountManager uam;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String uname) {
this.username = uname;
}
public String getUser() {
System.out.println(Util.getUserId());
return Util.getUserId();
}
public String getUserType(){
HttpSession session = Util.getSession();
if ( session != null )
return (String) session.getAttribute("userType");
else
return null;
}
public String login() {
userType = uam.validateUser(username, password);
HttpSession session = Util.getSession();
if (userType.equals("unknown")){
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_WARN,
"Invalid Login!",
"Please Try Again!"));
// invalidate session, and redirect to other pages
//message = "Invalid Login. Please Try Again!";
return "login";
}
else{
// get Http Session and store username
session.setAttribute("username", username);
session.setAttribute("userType",userType);
if (userType.equals("administrator"))
return "admin/adminHome?faces-redirect=true";
else if(userType.equals("warehouseman"))
return "WM/wmHome?faces-redirect=true";
else if(userType.equals("employee"))
return "emp/empHome?faces-redirect=true";
else
return "man/manHome?faces-redirect=true";
}
}
public String logout() {
HttpSession session = Util.getSession();
session.invalidate();
return "/login?faces-redirect=true";
}
}
User Interface: login.xhtml
<ui:composition template="/templates/layout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:define name="content">
<h:form styleClass="loginPanelStyle">
<p:growl id="msgs" showDetail="true" sticky="false" />
<p:panelGrid columns="2">
<f:facet name="header">
Login Panel
</f:facet>
<h:outputText value="Username : "></h:outputText>
<p:inputText id="username" value="#{loginBean.username}" required="true" requiredMessage="Please Enter Username!">
<f:validateLength minimum="1" />
</p:inputText>
<h:outputText value="Password : "></h:outputText>
<p:password id="password" value="#{loginBean.password}" required="true" requiredMessage="Please Enter password!">
<f:validateLength minimum="1" />
</p:password>
<f:facet name="footer">
<p:commandButton id="Submit" value="Submit" update="msgs" action="#{loginBean.login}" type="submit" icon="ui-icon-check" style="margin:0"></p:commandButton>
</f:facet>
</p:panelGrid>
</h:form>
</ui:define>
</ui:composition>
After deploying the project when I run the web app it displays the login page, unforunately when i insert and it generates the following error
WARNING: /login.xhtml #16,131 value="#{loginBean.username}": Target Unreachable, identifier 'loginBean' resolved to null
javax.el.PropertyNotFoundException: /login.xhtml #16,131 value="#{loginBean.username}": Target Unreachable, identifier 'loginBean' resolved to null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
at org.primefaces.renderkit.InputRenderer.findImplicitConverter(InputRenderer.java:170)
at org.primefaces.renderkit.InputRenderer.findConverter(InputRenderer.java:190)
at org.primefaces.renderkit.InputRenderer.getConvertedValue(InputRenderer.java:196)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1046)
at javax.faces.component.UIInput.validate(UIInput.java:976)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
at javax.faces.component.UIInput.processValidators(UIInput.java:712)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at org.primefaces.component.layout.Layout.processValidators(Layout.java:246)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
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 filters.AuthFilter.doFilter(AuthFilter.java:44)
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: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: javax.el.PropertyNotFoundException: Target Unreachable, identifier 'loginBean' resolved to null
at com.sun.el.parser.AstValue.getTarget(AstValue.java:174)
at com.sun.el.parser.AstValue.getType(AstValue.java:86)
at com.sun.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:201)
at org.jboss.weld.el.WeldValueExpression.getType(WeldValueExpression.java:93)
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
... 51 more
I am new to EJB+JSF please help me to resolve the above problem
When I replace #Named annotation with #ManagedBean(name="loginBean") in the LoginBean managed bean class it works perfectly. But can any one explain me the difference between the two in this context. Thanks Luiggi Medoza for your help

Class Not Found Error in a refactor-moved JSF Managed Bean

I re factor and move JSF managed bean from one package to another package in Netbeans JSF application. Intermittently I get an error stating that the moved bean is not found in the previous location. I clean and build several times. Still the issue persists. I restarted the GlassFish and even the computer. I find in project including the generate sources, but I could not locate any reference to that Bean. I add the current location to the faces-config.xml, still no result.
The Previous Package is com.divudi.bean
New Package is com.divudi.bean.lab
The Error Message is
SEVERE: Exception while loading the app : com/divudi/bean/CollectingCentreController
java.lang.NoClassDefFoundError: com/divudi/bean/CollectingCentreController
at java.lang.Class.getDeclaringClass(Native Method)
at java.lang.Class.getEnclosingClass(Class.java:1107)
at java.lang.Class.getSimpleBinaryName(Class.java:1242)
at java.lang.Class.isMemberClass(Class.java:1232)
at org.jboss.weld.util.reflection.Reflections.isNonStaticInnerClass(Reflections.java:139)
at org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:78)
at org.jboss.weld.bootstrap.BeanDeployer.addClasses(BeanDeployer.java:123)
at org.jboss.weld.bootstrap.BeanDeployment.createBeans(BeanDeployment.java:184)
at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:350)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:179)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:277)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:460)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassNotFoundException: com.divudi.bean.CollectingCentreController
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
... 41 more
The Bean is (Before Adding to faces-config.xml, where annotation is used)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.divudi.bean.lab;
import com.divudi.bean.SessionController;
import com.divudi.bean.UtilityController;
import com.divudi.data.InstitutionType;
import com.divudi.entity.Institution;
import com.divudi.facade.InstitutionFacade;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
/**
*
* #author www.divudi.com
*/
#ManagedBean
public class CollectingCentreController {
/**
* Creates a new instance of CollectingCentreController
*/
public CollectingCentreController() {
}
private static final long serialVersionUID = 1L;
#ManagedProperty(value = "#{sessionController}")
SessionController sessionController;
#EJB
private InstitutionFacade ejbFacade;
List<Institution> selectedItems;
private Institution current;
private List<Institution> items = null;
String selectText = "";
public List<Institution> getSelectedItems() {
selectedItems = getFacade().findBySQL("select c from Institution c where c.retired=false and i.institutionType = com.divudi.data.InstitutionType.CollectingCentre and upper(c.name) like '%" + getSelectText().toUpperCase() + "%' order by c.name");
return selectedItems;
}
public void prepareAdd() {
current = new Institution();
current.setInstitutionType(InstitutionType.CollectingCentre);
}
public void setSelectedItems(List<Institution> selectedItems) {
this.selectedItems = selectedItems;
}
public String getSelectText() {
return selectText;
}
private void recreateModel() {
items = null;
}
public void saveSelected() {
if (getCurrent().getId() != null && getCurrent().getId() > 0) {
getFacade().edit(current);
UtilityController.addSuccessMessage("savedOldSuccessfully");
} else {
current.setCreatedAt(Calendar.getInstance(TimeZone.getTimeZone("IST")).getTime());
current.setCreater(sessionController.getLoggedUser());
getFacade().create(current);
UtilityController.addSuccessMessage("savedNewSuccessfully");
}
recreateModel();
getItems();
}
public void setSelectText(String selectText) {
this.selectText = selectText;
}
public InstitutionFacade getEjbFacade() {
return ejbFacade;
}
public void setEjbFacade(InstitutionFacade ejbFacade) {
this.ejbFacade = ejbFacade;
}
public SessionController getSessionController() {
return sessionController;
}
public void setSessionController(SessionController sessionController) {
this.sessionController = sessionController;
}
public Institution getCurrent() {
if (current == null) {
current = new Institution();
current.setInstitutionType(InstitutionType.CollectingCentre);
}
return current;
}
public void setCurrent(Institution current) {
this.current = current;
}
public void delete() {
if (current != null) {
current.setRetired(true);
current.setRetiredAt(Calendar.getInstance(TimeZone.getTimeZone("IST")).getTime());
current.setRetirer(sessionController.getLoggedUser());
getFacade().edit(current);
UtilityController.addSuccessMessage("DeleteSuccessfull");
} else {
UtilityController.addSuccessMessage("NothingToDelete");
}
recreateModel();
getItems();
current = null;
getCurrent();
}
private InstitutionFacade getFacade() {
return ejbFacade;
}
public List<Institution> getItems() {
// items = getFacade().findAll("name", true);
String sql = "SELECT i FROM Institution i where i.retired=false and i.institutionType = com.divudi.data.InstitutionType.CollectingCentre order by i.name";
items = getEjbFacade().findBySQL(sql);
if (items == null) {
items = new ArrayList<Institution>();
}
return items;
}
}

Resources