Null Pointer Exception while calling a bean method (PrimesFaces) - jsf-2

the problem is that when i use my command button i have a NPE and i dont why there is some code and a stacktrace of the exception i hope you will help because i have spend a day and still dont know why (primefaces 4.0 ) JSF 2.1.6
javax.faces.el.EvaluationException: javax.el.ELException: /test.xhtml at line 54 and column 113 action="#{messageBean.save}": java.lang.NullPointerException
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:96)
at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:100)
at javax.faces.component.UICommand.broadcast(UICommand.java:120)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:937)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:271)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1249)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:675)
at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:34)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.el.ELException: /test.xhtml at line 54 and column 113 action="#{messageBean.save}": java.lang.NullPointerException
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:95)
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:88)
... 29 more
Caused by: java.lang.NullPointerException
at ma.corporate.bean.MessageBean.save(MessageBean.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
... 30 more
My Page
<!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://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<p:panel header="Contactez Nous">
<p:growl id="message" showDetail="true"/>
<h:form id="form">
<p:panelGrid style="width:700px;" styleClass="contactcss"
columns="2">
<p:inputText value="#{messageBean.message.nomComplet}" style="width:600px" id="nom" required="true"
requiredMessage="Champs Obligatoire">
<p:watermark for="nom" value="Nom" />
</p:inputText>
<p:message for="nom" display="both" />
<p:inputText style="width:600px" value="#{messageBean.message.email}" id="email" required="true"
requiredMessage="Champ Obligatoire"
validatorMessage="Email Invalide">
<p:watermark for="email" value="Email" />
<f:validateRegex
pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
</p:inputText>
<p:message for="email" display="both" />
<p:inputText style="width:600px" value="#{messageBean.message.objet}" id="objet" required="true"
requiredMessage="Champ Obligatoire">
<p:watermark for="objet" value="Objet" />
</p:inputText>
<p:message for="objet" display="both" />
<p:inputMask mask="9999-999-999" style="width:600px" value="#{messageBean.message.telephone}" id="telephone">
<p:watermark for="telephone" value="téléphone" />
</p:inputMask>
<p:message for="telephone" display="both" />
<p:inputTextarea style="width:600px;height:200px" value="#{messageBean.message.textMessage}" id="message"
required="true" requiredMessage="Champ Obligatoire">
<p:watermark for="message" value="Message" />
</p:inputTextarea>
<p:message for="message" display="both" />
<p:commandButton update=":form :message" style="float:right;" action="#{messageBean.save}" value="Envoyer"></p:commandButton>
</p:panelGrid>
</h:form>
</p:panel>
</h:body>
</html>
My Bean
package ma.corporate.bean;
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import ma.corporate.facade.MessageFacade;
import ma.corporate.model.Message;
import ma.corporate.util.Email;
import ma.corporate.util.EmailSender;
import org.primefaces.context.RequestContext;
#ManagedBean(name = "messageBean")
#SessionScoped
public class MessageBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private MessageFacade messageFacade;
private List<Message> messages;
private Message message;
private Email email =new Email();
private String reponse;
public MessageBean() {
message = new Message();
}
public List<Message> getMessages() {
// messages = messageFacade.Lister();
messageFacade = new MessageFacade();
messages = messageFacade.Lister();
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public void save() {
System.out.println(message.getEmail());
System.out.println(message.getNomComplet());
System.out.println(message.getObjet());
System.out.println(message.getTelephone());
System.out.println(message.getTextMessage());
messageFacade.enregistrer(message);
}
public void Supprimer(Message message) {
messageFacade.supprimer(message);
messages = messageFacade.Lister();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Succès","Suppression Complète"));
}
public void init(Message message) {
this.message = message;
email.setDestinataire(message.getEmail());
email.setObjet(message.getObjet());
//email.setTexte("eljfdksjlfhdskjfsdhfkds");
RequestContext.getCurrentInstance().update(":form1:dlg3");
//System.out.println(this.message.getNomComplet());
}
public void sendEmail()
{
/*System.out.println("Send Email");
System.out.println(email.getObjet());
System.out.println(email.getTexte());
System.out.println(email.getDestinataire());*/
//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"En Cours","En Cours d'envoi"));
#SuppressWarnings("unused")
EmailSender sender = new EmailSender(email);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Succès","Message Envoyé"));
//System.out.println("après emailSender");
}
public Email getEmail() {
return email;
}
public void setEmail(Email email) {
this.email = email;
}
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
}

i have solved my problem it was
messageFacade = new MessageFacade(); must be in the constructor and not in a the function getMessages()

Related

Load value from database to <h:inputText> with <h:selectOneMenu> valueChangeEvent

I want to develop a JSF Page which lets user edit a Employee from database. I loaded list of all employees in h:selectOneMenu. and second thing i want that with valueChangeEvent employee detail should be loaded in corresponding h:inputText. but nothing happens with every valueChangeEvent. So, where is the problem in codes.
<?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://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<div id="hdr">
<h1>Vinweb Services</h1>
<hr/>
</div>
;
<div id="mnu" style="height: 50px; width: auto; background: skyblue;">
<h:form>
<h:commandLink value="Home" action="index"/>
<h:outputText value=" "/>
<h:commandLink value="Create" action="create"/>
<h:outputText value=" "/>
<h:commandLink value="View" action="view"/>
<h:outputText value=" "/>
<h:commandLink value="Edit" action="edit"/>
</h:form>
</div>
<div id="cnt">
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Select an Employee"/>
<h:selectOneMenu value="#{esb.empName}" onchange="submit()" valueChangeListener="#{esb.loadEmployeeDetail}">
<f:selectItems value="#{esb.employeeList}"/>
</h:selectOneMenu>
<h:outputLabel value="Employee Code"/>
<h:inputText value="#{esb.empCode}" required="true"/>
<h:outputLabel value="Employee Name"/>
<h:inputText value="#{esb.empName}" required="true"/>
<h:outputLabel value="Joining Date"/>
<h:inputText value="#{esb.joinDate}" required="true">
<f:convertDateTime pattern="MM/yy"/>
</h:inputText>
<h:outputLabel value="Salary"/>
<h:inputText value="#{esb.salary}" required="true"/>
<h:commandButton value="Update" action="#{esb.updateEmployeeDetail}"/>
</h:panelGrid>
</h:form>
</div>
</h:body>
</html>
Backing Bean:
package ems.bean;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import javax.annotation.Resource;
import javax.faces.event.ValueChangeEvent;
import javax.sql.DataSource;
#Named(value = "esb")
#SessionScoped
public class EmployeeServiceBean implements Serializable {
#Resource(name = "JPA4A")
private DataSource ds;
// Member Declaration
private String empCode;
private String empName;
private Date joinDate;
private long salary;
private ArrayList empList;
// Service Code Segment
// This method will publish all emloyees in table to selectOneMenu
public ArrayList getEmployeeList() throws SQLException{
empList = new ArrayList();
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
ResultSet rslt = stmt.executeQuery("SELECT empName FROM Employee");
while(rslt.next()){
empList.add(rslt.getString("empName"));
}
}
catch(SQLException se) {
throw new SQLException();
}
finally{
con.close();
}
return empList;
}
// This method should load selected empoyee's details in inputText fields
public void loadEmployeeDetail(ValueChangeEvent evt) throws SQLException{
String emp = evt.getNewValue().toString();
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
String qry = "SELECT * FROM Employee WHERE empName = '"+emp+"'";
ResultSet rslt = stmt.executeQuery(qry);
rslt.next();
this.empCode = rslt.getString("empCode");
this.empName = rslt.getString("empName");
this.joinDate = rslt.getDate("joinDate");
this.salary = rslt.getLong("salary");
}
catch(SQLException se) {
se.printStackTrace();
}
finally{
con.close();
}
}
public void updateEmployeeDetail() throws SQLException{
Connection con = ds.getConnection();
try{
Statement stmt = con.createStatement();
boolean rs = stmt.execute("UPDATE Employee SET empCode='"+empCode+"', empName='"+empName+"', joinDate='"+joinDate+"', salary="+salary);
}
catch(SQLException se) {
throw new SQLException();
}
finally{
con.close();
}
}
// Property Getter & Setter code segment
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}
The valueChangeListener is the wrong tool for the job.
You're here doing a onchange="submit()" which submits the entire form, including those required fields which in turn caused validation errors which in turn failed to reach your attention because you don't have any <h:message(s)> for them. If you have placed a <h:messages/> inside the form, or have paid more love and attention to server logs, you should have been notified of those required="true" validation errors.
You need <f:ajax listener>.
Replace
<h:selectOneMenu value="#{esb.empName}" onchange="submit()" valueChangeListener="#{esb.loadEmployeeDetail}">
<f:selectItems value="#{esb.employeeList}"/>
</h:selectOneMenu>
by
<h:selectOneMenu value="#{esb.empName}">
<f:selectItems value="#{esb.employeeList}"/>
<f:ajax listener="#{esb.loadEmployeeDetail}" render="#form" />
</h:selectOneMenu>
and replace
public void loadEmployeeDetail(ValueChangeEvent evt) throws SQLException{
String emp = evt.getNewValue().toString();
// ...
}
by
public void loadEmployeeDetail() throws SQLException{
String emp = empName; // You can also just use `empName` directly.
// ...
}
See also:
When to use valueChangeListener or f:ajax listener?

