I have a JSF application that uses several java classes to do dynamic compilation of java code.
Code is written in a text area and compiled by pressing an h:commandButton via Ajax.
Problem occurs when i press more than 2 or 3 times to compile different codes.
Here is the stack trace :
javax.faces.application.ViewExpiredException: viewId:/home.xhtml - View /home.xhtml could not be restored.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:210)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:121)
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(Unknown Source)
If i set the attribute transient=true to f:view, the problem stops since the state is not saved, but that restricts me from using other functionality like saving my source file in database for user to retrieve in later time.
home.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>Home Page</title>
</h:head>
<h:body>
<f:view transient="true">
<h:form prependId="false">
<h:panelGrid columns="1">
<h:inputTextarea id="codeArea" rows="25" cols="70" value="#{user.userInputCode}" />
<h:outputText id="messages" value="#{user.compilationMessages}"/>
</h:panelGrid>
<h:commandButton value="Compile">
<f:ajax execute="codeArea" render="messages" listener="#{user.compileCode()}"/>
</h:commandButton>
</h:form>
</f:view>
</h:body>
</html>
UserBean
#Named(value = "user")
#SessionScoped
public class UserBean implements Serializable {
private String userInputCode;
private String compilationMessages;
private CompilerBean compiler;
public UserBean() {
compiler = new CompilerBean();
userInputCode = compiler.getDefaultCodeModel();
}
public String getUserInputCode() {
return userInputCode;
}
public void setUserInputCode(String userInputCode) {
this.userInputCode = userInputCode;
}
public String getCompilationMessages() {
return compilationMessages;
}
public void compileCode() throws Exception {
if (!compiler.isValidClass(userInputCode)) {
compilationMessages = "Please provide a correct class format";
} else {
if (compiler.compile(userInputCode)) {
compilationMessages = "Compilation Success!";
} else {
compilationMessages = compiler.getDiagnosticMessages();
}
}
}
Compiler
public class CompilerBean implements CompilationInterface {
private JavaCompiler compiler;
private DiagnosticCollector diagCollector;
private StandardJavaFileManager fileManager;
private String sourceFile;
public CompilerBean() {
sourceFile = DEFAULT_SOURCEFILE;
}
public boolean compile(String inputCode) throws Exception {
compiler = ToolProvider.getSystemJavaCompiler();
diagCollector = new DiagnosticCollector();
fileManager = compiler.getStandardFileManager(diagCollector, null, null);
File outputFile = new File(CLASS_FILES_PATH);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputFile));
String className = extractClassName(inputCode);
sourceFile = className + JAVA_POSTFIX;
JavaFileObject sourceObject = new CompilerJavaObject(sourceFile, inputCode);
Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(sourceObject);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagCollector, null, null, fileObjects);
deleteCompiledFiles();
return task.call();
}
public String getDiagnosticMessages() {
String message = "";
List<Diagnostic> diagErrors = diagCollector.getDiagnostics();
for (Diagnostic d : diagErrors) {
message = ("Error: " + d.getLineNumber() + " Cause: " + d.getMessage(null));
}
return message;
}
private void deleteCompiledFiles() {
File f = new File(CLASS_FILES_PATH);
for (File classFile : f.listFiles()) {
classFile.delete();
}
}
public String getDefaultCodeModel() {
return DEFAULT_CLASS_MODEL;
}
public String getSourceFile() {
return sourceFile;
}
/*
* Extracts the class name from the input code
*/
private String extractClassName(String input) {
String className = input.replaceAll(COMMENTS_REGEX, "");
className = className.replaceAll(IMPORTS_REGEX, "");
className = className.replaceAll(CLASS_BODY, "");
className = className.replaceAll(CLASS_REGEX, "").trim();
return className;
}
/*
* Checks if the input code is in a valid class format
*/
public boolean isValidClass(String input) {
Pattern pat1 = Pattern.compile(COMMENTS_REGEX);
Pattern pat2 = Pattern.compile(IMPORTS_REGEX);
Pattern pat3 = Pattern.compile(CLASS_REGEX);
Matcher m1 = pat1.matcher(input);
Matcher m2 = pat2.matcher(input);
Matcher m3 = pat3.matcher(input);
return m3.lookingAt() || m1.lookingAt() || m2.lookingAt();
}
}
Compiler uses 2 more class an Interface with some String constants and a class that extends SimpleJavaFileObject
There are a few approaches you can take:
Turn partial-state saving true in web.xml
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>true</param-value>
</context-param>
Increase the number of logical views in session. Note that JSF caches your views and there is a limit to that cache.
<context-param>
<param-name>com.sun.faces.NUMBER_OF_LOGICAL_VIEWS_IN_SESSION</param-name>
<param-value>50</param-value>
</context-param>
In cases where the above doesn't solve your problem, write a handler for ViewExpiredException and restore the view programatically. This will refresh your view on the client side(might not be the best user experience, though)
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.application.ViewHandlerWrapper;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
public class MyViewExpiredHandler extends ViewHandlerWrapper {
private ViewHandler wrapped;
private static Map<String, Boolean> viewsToProcess = new HashMap<String, Boolean>();
//assuming these xhtmls throw ViewExpiredException
static {
viewsToProcess.put("/view/xxxx.xhtml", true);
viewsToProcess.put("/view/aaa.xhtml", true);
viewsToProcess.put("/view/yyy.xhtml", true);
}
public MyViewExpiredHandler(ViewHandler parent) {
this.wrapped = parent;
}
#Override
public ViewHandler getWrapped() {
return wrapped;
}
#Override
public UIViewRoot restoreView(FacesContext context, String viewId) {
UIViewRoot viewRoot = super.restoreView(context, viewId);
if(viewsToProcess.containsKey(viewId) && viewRoot == null) {
viewRoot = super.createView(context, viewId);
super.initView(context);
try {
super.renderView(context, viewRoot);
} catch (FacesException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return viewRoot;
}
}
Related
I have a facelet page in which i have a primefaces selectCheckboxMenu where a user can select one or more conferences.
Primefaces 8.0,
5.194 #badassfish (build 327)|#]
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.3.9</version>
<scope>provided</scope>
</dependency>
I neeed to create a converter to convert between object and string. But no matter what I'm doing it does not work.
Either the stateless EJB I inject to be used as a service is not instantiated or I receive a NPE when CDI tries to create the converter:
Error Rendering View[/conferences.xhtml]
java.lang.NullPointerException
at com.sun.faces.cdi.CdiUtils.createConverter(CdiUtils.java:102)
at com.sun.faces.application.applicationimpl.InstanceFactory.createConverter(InstanceFactory.java:481)
at com.sun.faces.application.ApplicationImpl.createConverter(ApplicationImpl.java:510)
at javax.faces.application.ApplicationWrapper.createConverter(ApplicationWrapper.java:431)
at org.primefaces.renderkit.SelectRenderer.findImplicitConverter(SelectRenderer.java:202)
at org.primefaces.renderkit.SelectRenderer.getOptionAsString(SelectRenderer.java:181)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeOption(SelectCheckboxMenuRenderer.java:143)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeOption(SelectCheckboxMenuRenderer.java:137)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeInputs(SelectCheckboxMenuRenderer.java:128)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeMarkup(SelectCheckboxMenuRenderer.java:93)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeEnd(SelectCheckboxMenuRenderer.java:63)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1654)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:152)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:566)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1647)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:468)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:170)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.base/java.lang.Thread.run(Thread.java:834)
|#]
JSF1073: java.lang.NullPointerException caught during processing of RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=null|#]
No associated message
java.lang.NullPointerException
at com.sun.faces.cdi.CdiUtils.createConverter(CdiUtils.java:102)
at com.sun.faces.application.applicationimpl.InstanceFactory.createConverter(InstanceFactory.java:481)
at com.sun.faces.application.ApplicationImpl.createConverter(ApplicationImpl.java:510)
at javax.faces.application.ApplicationWrapper.createConverter(ApplicationWrapper.java:431)
at org.primefaces.renderkit.SelectRenderer.findImplicitConverter(SelectRenderer.java:202)
at org.primefaces.renderkit.SelectRenderer.getOptionAsString(SelectRenderer.java:181)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeOption(SelectCheckboxMenuRenderer.java:143)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeOption(SelectCheckboxMenuRenderer.java:137)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeInputs(SelectCheckboxMenuRenderer.java:128)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeMarkup(SelectCheckboxMenuRenderer.java:93)
at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.encodeEnd(SelectCheckboxMenuRenderer.java:63)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1654)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:152)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:566)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1647)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:468)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:170)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.base/java.lang.Thread.run(Thread.java:834)
Please find all my code below.
My facelet:
<?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:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<style type="text/css">
.ui-selectlistbox-listcontainer{
overflow: initial !important;
}
</style>
</h:head>
<h:body>
<h2>SelectManyMenu Example</h2>
<h:form>
<p:selectCheckboxMenu value="#{conferenceSelectionBean.selectedConferences}"
multiple="true"
filter="true" filterMatchMode="contains"
style="width:300px;">
<f:selectItems value="#{conferenceSelectionBean.allConferences}" var="conf"
itemLabel="#{conf.title}" itemValue="#{conf}"/>
</p:selectCheckboxMenu>
<p:commandButton value="Submit" action="#{conferenceSelectionBean.blabla}" update="selectedEmpPanel"/>
<h3>Selected Employees:</h3>
<h:panelGrid id="selectedEmpPanel" columns="1">
<ui:repeat value="#{conferenceSelectionBean.selectedConferences}" var="conf">
<h:outputText value="#{conf.id} (#{conf.title}) - #{conf.date}"/>
<br/>
</ui:repeat>
</h:panelGrid>
</h:form>
</h:body>
</html>
My Conference bean:
package com.logicbig.example;
public class Conference {
private String id;
private String title;
private String date;
public Conference(String id, String title, String date) {
this.id = id;
this.title = title;
this.date = date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
My converter
package com.logicbig.example;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;
#FacesConverter(forClass=Conference.class, managed=true)
public class ConferenceConverter implements Converter<Conference> {
#Inject
ConferenceService conferenceService;
public ConferenceConverter() { System.out.println("HOLA 2");
}
#Override
public Conference getAsObject(FacesContext fc, UIComponent comp, String value) {System.out.println("Get as object");
if(conferenceService == null){
System.out.println("SERVICE IS NULL");
}
return null;
}
#Override
public String getAsString(FacesContext fc, UIComponent comp, Conference value) { System.out.println("Get as String");
return ((Conference) value).getId();
}
}
In this case i receive the exception mentioned in the beginning.
Also, I've tried this:
package com.logicbig.example;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;
#FacesConverter(value = "confConverter")
public class ConferenceConverter implements Converter {
#Inject
ConferenceService conferenceService;
public ConferenceConverter() { System.out.println("HOLA 2");
}
#Override
public Object getAsObject(FacesContext fc, UIComponent comp, String value) {System.out.println("Get as object");
if(conferenceService == null){
System.out.println("SERVICE IS NULL");
}
return null;
}
#Override
public String getAsString(FacesContext fc, UIComponent comp, Object value) { System.out.println("Get as String");
return ((Conference) value).getId();
}
}
and entered the link in my xhtml:
<p:selectCheckboxMenu value="#{conferenceSelectionBean.selectedConferences}"
multiple="true" converter="confConverter"
filter="true" filterMatchMode="contains"
style="width:300px;">
<f:selectItems value="#{conferenceSelectionBean.allConferences}" var="conf"
itemLabel="#{conf.title}" itemValue="#{conf}"/>
</p:selectCheckboxMenu>
In this case the injected bean is always null.
My backing bean
package com.logicbig.example;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
#Named
#ViewScoped
public class ConferenceSelectionBean implements Serializable {
#Inject
ConferenceService conferenceService;
private List<Conference> selectedConferences = new ArrayList();
private List<Conference> allConferences;
#PostConstruct
private void init() {
allConferences = conferenceService.getAllConferences();
}
public void blabla(){
for(Conference c : selectedConferences){
System.out.println(c.getId() +" " + c.getTitle()+ " " + c.getDate());
}
}
public ConferenceService getConferenceService() {
return conferenceService;
}
public void setConferenceService(ConferenceService conferenceService) {
this.conferenceService = conferenceService;
}
public List<Conference> getSelectedConferences() {
return selectedConferences;
}
public void setSelectedConferences(List<Conference> selectedConferences) {
this.selectedConferences = selectedConferences;
}
public List<Conference> getAllConferences() {
return allConferences;
}
public void setAllConferences(List<Conference> allConferences) {
this.allConferences = allConferences;
}
}
My stateless session bean
package com.logicbig.example;
import java.util.Arrays;
import java.util.List;
import javax.ejb.Stateless;
#Stateless
public class ConferenceService {
private final List<Conference> conferences;
public ConferenceService() {
conferences = Arrays.asList(
new Conference("1", "Cool conference 1", "2010-05-10"),
new Conference("2", "Cool conference 2", "2010-05-10"),
new Conference("3", "Cool conference 3", "2010-05-10"),
new Conference("4", "Cool conference 4", "2010-05-10"),
new Conference("5", "Cool conference 5", "2010-05-10")
);
}
public List<Conference> getAllConferences() {
return conferences;
}
public Conference getConferenceById(String value) {
return conferences.stream()
.filter(e -> e.getId().equals(value))
.findAny().orElse(null);
}
}
and my configuration bean
package com.logicbig.example;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.annotation.FacesConfig;
#ApplicationScoped
#FacesConfig(version = FacesConfig.Version.JSF_2_3)
public class ConfigurationBean {
public ConfigurationBean() {
}
}
EDIT:
If I change the beginning of my converter to:
#FacesConverter(value = "confConverter", managed = true)
public class ConferenceConverter implements Converter<Object> {
the injection of the EJB service works as expected.
I need to have the following in my XHTML page
<f:converter converterId="confConverter"/>
So now it works as expected and I can retire the #MangedBean code.
As you already answered yourself, you need a converter for your non-primitive datatype.
For primitive datatypes or generic datatypes where the generic runtime information is lost there is regression / bug in mojarra which maybe is fixed in 2.3.10. https://github.com/eclipse-ee4j/mojarra/issues/4500.
Enums
converting enums without using omnifaces.genericEnumConverter
generics
Create concrete implementation class.
I had a class DataRange<T extends Comparable<T>> like DataRange<Date> and in p:calendar value="#{cc.attrs.range.start}" mojarra only retrieved Comparable<T> instead Date in conversion phase.
As a workaround i am using DataRangeDate to make sure runtime information of Date is not lost.
primefaces 6.19
This basically occurs when relying on default converters like in p:calendar or p:inputNumber.
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
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
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
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.