keep getting javax.faces.application.ViewExpiredException: viewId with jsf 2 [duplicate]

This question already has answers here:
javax.faces.application.ViewExpiredException: View could not be restored
(11 answers)
Closed 7 years ago.
Whatever I do I get javax.faces.application.ViewExpiredException: viewId. I know how to handle the exception (redirect to the main page again if I get the error), the issue is that any action I call from a commandButton is not executed.
Basically I have a simple view with a commandButton with an action.. I press it and I get the viewExpiredException or if I handle the error, I don't get the error messages but still my commandButton does not work.
I tried adding this:
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>client</param-value>
</context-param>
but it doesn't work. I don't know what is going on..
This is my view:
<?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:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
lang="es">
<div class="container">
<h:form id="principal">
<h1>Sistema de carga de publicaciones</h1>
<h:outputText value="Ingrese el año por el que desea buscar publicaciones" />
<h:inputText
id="year"
value="#{publicaciones.año}" />
<h:commandButton
style="display:block"
id="boton-codigo-facultad"
value="Buscar"
type="submit">
</h:commandButton>
<h:panelGroup id="output">
<h:outputText
style="display:block"
value="Total publicaciones en la DB:#{publicaciones.totalPublicacionesDB}" />
<h:outputText
style="display:block"
value="Publicaciones obtenidas desde el WS:" />
<h:outputText
style="display:block"
value="Publicaciones nuevas:" />
</h:panelGroup>
<h:commandButton
style="display:block"
id="insertar"
value="Cargar publicacion"
action="#{insert.insertPublicacionDB}">
</h:commandButton>
</h:form>
</div>
</html>
backing bean:
#ManagedBean(name="insert")
#ViewScoped
public class comparaDatosBean implements Serializable {
private static final long serialVersionUID = 1L;
Map<String, Object> parametros=new HashMap<String, Object>();
Map<String, Object> params2=new HashMap<String, Object>();
#PostConstruct
public void init(){
System.out.println("pase por aqui!!");
}
public void insertPublicacionDB() throws SQLException {
ApplicationContext applicationContext = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
ControllerPublicacion controlador= (ControllerPublicacion) applicationContext.getBean("controllerPublicaciones");
parametros.put("ut","234567876545555");
parametros.put("py", 2013);
params2.put("ut", "234567876545555");
params2.put("bp","asjñldfkjsñd");
params2.put("la", "Español");
params2.put("ti","Publicacion de prueba");
params2.put("py",2013);
params2.put("sn", "234wf");
params2.put("di", "asdfsf");
params2.put("j9", "");
params2.put("dt", "");
params2.put("ga", "");
params2.put("dt", "");
params2.put("so", "");
params2.put("fx", "");
params2.put("ep", "");
params2.put("issue", "");
params2.put("parte","");
params2.put("vl", "");
params2.put("rp", "");
params2.put("vinculada", null);
params2.put("ji", "");
params2.put("pd","");
params2.put("pg", "");
params2.put("pa","");
params2.put("ab","");
params2.put("pi", "");
params2.put("numero_articulo", null);
params2.put("tipo_carga_revista",null);
params2.put("id",null );
params2.put("su", "");
System.out.println(params2.get("la"));
if(controlador.existeEnDB(parametros)>0){
System.out.println("La publicacion ya existe en la Base de Datos");
} else {
controlador.insertPublicacion(params2);
System.out.println("la publicacion ha sido añadida");
}
}
public Map<String, Object> getParametros() {
return parametros;
}
public void setParametros(Map<String, Object> parametros) {
this.parametros = parametros;
}
public Map<String, Object> getParams2() {
return params2;
}
public void setParams2(Map<String, Object> params2) {
this.params2 = params2;
}
}
Error message:
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/test] threw exception [viewId:/main.jsf - No se pudo restablecer la vista /main.jsf.] with root cause
javax.faces.application.ViewExpiredException: viewId:/main.jsf - No se pudo restablecer la vista /main.jsf.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:212)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:110)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
What I need is to know why this is happening, not how to handle the exception.. I can't call any action from a commandButton because nothing happens.
I solved it with this:
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
In some places I saw it like this javax.faces.PARTIAL_STATE_SAVING but it did not work.

Primefaces cropper error when nothing selected on image

I have this following error when I try to crop an image using primefaces cropper, but nothing is selected on the image (the selection is not there ) :
Mar 17, 2013 5:10:46 PM com.sun.faces.lifecycle.ProcessValidationsPhase execute
WARNING: negative or zero width
java.awt.image.RasterFormatException: negative or zero width
at java.awt.image.Raster.<init>(Raster.java:1108)
at java.awt.image.WritableRaster.<init>(WritableRaster.java:129)
at sun.awt.image.SunWritableRaster.<init>(SunWritableRaster.java:129)
at sun.awt.image.ByteComponentRaster.<init>(ByteComponentRaster.java:154)
at sun.awt.image.ByteInterleavedRaster.<init>(ByteInterleavedRaster.java:191)
at sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1261)
at java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1173)
at org.primefaces.component.imagecropper.ImageCropperRenderer.getConvertedValue(ImageCropperRenderer.java:146)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:510)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1612)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIForm.visitTree(UIForm.java:362)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:378)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:253)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1171)
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:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.omnifaces.filter.FacesExceptionFilter.doFilter(FacesExceptionFilter.java:56)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.omnifaces.filter.GzipResponseFilter.doFilter(GzipResponseFilter.java:148)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.omnifaces.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:115)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:75)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Mar 17, 2013 5:10:46 PM com.sun.faces.renderkit.html_basic.OutcomeTargetRenderer getNavigationCase
WARNING: JSF1090: Navigation case not resolved for component j_idt74.
I really don't know how to solve this because it seems that the error doesn't occur in the process of cropping..
Can you please help me to solve this problem ? I really don't know what to do.
I am using Primefaces 3.5 and Myfaces 2.1.17.
Thank you very much.
UPDATE :
The cropper bean :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletContext;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.primefaces.model.CroppedImage;
import com.meinanliegen.backingbean.User;
import com.meinanliegen.handlers.filters.Configurations;
#ManagedBean
#ViewScoped
public class ImageCropperBean implements Serializable {
private static final long serialVersionUID = -7835902358418363820L;
private static final Logger LOGGER = Logger.getLogger(ImageCropperBean.class);
private CroppedImage croppedImage;
private String photoCropped;
// This only contains the relative path to the temp image : /temp/croppedImage
private String relativeImagePhotoCropped;
private String originalUploadedPhotoFileName;
#ManagedProperty(value = "#{user}")
private User user;
public CroppedImage getCroppedImage() {
return croppedImage;
}
public void setCroppedImage(CroppedImage croppedImage) {
this.croppedImage = croppedImage;
}
public String getPhotoCropped() {
return photoCropped;
}
public void setPhotoCropped(String photoCropped) {
this.photoCropped = photoCropped;
}
public String getRelativeImagePhotoCropped() {
return relativeImagePhotoCropped;
}
public void setRelativeImagePhotoCropped(String relativeImagePhotoCropped) {
this.relativeImagePhotoCropped = relativeImagePhotoCropped;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String crop() {
if (croppedImage == null) {
LOGGER.error("The cropped image is null");
}
else {
manageTheCrop();
}
return null;
}
private void manageTheCrop() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
String originalFilePhotoName = croppedImage.getOriginalFilename();
String tempLocationForCroppedFile = servletContext.getRealPath(Configurations.UPLOAD_TEMP_FILE_PATH);
String prefix = FilenameUtils.getBaseName(originalFilePhotoName);
String suffix = FilenameUtils.getExtension(originalFilePhotoName);
// First time we need to save the original photo name
if (originalUploadedPhotoFileName == null) {
originalUploadedPhotoFileName = prefix + "." + suffix;
}
try {
// We will keep the same name for cropped photo, until the user decides
File photoCroppedFile = File.createTempFile(prefix, "." + suffix, new File(tempLocationForCroppedFile));
photoCropped = photoCroppedFile.getPath();
cropImageAddContentTo(photoCropped);
String prefixCroppedPhoto = FilenameUtils.getBaseName(photoCropped);
String suffixCroppedPhoto = FilenameUtils.getExtension(photoCropped);
String photoCroppedFileName = prefixCroppedPhoto + "." + suffixCroppedPhoto;
relativeImagePhotoCropped = Configurations.UPLOAD_TEMP_FILE_PATH + photoCroppedFileName;
}
catch (IOException ex) {
LOGGER.error(ex);
BeanUtils.addMessage(FacesMessage.SEVERITY_ERROR, "Bitte versuchen Sie es noch einmal.",
"Fehler beim Zuschneiden Ihres Fotos");
}
}
public void saveCroppedImageAsPrimaryUserImage() {
if (photoCropped != null) {
String profilePhotoChosenFilePrefix = String.format("%s_%s_%s", user.getFirstName(), user.getLastName(),
originalUploadedPhotoFileName);
try {
// We will save the last cropped image as profile
File finalPhotoLocation = new File(Configurations.UPLOAD_FILE_PATH, profilePhotoChosenFilePrefix);
OutputStream output = null;
output = new FileOutputStream(finalPhotoLocation);
IOUtils.copy(new FileInputStream(photoCropped), output);
user.setTempProfilePictureSrc(relativeImagePhotoCropped);
user.setProfilePictureSrc("../uploads/" + finalPhotoLocation.getName());
}
catch (IOException ex) {
LOGGER.error(ex);
BeanUtils.addMessage(FacesMessage.SEVERITY_ERROR, "Bitte versuchen Sie es noch einmal.", "Fehlermeldung");
}
}
}
public void cropImageAddContentTo(String croppedImagePath) {
try {
cropImage(croppedImagePath);
}
catch (IOException ex) {
LOGGER.error(ex);
BeanUtils.addMessage(FacesMessage.SEVERITY_ERROR, "Fehlermeldung",
"Es ist eiin Fehler aufgetreten. Bitte versuchen Sie es noch einmal.");
}
}
public void cropImage(String imageFileName) throws IOException {
FileImageOutputStream imageFileOutput = null;
imageFileOutput = new FileImageOutputStream(new File(imageFileName));
imageFileOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
imageFileOutput.close();
}
}
and the JSF part :
<ui:composition 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">
<p:row>
<p:column style="height:120px; width 120px;">
<p:panelGrid columns="2">
<p:row>
<p:column>
<div class="photo">
<p:graphicImage id="standardUploadedImage" value="#{user.tempProfilePictureSrc}" />
</div>
</p:column>
</p:row>
<p:row>
<h:panelGroup id="adjustImage">
<p:column style="width:150px">
<p:panelGrid>
<p:row>
<p:column>
<h:outputText value="Bild innerhalb des Rahmens positionieren"
rendered="#{uploadPhotoHandler.userImageUploaded == true}" />
</p:column>
</p:row>
<p:row>
<p:column>
<p:commandButton value="Bild anpassen" oncomplete="cropWidget.show()"
update=":growl cropDialog" immediate="true"
rendered="#{uploadPhotoHandler.userImageUploaded == true}"
styleClass="css3button" />
</p:column>
</p:row>
</p:panelGrid>
</p:column>
</h:panelGroup>
</p:row>
</p:panelGrid>
</p:column>
</p:row>
<p:row>
<p:column>
<p:fileUpload fileUploadListener="#{uploadPhotoHandler.handleFileUpload}" mode="advanced"
label="Portraitfoto hochladen" sizeLimit="5242880" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="Datei darf maximal 5 MB groß sein"
invalidFileMessage="Bitte prüfen Sie das Format. Es können nur jpg, gif, png Dateien verwendet werden."
update=":growl standardUploadedImage uploadedImage imageCropper adjustImage" auto="true"
required="false" />
</p:column>
</p:row>
<p:row>
<p:column>
<p:confirmDialog id="cropDialog" header="Bild anpassen" severity="alert" showEffect="fade" closeOnEscape="true"
closable="true" hideEffect="fade" widgetVar="cropWidget">
<p:panelGrid>
<p:row>
<p:column colspan="2">
<p:panelGrid columns="3" style="height:50px">
<p:row>
<p:column>
<p:commandButton id="cancel" value="Löschen" onclick="cropWidget.hide()"
type="button"
update=":growl imageCropper uploadedImage standardUploadedImage"
immediate="true" styleClass="css3button" />
</p:column>
</p:row>
<p:row>
<p:column>
<h:panelGrid id="cropBtnPanel">
<p:commandButton id="crop" value="Zuschneiden"
action="#{imageCropperBean.crop}"
update=":growl imageCropper uploadedImage standardUploadedImage cropFinished crop cropBtnPanel ApplyBtnPanel"
process="crop imageCropper" styleClass="css3button"
rendered="#{imageCropperBean.showCrop}" />
</h:panelGrid>
</p:column>
</p:row>
<p:row>
<p:column>
<h:panelGrid id="ApplyBtnPanel">
<p:commandButton id="cropFinished" value="Übernehmen"
actionListener="#{imageCropperBean.saveCroppedImageAsPrimaryUserImage}"
oncomplete="cropWidget.hide()"
update=":growl imageCropper uploadedImage standardUploadedImage crop cropFinished cropBtnPanel ApplyBtnPanel"
process="cropFinished imageCropper" styleClass="css3button"
rendered="#{imageCropperBean.showApply}" />
</h:panelGrid>
</p:column>
</p:row>
</p:panelGrid>
</p:column>
</p:row>
<p:row>
<p:column headerText="Original">
<div class="photoToBeCropped">
<p:imageCropper id="imageCropper"
value="#{imageCropperBean.croppedImage}"
image="#{user.tempProfilePictureSrc}"
initialCoords="225,75,300,125"
aspectRatio="1.0"
rendered="#{uploadPhotoHandler.userImageUploaded == true}"
minSize="170"
required="true" />
</div>
</p:column>
<p:column headerText="Cropped">
<div class="photoToBeCropped">
<p:graphicImage id="uploadedImage" value="#{imageCropperBean.relativeImagePhotoCropped}" />
</div>
</p:column>
</p:row>
</p:panelGrid>
</p:confirmDialog>
</p:column>
</p:row>
It is worth to be mentioned that this entire crop module is embedded in one wizard primefaces step.
I can reproduce it on their own showcase. When I deselect the image and click Crop, then I see the unhandled exception in the ajax response:
(it'd been nice if they installed a decent ajax exception handler, so that this was immediately visible to the enduser)
Well, this is really a bug in their own code. This is 4 days ago already been reported as issue 5349 which is currently unscheduled.
If you really can't wait for them to fix it, then your best is to override the renderer to skip the job in getConvertedValue():
public class MyImageCropperRenderer extends ImageCropperRenderer {
#Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
if (submittedValue == null || ((String) submittedValue).endsWith("_0_0")) {
return null;
}
return super.getConvertedValue(context, component, submittedValue);
}
}
The submitted value is in the format x_y_w_h wherein the _w_h would be _0_0 when nothing is selected. In that case, the above custom renderer will thus return immediately null instead of continuing the conversion job which would throw that exception.
To get this renderer to run, register it as follows in faces-config.xml wherein the <renderer-class> is the FQN of the custom renderer:
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.ImageCropperRenderer</renderer-type>
<renderer-class>com.example.MyImageCropperRenderer</renderer-class>
</renderer>
</render-kit>
I used the solution posted for BalusC. But sporadically I get the value "_2_0" or something like that. In these cases, the error happens again. Then I resolved so:
#Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
if (submittedValue != null ){
String[] submittedValueArray = ((String) submittedValue).split("_");
if (!"0".equals(submittedValueArray[2]) && !"0".equals(submittedValueArray[3])) {
return super.getConvertedValue(context, component, submittedValue);
}
}
return null;
}
catch (RasterFormatException e) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "This crop size is not supported", null);
throw new ErrorImageSizeException(message); }
Creates ErrorImageSizeException extending ConverterException with constructor
public ErrorImageSizeException(FacesMessage mensagem) {
super(mensagem);
}
I get java.lang.NumberFormatException: For input string: "NaN" when I pressed the button before changing the crop area.
<h:form id="editUserPhotoForm" >
<p:messages showDetail="true" autoUpdate="false" closable="true" />
<h:panelGrid columns="2" rendered="#{not empty adminView.editUser}">
<p:imageCropper value="#{adminView.croppedImage}" image="#{adminView.userImagePath}" initialCoords="0,0,200,260" aspectRatio="0.77" minSize="200,260"/>
<p:graphicImage value="#{adminView.imageUser}" width="200" cache="false" />
</h:panelGrid>
<p:commandButton value="crop" action="#{adminView.crop}" ignoreAutoUpdate="true" process="#form" update="#form" icon="ui-icon-scissors"/>
</h:form>
I used the solution posted by #BalusC but added the condition:
if (submittedValue == null || ((String) submittedValue).endsWith("_0_0") || ((String)submittedValue).contains("NaN"))
Following the solution posted by #BalusC, I have implemented my own and I save the whole picture when there is no selection:
#Override
public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
if (submittedValue != null ){
String[] submittedValueArray = ((String) submittedValue).split("_");
if (!"0".equals(submittedValueArray[2]) && !"0".equals(submittedValueArray[3])) {
return super.getConvertedValue(context, component, submittedValue);
}
}
try {
return super.getConvertedValue(context, component, buildDefaultSubmittedValue(context, component));
} catch (IOException e) {
throw new ConverterException("Error cropping the whole image");
}
}
private String buildDefaultSubmittedValue(FacesContext context, UIComponent component) throws IOException {
ImageCropper cropper = (ImageCropper) component;
//remove query string
String imagePath = cropper.getImage();
int queryStringIndex = imagePath.indexOf("?");
if(queryStringIndex != -1 ) {
imagePath = imagePath.substring(0, queryStringIndex);
}
BufferedImage outputImage = getSourceImage(context, imagePath);
return "0_0_" + outputImage.getWidth() + "_" + outputImage.getHeight();
}
private BufferedImage getSourceImage(FacesContext context, String imagePath) throws IOException {
BufferedImage outputImage = null;
boolean isExternal = imagePath.startsWith("http");
if(isExternal) {
URL url = new URL(imagePath);
outputImage = ImageIO.read(url);
}
else {
ExternalContext externalContext = context.getExternalContext();
outputImage = ImageIO.read(new File(externalContext.getRealPath("") + imagePath));
}
return outputImage;
}

setPropertyActionListener not working properly [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
primefaces selectOneMenu doesn’t working when it should
my setPropertyActionListener is not setting the corresponding bean property. I need to get the select public after i click the corresponding delete button (cbViewExcluir) which shows a confirm dialog before delete. Below is my xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
template="./../../resources/templates/baseTemplate.xhtml">
<ui:define name="content">
<f:view id="vRoot">
<p:fieldset legend="Manage publics">
<h:form id="frmPublics">
<!-- Global messages -->
<p:growl id="gMessages" sticky="false" globalOnly="true" />
<!-- Public list on dataTable -->
<p:dataTable id="dtPublics"
value="#{publicBean.lstPublics}"
paginator="true" rows="5"
rowsPerPageTemplate="5,10"
paginatorPosition="bottom"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
var="actual">
<f:facet name="header">
<p:commandButton id="cbViewNew" value="New" type="button" onclick="dlgNew.show();" />
</f:facet>
<!-- Colunas de edição e exclusão -->
<p:column>
<f:facet name="header">
<h:outputLabel value="Edit"/>
</f:facet>
<p:commandButton id="cbViewEdit"
image="ui-icon-pencil"
title="Edit"
update=":frmEdit:pEditPublic"
oncomplete="dlgEdit.show();">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
<h:outputLabel value="Delete"/>
</f:facet>
<p:commandButton id="cbViewDelete" onclick="dlgDelete.show();"
icon="ui-icon-close" title="Delete">
<f:setPropertyActionListener value="#{actual}" target="#{publicBean.selectedPublic}" />
</p:commandButton>
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
<h:outputLabel id="olViewPublicName" value="#{actual.publicName}"/>
</p:column>
<p:column>
<f:facet name="header">
Public Type
</f:facet>
<h:outputLabel id="olViewPublicType" value="#{actual.publicType}"/>
</p:column>
</p:dataTable>
</h:form>
<!-- New dialog -->
<p:dialog id="dlgNewPublic" widgetVar="dlgNew" modal="true" header="New Public"
resizable="false">
<h:form id="frmNew">
<p:panel id="pNewPublico">
<p:messages id="mNewMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olNewPublicName" value="Name:" for="itNewPublicName"/>
<p:inputText id="itNewPublicName" value="#{publicBean.name}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olNewPublicType" for="somNewPublicType" value="Public type:"/>
<p:selectOneMenu id="somNewPublicType" value="#{publicBean.publicType}" effect="fade"
converter="#{publicBean.converter}"
required="true" requiredMessage="Enter the public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}" var="actual" itemLabel="#{actual.label}" itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgNew.hide()"/>
<p:commandButton id="cbSaveNew" value="Save"
actionListener="#{publicBean.save}"
oncomplete="handleSave(xhr, status, args);"
update=":frmPublics:dtPublics :frmNew :frmPublics:gMessages"
ajax="true"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
<!-- Delete dialog -->
<p:confirmDialog id="dialogDelete" message="Are you sure?"
header="Delete public" severity="alert"
widgetVar="dlgDelete">
<h:form id="frmDelete">
<p:commandButton id="cbDeleteCancel" value="Cancel" onclick="dlgDelete.hide()" type="button" />
<p:commandButton id="cbDeleteContinue" value="Continue"
update=":frmPublics:dtPublics :frmPublics:gMessages"
oncomplete="dlgDelete.hide()"
actionListener="#{publicBean.delete}"/>
</h:form>
</p:confirmDialog>
<!-- Edit dialog -->
<p:dialog id="dialogEdit" widgetVar="dlgEdit" header="Edit public"
resizable="false" modal="true">
<h:form id="frmEdit">
<p:panel id="pEditPublic">
<p:messages id="mEditMessages" redisplay="false" />
<p:panelGrid columns="2">
<p:outputLabel id="olEditPublicName" value="Name:" for="itEditPublicName"/>
<p:inputText id="itEditPublicName" value="#{publicBean.selectedPublic.publicName}" required="true"
requiredMessage="Enter the public name."/>
<p:outputLabel id="olEditPublicType" for="somEditPublicType" value="Public type:"/>
<p:selectOneMenu id="somEditPublicType"
value="#{publicBean.selectedPublic.publicType}"
effect="fade"
converter="#{publicBean.converter}"
required="true"
requiredMessage="Select a public type."
>
<f:selectItem itemLabel="-- Select --" itemValue=""/>
<f:selectItems value="#{publicBean.publicTypes}"
var="actual"
itemLabel="#{actual.label}"
itemValue="#{actual}"></f:selectItems>
</p:selectOneMenu>
<p:commandButton value="Cancel" immediate="true" onclick="dlgEdit.hide()"/>
<p:commandButton id="cbEditSave" value="Save"
actionListener="#{publicBean.alter}"
oncomplete="dlgEdit.hide();"
update=":frmPublics :frmEdit"/>
</p:panelGrid>
</p:panel>
</h:form>
</p:dialog>
</p:fieldset>
</f:view>
<!-- Javascript callbacks -->
<script type="text/javascript">
function handleSaved(xhr, status, args){
if(args.saved){
dlgNew.hide();
}
}
function handleEdited(xhr, status, args){
if(args.edited){
dlgEdit.hide();
}
}
</script>
</ui:define>
And my bean is as follows:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.siseventos.managed;
import br.siseventos.dao.da.PublicoDAO;
import br.siseventos.dao.da.TipoPublicoDAO;
import br.siseventos.model.TbPublico;
import br.siseventos.model.TdTipoPublico;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
#ManagedBean(name = "publicoBean")
#SessionScoped
public class PublicoBean {
// Campos
private TipoPublicoDAO daoTipoPublico = null;
private PublicoDAO daoPublico = null;
private String nome;
private List<SelectItem> lstMenuTipoPublico = new ArrayList<SelectItem>();
private TdTipoPublico tipoPublicoSelecionado = null;
private List<TbPublico> lstDataTablePublico = null;
private TbPublico publicoSelecionado;
// Util
private int maximoLinhasTablePublico = 5;
private boolean mostrarMsg = false;
// Construtor
public PublicoBean() {
// Inicializando as daos
daoPublico = new PublicoDAO();
daoTipoPublico = new TipoPublicoDAO();
// Carregando o datatable de publicos
lstDataTablePublico = daoPublico.consultarTodos();
// Carregando o menu de tipos de público
List<TdTipoPublico> l = getDaoTipoPublico().consultarTodos();
Iterator<TdTipoPublico> i = l.iterator();
while (i.hasNext()) {
TdTipoPublico atual = (TdTipoPublico) i.next();
lstMenuTipoPublico.add(new SelectItem(atual, atual.getNmeTipoPublico()));
}
}
public TipoPublicoDAO getDaoTipoPublico() {
return daoTipoPublico;
}
public void setDaoTipoPublico(TipoPublicoDAO daoTipoPublico) {
this.daoTipoPublico = daoTipoPublico;
}
public PublicoDAO getDaoPublico() {
return daoPublico;
}
public void setDaoPublico(PublicoDAO daoPublico) {
this.daoPublico = daoPublico;
}
// Getters e Setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<SelectItem> getLstMenuTipoPublico() {
return lstMenuTipoPublico;
}
public void setLstMenuTipoPublico(List<SelectItem> lstMenuTipoPublico) {
this.lstMenuTipoPublico = lstMenuTipoPublico;
}
public TdTipoPublico getTipoPublicoSelecionado() {
return tipoPublicoSelecionado;
}
public void setTipoPublicoSelecionado(TdTipoPublico tipoPublicoSelecionado) {
this.tipoPublicoSelecionado = tipoPublicoSelecionado;
}
public List<TbPublico> getLstDataTablePublico() {
return lstDataTablePublico;
}
public void setLstDataTablePublico(List<TbPublico> lstDataTablePublico) {
this.lstDataTablePublico = lstDataTablePublico;
}
public int getMaximoLinhasTablePublico() {
return maximoLinhasTablePublico;
}
public void setMaximoLinhasTablePublico(int maximoLinhasTablePublico) {
this.maximoLinhasTablePublico = maximoLinhasTablePublico;
}
public boolean isMostrarMsg() {
return mostrarMsg;
}
public void setMostrarMsg(boolean mostrarMsg) {
this.mostrarMsg = mostrarMsg;
}
public TbPublico getPublicoSelecionado() {
return publicoSelecionado;
}
public void setPublicoSelecionado(TbPublico publicoSelecionado) {
this.publicoSelecionado = publicoSelecionado;
}
// Actions e listeners
public void cadastrarPublico(ActionEvent ex) {
FacesContext contexto = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage();
try {
TbPublico p = new TbPublico();
p.setNmePublico(getNome());
p.setTdTipoPublico(getTipoPublicoSelecionado());
getDaoPublico().incluir(p);
// Carregar a lista de publicos novamente
lstDataTablePublico = getDaoPublico().consultarTodos();
// Mostrando msg de sucesso!
msg.setSummary("Público cadastrado com sucesso!");
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
// Invocando script no cliente
RequestContext rc = RequestContext.getCurrentInstance();
rc.addCallbackParam("salvo", true);
} catch (Exception e) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}
}
public void excluirPublico(ActionEvent e) {
FacesMessage msg = new FacesMessage();
FacesContext contexto = FacesContext.getCurrentInstance();
// Mostrando msg de sucesso!
msg.setSummary(publicoSelecionado.getNmePublico());
msg.setSeverity(FacesMessage.SEVERITY_INFO);
contexto.addMessage(null, msg);
/*try {
// Excluindo o publico selecionado
daoPublico.excluir(getPublicoSelecionado().getIdtPublico());
} catch (Exception ex) {
msg.setSummary("Erro ao cadastrar público!");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
contexto.addMessage(null, msg);
}*/
}
public void alterarPublico() {
FacesMessage msg = new FacesMessage("Publico alterado!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
// Converters
public Converter getConversor() {
return new Converter() {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Transformar string em objeto
TdTipoPublico r = null;
try {
r = getDaoTipoPublico().consultarPorIdt(Integer.parseInt(value));
} catch (NumberFormatException e) {
}
return r;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Transformar objeto em string
String r = null;
if (value instanceof TdTipoPublico) {
r = ((TdTipoPublico) value).getIdtTipoPublico().toString();
}
return r;
}
};
}
}
There is something i'm doing wrong?
its because of the attribute type="button" which is not firing the actionlistener.
when you declare this attribute (type="button") its not a p:commandButton anymore.
type="button" is push button purposes, it does not do any action or submit the form
try to remove type="button" attribute. it'd fire the actionlistener.
<p:commandButton id="cbViewExcluir"
image="ui-icon-circle-close"
onclick="dlgExcluir.show()"
title="Excluir"
update=":frmExcluir">
<!-- This is not working properly -->
<f:setPropertyActionListener value="#{atual}" target="# {publicoBean.publicoSelecionado}" />
</p:commandButton>
lemme know if this helps :)

How to create JSF Table with links after post

I like to display a form where the end-user can enter details and the post will result in the table which contain a filtered list based on the user input. This table should have link for each row to select that specific row and return a detailed view.
accounts-list.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"
xmlns:utils="http://java.sun.com/jsf/composite/snippets" template="/WEB-INF/templates/default.xhtml">
<ui:define name="title"></ui:define>
<ui:define name="content">
<h:form id="search">
<fieldset>
<legend>Search for account</legend>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="id" value="Account ID" /></span>
<span class="account_list_item">
<h:inputText id="id" value="#{accountsCrudBean.searchId}" styleClass="field_inputtext_account" />
</span>
</div>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="name" value="Account Name" /></span>
<span class="account_list_item">
<h:inputText id="name" value="#{accountsCrudBean.searchName}" styleClass="field_inputtext_account" />
</span>
</div>
<h:commandButton id="search" value="Display" action="#{accountsCrudBean.actionSearch}" />
</fieldset>
</h:form>
<h:form id="view" rendered="#{accountsCrudBean.dataItemId.value != null}">
<h:dataTable var="dataItem" binding="#{accountsCrudBean.dataTable}" value="#{accountsCrudBean.list}" id="accountListTable"
columnClasses="accountsCrudBeanTable_row_date, transactionsListTable_row_amount, transactionsListTable_row_balance, transactionsListTable_row_description" styleClass="transactionsListTable">
<h:column headerClass="transactionsListTable_header_amount">
<f:facet name="header">Id</f:facet>
<h:commandLink value="#{dataItem.id}" action="#{accountsCrudBean.editDataItem}" />
</h:column>
<h:column headerClass="transactionsListTable_header_balance">
<f:facet name="header">Name</f:facet>#{dataItem.name}</h:column>
<h:column headerClass="transactionsListTable_header_description">
<f:facet name="header">Total Balance</f:facet>#{dataItem.totalBalance}</h:column>
</h:dataTable>
<h:inputHidden binding="#{accountsCrudBean.dataItemId}" />
</h:form>
</ui:define>
</ui:composition>
accounts-edit.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:utils="http://java.sun.com/jsf/composite/snippets"
template="/WEB-INF/templates/default.xhtml">
<ui:define name="title"></ui:define>
<ui:define name="content">
<h:form id="edit" rendered="#{accountsCrudBean.dataItemId.value != null}">
<fieldset>
<legend>View account 1</legend>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="id" value="Account ID" /></span>
<span class="account_list_item">
#{accountsCrudBean.dataItemId.value}
</span>
</div>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="name" value="Account Name" /></span>
<span class="account_list_item">
<h:inputText readonly="true" id="name" value="#{accountsCrudBean.dataItem.name}" styleClass="field_inputtext_account" />
</span>
</div>
<div class="account_list_section">
<span class="account_section_title"><h:outputLabel for="accountOwners" value="Owners" /></span>
<span class="account_list_item">
<h:selectOneListbox readonly="true" id="accountOwners" value="#{accountsCrudBean.selectedOwner}">
<f:selectItems value="#{accountsCrudBean.accountOwners}" />
</h:selectOneListbox>
</span>
</div>
<h:inputHidden binding="#{accountsCrudBean.dataItemId}" />
<h:commandButton id="edit" value="Save" action="#{accountsCrudBean.actionSearch}" />
</fieldset>
</h:form>
<h:outputText value="No item selected." rendered="#{accountsCrudBean.dataItemId.value == null}" />
</ui:define>
</ui:composition>
AccountsCrudBean.java:
#ManagedBean
#SessionScoped
public class AccountsCrudBean extends JsfManagedBeanBase {
private static final long serialVersionUID = 1L;
#EJB
AccountsManagerLocal accountsManager;
private Long searchId;
private String searchName;
private String selectedOwner;
private Account dataItem;
private HtmlDataTable dataTable;
private HtmlInputHidden dataItemId = new HtmlInputHidden();
private List<Account> accountList = null;
public AccountsCrudBean() {
}
public Long getSearchId() {
return searchId;
}
public void setSearchId(Long searchId) {
this.searchId = searchId;
}
public String getSearchName() {
return searchName;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public HtmlInputHidden getDataItemId() {
return dataItemId;
}
public Account getDataItem() {
return dataItem;
}
public void setDataItem(Account dataItem) {
this.dataItem = dataItem;
}
public HtmlDataTable getDataTable() {
return dataTable;
}
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
public void setDataItemId(HtmlInputHidden dataItemId) {
this.dataItemId = dataItemId;
}
public String getSelectedOwner() {
return selectedOwner;
}
public void setSelectedOwner(String selectedOwner) {
this.selectedOwner = selectedOwner;
}
public List<Account> getList() {
if (accountList == null) {
actionLoad();
}
return accountList;
}
private void actionLoad() {
if (searchId != null) {
Account account = accountsManager.getAccount(searchId);
accountList = Arrays.asList(account);
} else if (searchName != null) {
accountList = accountsManager.findAccountByName(searchName);
} else if (dataItemId != null && dataItemId.getValue() != null) {
Account account = accountsManager.getAccount(Long
.valueOf(dataItemId.getValue().toString()));
accountList = Arrays.asList(account);
} else
accountList = new ArrayList<Account>();
};
public void actionSearch() {
dataItem = (Account) dataTable.getRowData();
dataItemId.setValue(dataItem.getId());
actionLoad();
}
public Map<String, User> getAccountOwners() {
List<User> owners = accountsManager.getUsers(dataItem);
LinkedHashMap<String, User> map = new LinkedHashMap<String, User>();
for (User user : owners) {
map.put(user.getFirstName() + " " + user.getLastName(), user);
}
return map;
}
public String editDataItem() {
dataItem = (Account) dataTable.getRowData();
dataItemId.setValue(dataItem.getId());
return "accounts-edit";
}
}
This works on JBoss 7.1 but on 6 it's failed with:
javax.faces.el.EvaluationException: javax.el.ELException: /s/accounts-list.xhtml at line 22 and column 94 action="#{accountsCrudBean.actionSearch}": java.lang.IllegalArgumentException: row is unavailable
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:96)
at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:100)
at javax.faces.component.UICommand.broadcast(UICommand.java:120)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:889)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:238)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1201)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:627)
at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:34)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:324)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242)
at org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:67)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:274)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242)
at com.demo.server.ejb.security.AuthenticationFilter.doFilter(AuthenticationFilter.java:35)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:274)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:181)
at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.event(CatalinaContext.java:285)
at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.invoke(CatalinaContext.java:261)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:88)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:100)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.jboss.web.tomcat.service.request.ActiveRequestResponseCacheValve.invoke(ActiveRequestResponseCacheValve.java:53)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:654)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:951)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.el.ELException: /s/accounts-list.xhtml at line 22 and column 94 action="#{accountsCrudBean.actionSearch}": java.lang.IllegalArgumentException: row is unavailable
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:95)
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:88)
... 35 more
Caused by: java.lang.IllegalArgumentException: row is unavailable
at javax.faces.model.ListDataModel.getRowData(ListDataModel.java:69)
at javax.faces.component.UIData.getRowData(UIData.java:462)
at com.demo.server.web.AccountsCrudBean.actionSearch(AccountsCrudBean.java:130)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.el.parser.AstValue.invoke(AstValue.java:196)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:43)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:56)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:43)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:56)
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
... 36 more
This is based on http://balusc.blogspot.com/2006/06/using-datatables.html#AddBackingBeanActionToEveryRow
On the post the author use #RequestScoped bean but if I try to change the bean to be #RequestScoped the filter does not work, and i don't get the table with the links.
Thanks.
Your bean is in the session scope. You don't need the <h:inputHidden binding="..."> at all. Remove it and all related code. Your backing bean action methods should look like this:
public void actionSearch() {
actionLoad();
}
public String editDataItem() {
dataItem = (Account) dataTable.getRowData();
return "accounts-edit";
}
Also replace #{accountsCrudBean.dataItemId} in your view by #{accountsCrudBean.dataItem.id}.
Unrelated to the concrete problem, please note that the article is nearly 6 years old and based on JSF 1.x. These days, with JSF 2.x and EL 2.2, there are other and easier ways to get the selected row. My favourite is
<h:commandLink value="#{dataItem.id}" action="#{accountsCrudBean.editDataItem(dataItem)}" />
with
public String editDataItem(Account dataItem) {
this.dataItem = dataItem;
return "accounts-edit";
}

Resources