Issue in Object creation concurrently in java web - maven

I have developed maven web project using spring primefaces and run on jboss 5.0 server.
The Application is cloud based and multiple users can access concurrently.
My issue is when create objects concurrently sometimes refer previous object.this is ok with sequentially. But, when called same method in parallel it run as ambiguous way. Is it issue in primefaces?
depositController method:
#ManagedBean(name = "depositController")
#ViewScoped
public class DepositController {
public void depositAcc(ActionEvent actionEvent) {
try {
validate = true;
TrxnObj tempTrxnObj = trxnObj;
if (requiredFieldValidate()) {
this.mobileNoVerify();
if (validate) {
this.amountValidate();
}
} else {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Please Enter the Required Fields");
context.addMessage("ad", message);
return;
}
if (!validate) {
return;
}
if (isRCP) {
if (null == userManager) {
userManager = (UserManager) SpringUtil.getApplicationContext().getBean("userManager");
}
merchant = userManager.getMerchantDetails(AppConstants.TRXN_CODE_WALLET_CASH_IN_WEB, merchantID);
if (null == commonManager) {
commonManager = (CommonManager) SpringUtil.getApplicationContext().getBean("commonManager");
}
//insert txn id
WSRequest request = new WSRequest();
request.setMerchantId(merchantID);
request.setMerchantOutletCode(merchantOutletCode);
request.setCustomerMobileNumber(tempTrxnObj.getMobileNo());
request.setMobileNumber(merchant.getMobileNumber());
request.setPinCode(merchant.getPinCode());
request.setTransactionAmount(tempTrxnObj.getAmount().doubleValue());
if(branchCode!=null && !branchCode.equals("")){
request.setUserName(userId+"-"+branchCode);
}else{
request.setUserName(userId);
}
if (tempTrxnObj.getNote() == null || tempTrxnObj.getNote().isEmpty()) {
request.setNote("Cash In at " + merchantID + " for " + tempTrxnObj.getMobileNo());
} else {
request.setNote(tempTrxnObj.getNote());
}
request.setMerchantTransactionId(getRCPTransactionRef());
CashInRequest cashInRequest = new CashInRequest();
cashInRequest.setWsRequest(request);
CashInResponse cashInResponse = commonManager.callCashInService(cashInRequest);
if (cashInResponse.getWsResponse().getResponseCode() == AppConstants.WS_TRXN_WEB_RES_SUCCESS) {
FacesContext.getCurrentInstance().addMessage("ad", new FacesMessage("Transaction Success: " + cashInResponse.getWsResponse().getResponse()));
receiptObj.setValues(this.trxnObj, locationShortCode, customerName);
recieptPrintEnabled = true;
receiptObj.setRefNumber(cashInResponse.getWsResponse().getReference());
receiptObj.setCusName(userControlObj.getMwtUserWalletDetails().getName());
receiptObj.setUtilityType("CASH IN");
receiptObj.setAccountNumber(userControlObj.getMwtUserWallet().getMobileNo());
receiptObj.setNote("Accepted payment for CASH IN.Thank You.");
reset();
} else {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Transaction Failed");
context.addMessage("ad", message);
}
}
}catch(Exception e){
log.error(e,e)
}
}
DepositAcc.xhtml:
<p:messages id="msgs" for="ad" globalOnly="true"/>
<h:panelGrid columns="9" cellpadding="5" id="add_edit" styleClass="add-form">
<h:outputLabel for="mobileNo" value="*Confirm Mobile No:"/>
<p:inputText id="mobileNo" value="#{depositController.mobileNoCnfrm}" required="true" disabled="#{depositController.trxnObj.mobileNo == null}">
</p:inputText>
<p:message for="mobileNo" display="icon"/>
<h:outputLabel for="amount" value="*Deposit Amount:"/>
<p:inputText id="amount" value="#{depositController.trxnObj.amount}" onkeyup="$(this).val(addCommas($(this).val()))" required="true" disabled="#{depositController.trxnObj.mobileNo == null}">
<f:convertNumber maxFractionDigits="2"
groupingUsed="true"
pattern="#,##0.00"/>
</p:inputText>
<p:message for="amount" display="icon"/>
<h:outputLabel for="amountCnfrm" value="*Confirm Amount:"/>
<p:inputText id="amountCnfrm" value="#{depositController.amountCnfrm}" onkeyup="$(this).val(addCommas($(this).val()))" required="true" disabled="#{depositController.trxnObj.mobileNo == null}">
<f:convertNumber maxFractionDigits="2"
groupingUsed="true"
pattern="#,##0.00"/>
</p:inputText>
<p:message for="amountCnfrm" display="icon"/>
<h:outputLabel for="location" value="*Branch Location:" rendered="#{!depositController.isRCP}"/>
<p:inputText id="location" value="#{depositController.location}" required="true" disabled="true" style="width: 200px" rendered="#{!depositController.isRCP}">
</p:inputText>
<p:message for="location" display="icon" rendered="#{!depositController.isRCP}"/>
<h:outputLabel for="note" value="Note:"/>
<p:inputTextarea id="note" value="#{depositController.trxnObj.note}" disabled="#{depositController.trxnObj.mobileNo == null}"
rows="4" cols="20" counter="counter" maxlength="100"
counterTemplate="({0}/100)">
</p:inputTextarea>
<h:outputText id="counter"/>
<p:message for="note" display="icon"/>
</h:panelGrid>
<h:panelGrid columns="3" cellpadding="5" id="btns" styleClass="add-btn">
<p:commandButton value="Deposit" ajax="true" update=":add:addFields :add:btns :list :dialog" actionListener="#{depositController.depositAcc}"
disabled="#{!depositController.depositEnable}"/>
<p:commandButton value="Reset" update="addFields btns" process="#this"
disabled="#{!depositController.depositEnable}"
actionListener="#{depositController.reset}"/>
<p:commandButton value="View Receipt" onclick="dlg.show()"
disabled="#{!depositController.recieptPrintEnabled}"/>
</h:panelGrid>
</p:fieldset>
</h:form>

Related

PrimeFaces 6.0 - InputText Ajax event + CommandButton Event Yields NULL Bean Fields

I want to trigger a method when a text field is blurred, and so I added an Ajax onblur event to this text field, and it works.
The problem I am having is with the commandButton that submits a bean with NULL fields.
When I get rid of the inputText Ajax event, the form submission works as usual.
The .xhtml file:
`
<h:head>
<title>Saisie Cotisations</title>
</h:head>
<h:body>
<h3>Saisie Cotisation</h3>
<h:form id="formulaire">
<h:panelGroup>
<p:panelGrid columns="2" id="panelMenage" >
<p:outputLabel value="N° Appartement" for="appart" />
<p:inputNumber id="appart" value="#{saisieBean.menage.numAppart}" decimalPlaces="0" emptyValue="empty" size="3" thousandSeparator="" >
<p:ajax event="blur" listener="#{saisieBean.chargerMenage}" update="panelMenage panelCotisation" />
</p:inputNumber>
<p:outputLabel value="Nom" for="nom" />
<p:inputText id="nom" value="#{saisieBean.menage.nom}" disabled="#{saisieBean.lectureSeule}" >
</p:inputText>
<p:outputLabel value="Prenom" for="prenom" />
<p:inputText id="prenom" value="#{saisieBean.menage.prenom}" disabled="#{saisieBean.lectureSeule}" >
</p:inputText>
<p:outputLabel value="Adresse E-Mail" for="email" />
<p:inputText id="email" value="#{saisieBean.menage.email}" disabled="#{saisieBean.lectureSeule}" >
</p:inputText>
</p:panelGrid>
</h:panelGroup>
<br />
<h:panelGroup>
<p:panelGrid columns="2" id="panelCotisation" >
<p:outputLabel value="Type Cotisation" />
<p:selectOneMenu value="#{saisieBean.menage.cotisation.id}" disabled="#{saisieBean.lectureSeule}" >
<f:selectItems value="#{saisieBean.typesCotisation}" var="tc" itemValue="#{tc.id}" itemLabel="#{tc.intitule}" />
</p:selectOneMenu>
<p:outputLabel value="Mois" />
<p:selectOneMenu value="#{saisieBean.mois}" disabled="#{saisieBean.lectureSeule}" >
<f:selectItems value="#{saisieBean.listeMois}" />
</p:selectOneMenu>
<p:outputLabel value="Annee" />
<p:inputNumber value="#{saisieBean.menage.cotisation.annee}" decimalPlaces="0" thousandSeparator="" disabled="#{saisieBean.lectureSeule}" />
<p:outputLabel value="Montant" />
<p:inputNumber value="#{saisieBean.menage.cotisation.montant}" decimalPlaces="2" disabled="#{saisieBean.lectureSeule}" />
</p:panelGrid>
</h:panelGroup>
<br />
<p:commandButton value="Soumettre" actionListener="#{saisieBean.exec}" process="#form" update="#form" immediate="false" ></p:commandButton>
</h:form>
</h:body>
`
The Bean:
package ma.syndic.bean;
import java.io.Serializable;
import java.text.DateFormatSymbols;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
import ma.syndic.back.bean.Cotisation;
import ma.syndic.back.bean.Menage;
import ma.syndic.back.bean.TypeCotisation;
import ma.syndic.back.dao.bean.MenageDAO;
import ma.syndic.back.dao.bean.TypeCotisationDAO;
import org.joda.time.DateTime;
/**
*
* #author Mohamed ENNAHDI EL IDRISSI
* #date 13/11/2016
*/
#ManagedBean
#ViewScoped
public class SaisieBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5492998931983521852L;
private Menage menage;
private Cotisation cotisation;
private List<TypeCotisation> typesCotisation;
private String[] listeMois;
private String mois;
private boolean lectureSeule = true;
public SaisieBean() {
// TODO Auto-generated constructor stub
}
#PostConstruct
public void init() {
this.menage = new Menage();
this.cotisation = new Cotisation();
try {
this.typesCotisation = new TypeCotisationDAO().findAll();
} catch (Exception e) {
e.printStackTrace();
}
this.listeMois = new DateFormatSymbols().getMonths();
int i = new DateTime().monthOfYear().get();
this.mois = this.listeMois[ i - 1 ];
this.menage.getCotisation().setAnnee(new DateTime().year().get());
}
public void exec() {
System.out.println("Exec fired");
System.out.println("EMail: " + this.menage.getEmail());
}
public void chargerMenage() {
System.out.println("chargerMenage fired");
if (this.menage.getNumAppart() != null) {
this.lectureSeule = false;
try {
Menage m = new MenageDAO().find(this.menage);
if (m != null) {
this.menage = m;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Menage getMenage() {
return menage;
}
public void setMenage(Menage menage) {
this.menage = menage;
}
public Cotisation getCotisation() {
return cotisation;
}
public void setCotisation(Cotisation cotisation) {
this.cotisation = cotisation;
}
public List<TypeCotisation> getTypesCotisation() {
return typesCotisation;
}
public void setTypesCotisation(List<TypeCotisation> typesCotisation) {
this.typesCotisation = typesCotisation;
}
public String[] getListeMois() {
return listeMois;
}
public void setListeMois(String[] listeMois) {
this.listeMois = listeMois;
}
public String getMois() {
return mois;
}
public void setMois(String mois) {
this.mois = mois;
}
public boolean isLectureSeule() {
return lectureSeule;
}
public void setLectureSeule(boolean lectureSeule) {
this.lectureSeule = lectureSeule;
}
}

How to show results from a search in a <p:Datatable> in the SAME Page?

I'm newbie in Java EE 7, I'm using DAO pattern to development a Java EE7 Application ( JPA , EJB , JSF-Primefaces)
I Have a p:tabView with 2 tabs, as you can see in the following image.
I want show the results from the search (when the user press the search button) in a p:DataTable, both are in the SAME PAGE.
I trying it, but I have various errors using p:ajax
Can you help me please.
Well I'm working in this exercise, to below my code:
My view XHTML
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<h:outputStylesheet library="css" name="style.css" />
<title>Creditos</title>
</h:head>
<body>
<ui:composition template="./../views/template.xhtml">
<ui:define name="content">
<h:form>
<p:panelGrid columns="2">
<p:outputLabel value="Fecha Inicio:"/>
<p:calendar navigator="true" value="#{creditoBean.fecha1}"/>
<p:outputLabel value="Fecha Fin:"/>
<p:calendar navigator="true" value="#{creditoBean.fecha2}"/>
<p:commandButton value="Cargar" actionListener="#{creditoBean.filtrarFechas()}"
update=":formMostrar"/>
</p:panelGrid>
<p:panelGrid columns="2">
<p:outputLabel value="Ingrese DNI o RUC:"/>
<p:inputMask mask="9?9999999999" maxlength="11" value="#{creditoBean.dni}"/>
<p:commandButton value="Buscar" actionListener="#{creditoBean.cargarAnexoDNI()}"
ajax="false"/>
</p:panelGrid>
</h:form>
<h:form id="formMostrar">
<p:dataTable var="cred" value="#{creditoBean.filtradafecha}"
emptyMessage="No hay nada para mostrar"
paginator="true" rows="20" paginatorPosition="top"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink}
{PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="20">
<p:column headerText="Cod.">
<h:outputText value="#{cred.liqventa}" />
</p:column>
<p:column headerText="Nombres">
<h:outputText value="#{cred.anexoByIdanexo.nombres}" />
</p:column>
<p:column headerText="Tienda" filterBy="#{cred.tienda}" filterMatchMode="contains">
<h:outputText value="#{cred.tienda}">
<f:converter converterId="tiendaconverter"/>
</h:outputText>
</p:column>
<p:column headerText="Empresa" filterBy="#{cred.empresa}" filterMatchMode="contains">
<h:outputText value="#{cred.empresa}">
<f:converter converterId="empresaconverter"/>
</h:outputText>
</p:column>
<p:column headerText="Vehículo">
<h:outputText value="#{cred.vehiculo.tipovehiculo}">
<f:converter converterId="tvehiculo"/>
</h:outputText>
</p:column>
<p:column headerText="Deuda">
<h:outputText value="#{cred.totaldeuda}" />
</p:column>
<p:column headerText="Cargar">
<p:commandButton value="C" /*Here charge the table */ update=":formModificar"
actionListener="#{creditoBean.cargarLetras()}" onclick="$('#tablaletras').show();"/>
</p:column>
<p:column headerText=" ">
<p:commandButton icon="b-delete" oncomplete="dlgeliminar.show()" update=":formEliminar">
<f:setPropertyActionListener target="#{creditoBean.credito}" value="#{cred}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
<div id="tablaletras" class="campo">
<h:form id="formModificar">
<p:dataTable var="letras" value="#{creditoBean.letraslista}"
emptyMessage="No hay nada para mostrar">
<p:inputText type="hidden" value="#{letras.idletras}"/>
<p:column headerText="Cod venta.">
<h:outputText value="#{letras.credito.liqventa}" />
</p:column>
<p:column headerText="Descripcion">
<h:outputText value="#{letras.descripcion}"/>
</p:column>
<p:column headerText="Monto">
<h:outputText value="#{letras.montoletra}"/>
</p:column>
<p:column headerText="Interes">
<h:outputText value="#{letras.interes}"/>
</p:column>
<p:column headerText="Total Letra">
<h:outputText value="#{letras.monto}"/>
</p:column>
<p:column headerText="Fecha In.">
<h:outputText value="#{letras.fecini}">
<f:convertDateTime/>
</h:outputText>
</p:column>
<p:column headerText="Fecha Ven.">
<h:outputText value="#{letras.fecven}">
<f:convertDateTime/>
</h:outputText>
</p:column>
<p:column headerText="Saldo">
<h:outputText value="#{letras.saldo}"/>
</p:column>
<p:column headerText="Estado">
<h:outputText value="#{letras.estado}">
<f:converter converterId="letrasconverter"/>
</h:outputText>
</p:column>
<p:column headerText="Pagar">
<p:commandButton oncomplete="dlgpagar.show()" value="P" update=":formPagar"
actionListener="#{pagosBean.cargarLetra(letras)}"/>
</p:column>
</p:dataTable>
<p:commandButton value="Nota de Débito" icon="b-add" update=":formPagar"
oncomplete="dlgnotadebito.show()" />
</h:form>
</div>
<p:dialog id="dlg1" header="Ingrese los datos" showEffect="explode" hideEffect="explode"
widgetVar="dlgpagar" modal="true" resizable="false" minWidth="200">
<h:form id="formPagar">
<p:panelGrid columns="4">
<p:outputLabel value="Fecha:"/>
<p:calendar navigator="true" value="#{pagosBean.pago.fecreg}"/>
<p:outputLabel value="Tipo:"/>
<p:selectOneMenu value="#{pagosBean.pago.tipo}">
<f:selectItem itemLabel="Letra" itemValue="LE" />
<f:selectItem itemLabel="Nota de Credito" itemValue="NC" />
</p:selectOneMenu>
<p:outputLabel value="Referencia:"/>
<p:inputText value="#{pagosBean.pago.operacion}"/>
<p:outputLabel value="Monto:"/>
<p:inputText value="#{pagosBean.pago.monto}"/>
<p:outputLabel value="Descripción:"/>
<p:inputText value="#{pagosBean.pago.descripcion}"/>
<p:commandButton actionListener="#{pagosBean.insertar()}" value="Pagar" oncomplete="dlgpagar.hide()"
update=":formModificar"/>
</p:panelGrid>
</h:form>
</p:dialog>
<p:dialog id="dlg3" header="Ingrese los datos" showEffect="explode" hideEffect="explode"
widgetVar="dlgnotadebito" modal="true" resizable="false" minWidth="200">
<h:form id="formNotadebito">
<p:panelGrid columns="4">
<p:outputLabel value="Fecha Inicio:"/>
<p:calendar navigator="true" value="#{creditoBean.letra.fecini}"/>
<p:outputLabel value="Fecha Venc:"/>
<p:calendar navigator="true" value="#{creditoBean.letra.fecven}"/>
<p:outputLabel value="Monto:"/>
<p:inputText value="#{creditoBean.letra.monto}"/>
<p:commandButton actionListener="#{creditoBean.insertarNotaDebito()}" value="Guardar" oncomplete="dlgnotadebito.hide()"
update=":formModificar"/>
</p:panelGrid>
</h:form>
</p:dialog>
<p:dialog id="dlg2" header="Eliminar Credito" showEffect="explode" hideEffect="explode"
widgetVar="dlgeliminar" modal="true" resizable="false" minWidth="200">
<h:form id="formEliminar">
<h:outputText value="¿Desea eliminar?" />
<p:commandButton value="Si" actionListener="#{creditoBean.eliminar()}"
ajax="false" oncomplete="dlgeliminar.hide();" />
<p:commandButton value="No" onclick="dlg2.hide();" />
</h:form>
</p:dialog>
</ui:define>
</ui:composition>
</body>
My CreditoBean:
#ManagedBean
#SessionScoped
public class creditoBean implements Serializable {
public Credito credito = new Credito();
public List<Credito> creditos;
LetrasDao letrasdao = new LetrasDaoImplements();
public List<Letras> letrasventa;
public List<Credito> filtradafecha;
private Date fecha1 = new Date();
private Date fecha2 = new Date();
private List<Letras> letraslista = new ArrayList();
private Pagos pago = new Pagos();
private Letras letra = new Letras();
private String dni;
private BigDecimal res;
/*Constructor and getters and setters*/
public void eliminar() {
CreditoDao creditodao = new CreditoDaoImp();
LetrasDao letrasdao = new LetrasDaoImplements();
List<Letras> letrita = new ArrayList();
letrita = letrasdao.mostrarLetrasXCred(credito);
BigDecimal totaldeuda = new BigDecimal(BigInteger.ZERO);
for (int i = 0; i < letrita.size(); i++) {
Letras get = letrita.get(i);
totaldeuda = totaldeuda.add(get.getMonto());
}
if (totaldeuda.compareTo(credito.getTotaldeuda()) == 0) {
creditodao.eliminarVenta(credito);
} else {
System.out.println("Mostrar Error de que el credito ya ha sido cobrado y no se puede borrar");
}
credito = new Credito();
}
public Date sumaDias(Date fecha, int dias) {
Calendar cal = Calendar.getInstance();
cal.setTime(fecha);
cal.add(Calendar.DAY_OF_YEAR, dias);
return cal.getTime();
}
public void filtrarFechas() {
CreditoDao linkdao = new CreditoDaoImp();
filtradafecha = linkdao.filtrarFechas(fecha1, fecha2);
}
public void cargarCredito(Anexo anexo) {
letraslista = new ArrayList();
CreditoDao creditodao = new CreditoDaoImp();
List<Letras> letritas = new ArrayList();
Calendar calendario = GregorianCalendar.getInstance();
Date fecha = calendario.getTime();
credito = creditodao.cargarCreditoxAnexo(anexo);
LetrasDao letras = new LetrasDaoImplements();
letritas = letras.mostrarLetrasXCred(credito);
for (int i = 0; i < letritas.size(); i++) {
System.out.println(" Entre al for :" + letritas.get(i));
Letras get = letritas.get(i);
if (get.getSaldo().compareTo(BigDecimal.ZERO) == 0) {
get.setEstado("CN");
System.out.println(" Entre al IF :" + get.getEstado());
} else {
if (get.getSaldo().compareTo(BigDecimal.ZERO) == 1) {
if (get.getFecven().after(fecha)) {
get.setEstado("PN");
} else {
get.setEstado("VN");
}
}
}
letrasdao.modificarLetra(get);
}
letraslista = letras.mostrarLetrasXCred(credito);
}
public void cargarLetras(/*Anexo anexo*/) {
letraslista = new ArrayList();
CreditoDao creditodao = new CreditoDaoImp();
List<Letras> letritas = new ArrayList();
Calendar calendario = GregorianCalendar.getInstance();
Date fecha = calendario.getTime();
LetrasDao letras = new LetrasDaoImplements();
letritas = letras.mostrarLetrasXCred(credito);
for (int i = 0; i < letritas.size(); i++) {
System.out.println(" Entre al for :" + letritas.get(i));
Letras get = letritas.get(i);
if (get.getSaldo().compareTo(BigDecimal.ZERO) == 0) {
get.setEstado("CN");
System.out.println(" Entre al IF :" + get.getEstado());
} else {
if (get.getSaldo().compareTo(BigDecimal.ZERO) == 1) {
if (get.getFecven().after(fecha)) {
get.setEstado("PN");
} else {
get.setEstado("VN");
}
}
}
letrasdao.modificarLetra(get);
}
letraslista = letras.mostrarLetrasXCred(credito);
}
public void insertarPago() {
PagosDao linkDao = new PagosDaoImp();
System.out.println("Este es el Id de letra :" + letra.getIdletras());
linkDao.insertarPago(pago);
pago = new Pagos();
}
public void insertarNotaDebito() {
LetrasDao letrasdao = new LetrasDaoImplements();
Date d = new Date();
letra.setCredito(credito);
letra.setDescripcion("ND");
letra.setFecreg(d);
letra.setMontoletra(BigDecimal.ZERO);
letra.setInteres(BigDecimal.ZERO);
letra.setSaldo(letra.getMonto());
letra.setEstado("PN");
letrasdao.insertarLetra(letra);
}
public void cargarAnexoDNI() {
filtradafecha = new ArrayList();
AnexoDao anexodao = new AnexoDaoImplements();
Anexo anexo = new Anexo();
CreditoDao creditodao = new CreditoDaoImp();
try {
anexo = anexodao.cargarClientexDoc(dni, "CN", "CJ");
credito = creditodao.cargarCreditoxAnexo(anexo);
filtradafecha.add(credito);
} catch (Exception e) {
}
}
And finally, My Dao:
package Dao;
import Model.Anexo;
import Model.Credito;
import Model.Letras;
import Persistencia.HibernateUtil;
import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public class CreditoDaoImp implements CreditoDao{
#Override
public List<Credito> mostrarVentas() {
Session session = null;
List<Credito> lista = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery("FROM Credito");
lista = (List<Credito>)query.list();
}catch (HibernateException e){
System.out.println(e.getMessage());
}
finally{
if (session != null){
session.close();
}
}
return lista;
}
#Override
public void insertarVenta(Credito credito) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(credito);
session.getTransaction().commit();
} catch (HibernateException e){
System.out.println(e.getMessage());
session.getTransaction().rollback();
}
finally {
if(session != null){
session.close();
}
}
}
#Override
public void modificarVenta(Credito credito) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.update(credito);
session.getTransaction().commit();
} catch (HibernateException e){
System.out.println(e.getMessage());
session.getTransaction().rollback();
}
finally {
if(session != null){
session.close();
}
}
}
#Override
public void eliminarVenta(Credito credito) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.delete(credito);
session.getTransaction().commit();
} catch (HibernateException e){
System.out.println(e.getMessage());
session.getTransaction().rollback();
}
finally {
if(session != null){
session.close();
}
}
}
#Override
public List<Credito> filtrarFechas(Date date1, Date date2) {
Session session = null;
List<Credito> lista = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery("FROM Credito WHERE fechareg BETWEEN :start_date AND :end_date" );
query.setParameter("start_date", date1);
query.setParameter("end_date", date2);
lista = (List<Credito>)query.list();
}catch (HibernateException e){
System.out.println(e.getMessage());
}
finally{
if (session != null){
session.close();
}
}
return lista;
}
#Override
public Credito cargarCreditoxAnexo(Anexo anexo) {
Session session = null;
Credito credito = new Credito();
Integer idanexo;
idanexo = anexo.getIdanexo();
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery("FROM Credito WHERE idanexo=:w");
query.setParameter("w", idanexo);
credito = (Credito) query.uniqueResult();
} catch (HibernateException e) {
System.out.println(e.getMessage());
} finally {
if (session != null) {
session.close();
}
}
return credito;
}
#Override
public Credito cargarCreditoxLetra(Letras letra) {
Session session = null;
Credito credito = new Credito();
Integer idcredito;
idcredito = letra.getCredito().getIdventa();
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery("FROM Credito WHERE idventa=:w");
query.setParameter("w", idcredito);
credito = (Credito) query.uniqueResult();
} catch (HibernateException e) {
System.out.println(e.getMessage());
} finally {
if (session != null) {
session.close();
}
}
return credito;
}
#Override
public List<Credito> filtrarDni(String dni) {
Session session = null;
List<Credito> lista = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery("FROM Credito WHERE " );
query.setParameter("start_date", dni);
lista = (List<Credito>)query.list();
}catch (HibernateException e){
System.out.println(e.getMessage());
}
finally{
if (session != null){
session.close();
}
}
return lista;
}
#Override
public List<Credito> filtrarCreditoxAnexo(Anexo anexo) {
Session session = null;
List<Credito> lista = null;
Integer idanexo;
idanexo = anexo.getIdanexo();
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery("FROM Credito WHERE idanexo=:w");
query.setParameter("w", idanexo);
lista = query.list();
} catch (HibernateException e) {
System.out.println(e.getMessage());
} finally {
if (session != null) {
session.close();
}
}
return lista;
}
}
The results:

Data table filtering with Ajax issue in JSF primefaces

I have a data table with global filtering. I want to filtered the data. In search criteria I pressed one key based on data is not filtered and Ajax call is wont be terminated still loaded.where I made mistake please suggest me.
Here is my Code:
<p:dataTable id="dataCall" var="calls" value="#{calllist.mediumCallsModel}" style="font-size: 12px; width: 1000px" widgetVar="callsTable"
emptyMessage="No record found with given criteria"
selection="#{calllist.selectedCall}" selectionMode="single" rows="5" paginator="true" filteredValue="#{callList.filteredDatas}"
paginatorPosition="bottom" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" >
<p:ajax event="rowSelect" listener="#{calllist.onRowSelect}" update=":MyListForm:showlist: :MyListForm:growl" />
<p:ajax event="rowUnselect" listener="#{calllist.onRowUnselect}" update=":MyListForm:growl"/>
<f:facet name="header">
<p:outputPanel style="display:block; text-align:right">
<h:outputText value="Search all fields:"/>
<p:inputText id="globalFilter" onkeyup="callsTable.filter()" style="width:150px" />
</p:outputPanel>
</f:facet>
<p:column headerText="Call ID" filterBy="#{calls.callId}" sortBy="#{calls.callId}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.callId}" />
</p:column>
<p:column headerText="Created By" filterBy="#{calls.createdBy}" sortBy="#{calls.createdBy}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.createdBy}" />
</p:column>
<p:column headerText="Location" filterBy="#{calls.location}" sortBy="#{calls.location}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.location}" />
</p:column>
<p:column headerText="Status" filterBy="#{calls.status}" sortBy="#{calls.status}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.status}" />
</p:column>
<p:column headerText="Product" filterBy="#{calls.product}" sortBy="#{calls.product}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.product}" />
</p:column>
<p:column headerText="Module" filterBy="#{calls.module}" sortBy="#{calls.module}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.module}" />
</p:column>
<p:column headerText="Group Assigned" filterBy="#{calls.groupAssigned}" sortBy="#{calls.groupAssigned}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.groupAssigned}" />
</p:column>
<p:column headerText="Assigned to" filterBy="#{calls.assignedTo}" sortBy="#{calls.assignedTo}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.assignedTo}" />
</p:column>
<p:column headerText="Call creation" filterBy="#{calls.callCreation}" sortBy="#{calls.callCreation}" filterStyle="display: none; visibility: hidden;">
<h:outputText value="#{calls.callCreation}" />
</p:column>
</p:dataTable>
My Bean:
public class CallList{
private List<CallModel> callList = null;
private CallModel selectedCall = new CallModel();
private CallDataModel mediumCallsModel;
private List<CallModel> filteredDatas;
private boolean enableButton;
public CallList() {
this.enableButton = true;
}
public CallModel getSelectedCall() {
return selectedCall;
}
public void setSelectedCall(CallModel selectedCall) {
this.selectedCall = selectedCall;
}
public CallDataModel getMediumCallsModel() {
getAllList();
return mediumCallsModel;
}
public void setMediumCallsModel(CallDataModel mediumCallsModel) {
this.mediumCallsModel = mediumCallsModel;
}
public List<CallModel> getCallList() {
return callList;
}
public void setCallList(List<CallModel> callList) {
this.callList = callList;
}
public List<CallModel> getFilteredDatas() {
return filteredDatas;
}
public void setFilteredDatas(List<CallModel> filteredDatas) {
this.filteredDatas = filteredDatas;
}
public List<CallModel> getAllList() {
List<CallHeader> headerList = null;
List<ProductMaster> productList = null;
List<StatusMaster> statusList = null;
List<ModuleMaster> moduleDesc = null;
List<Time> timeList = null;
List<PriorityMaster> priorityList = null;
List<SlaMaster> slaList = null;
List<SubmoduleMaster> subList = null;
List<UserMaster> userList=null;
Session ses = HibernateUtil.getSessionFactory().openSession();
FacesContext context = FacesContext.getCurrentInstance();
try {
HttpSession sess = (HttpSession) context.getExternalContext().getSession(true);
String userid = (String) sess.getAttribute("userId");
headerList = ses.createCriteria(CallHeader.class).add(Expression.or(Restrictions.eq("userMaster.userId", userid), Restrictions.eq("assignedId", userid))).list();
callList = new ArrayList<CallModel>(headerList.size());
for (Iterator<CallHeader> it = headerList.iterator(); it.hasNext();) {
CallHeader callHeader = it.next();
productList = ses.createCriteria(ProductMaster.class).add(Restrictions.eq("productId", callHeader.getId().getProductId())).list();
Iterator<ProductMaster> it1 = productList.iterator();
ProductMaster productMaster = it1.next();
statusList = ses.createCriteria(StatusMaster.class).add(Restrictions.eq("id.statusId", callHeader.getStatusId())).list();
Iterator<StatusMaster> it2 = statusList.iterator();
it2.hasNext();
StatusMaster statusMaster = it2.next();
moduleDesc = ses.createCriteria(ModuleMaster.class).add(Restrictions.eq("id.moduleId", callHeader.getModuleId())).list();
Iterator<ModuleMaster> it3 = moduleDesc.iterator();
it3.hasNext();
ModuleMaster moduleMaster = it3.next();
timeList = ses.createCriteria(Time.class).add(Restrictions.eq("id.callId", callHeader.getId().getCallId())).list();
Iterator<Time> it4 = timeList.iterator();
it4.hasNext();
Time time = it4.next();
priorityList = ses.createCriteria(PriorityMaster.class).add(Restrictions.eq("id.priorityId", callHeader.getPriorityId())).list();
Iterator<PriorityMaster> it5 = priorityList.iterator();
it5.hasNext();
PriorityMaster priorityMaster = it5.next();
slaList = ses.createCriteria(SlaMaster.class).add(Restrictions.eq("id.slaId", callHeader.getSlaId())).list();
Iterator<SlaMaster> it6 = slaList.iterator();
it6.hasNext();
SlaMaster slaMaster = it6.next();
subList = ses.createCriteria(SubmoduleMaster.class).add(Restrictions.eq("id.productId", callHeader.getId().getProductId())).add(Restrictions.eq("id.moduleId", callHeader.getModuleId())).list();
Iterator<SubmoduleMaster> it7 = subList.iterator();
it7.hasNext();
SubmoduleMaster subMaster = it7.next();
userList=ses.createCriteria(UserMaster.class).add(Restrictions.eq("userId", callHeader.getAssignedId())).list();
Iterator<UserMaster> it8 = userList.iterator();
it8.hasNext();
UserMaster userMaster = it8.next();
callList.add(new CallModel(callHeader.getId().getCallId(), callHeader.getUserMaster().getFirstName() + " " + callHeader.getUserMaster().getLastName(), callHeader.getUserMaster().getLocation(), statusMaster.getStatusDesc(), productMaster.getProductName(), moduleMaster.getModuleDesc(), callHeader.getGroupMaster().getGroupId(), userMaster.getUserId(), time.getCallCreated(),
priorityMaster.getId().getPriorityId(), callHeader.getProposedTime(), callHeader.getAcceptedTime(), callHeader.getActualTime(), callHeader.getCallRelation(), slaMaster.getId().getSlaId(), statusMaster.getId().getStatusId(), productMaster.getProductId(), moduleMaster.getId().getModuleId(), subMaster.getId().getSubmoduleId(), callHeader.getProblemType(),
callHeader.getRatingId(), callHeader.getId().getCompanyId(),userMaster.getFirstName()+" "+userMaster.getLastName()));
}
mediumCallsModel = new CallDataModel(callList);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
ses.close();
}
return callList;
}
public void onRowSelect(SelectEvent event) { }
}

JSF ajax validation don't validate items with required true

I have a datatable, a column with h:commandlink for edit (ajax request), the detail show in jquery dialog, everything ok, in the edit form i have h:commandlink (ajax request) for save, if i make changes eg, drop a value in input required, and push submit, jsf don't validate this input, and don't show the message "this input is required"
<div id="container">
<button id="create-user" >Create new user</button>
<h:dataTable value="#{gasweb.lsProveedor}" var="tabpro" id="example" class="display dataTable" >
<h:column>
<f:facet name="id">
<h:outputLabel value="Id"/>
</f:facet>
<h:outputText value="#{tabpro.proveedor_id}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel value="Cedula"/>
</f:facet>
<h:outputText value="#{tabpro.cedula_ruc}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel value="NombreComercial"/>
</f:facet>
<h:commandLink value="#{tabpro.nombre_comercial}" actionListener="#{gasweb.doEditProveedor2}" class="labrir" >
<f:param name="pproveedor_id" value="#{tabpro.proveedor_id}" />
<f:ajax execute="#this" render=":forma:editgrid" >
</f:ajax>
</h:commandLink>
</h:column>
<h:column>
<f:facet name="header">
<h:outputLabel value="Razon Social"/>
</f:facet>
<h:outputText value="#{tabpro.razon_social}"/>
</h:column>
</h:dataTable>
</div>
<div id="divformap" title="Proveedor">
<h:inputHidden value="#{gasweb.newRecord}" id="txtnewrecord" />
<h:inputHidden value="#{gasweb.ruc_proveedor_ori}" id="txtcedulaori" />
<h:panelGrid columns="2" id="editgrid" >
<h:outputLabel value="Id :" />
<h:outputText id="txtid" value="#{gasweb.proveedor.proveedor_id}" />
<h:outputLabel value="Ruc :" />
<h:inputText id="txtcedula" value="#{gasweb.proveedor.cedula_ruc}" size="20" class="text ui-widget-content ui-corner-all" />
<h:outputLabel value="Nombr Comercial :" />
<h:inputText id="txtnombre" value="#{gasweb.proveedor.nombre_comercial}" required="true" size="80" class="text ui-widget-content ui-corner-all"/>
<h:outputLabel value="Razón Social :" />
<h:inputText id="txtrazon" value="#{gasweb.proveedor.razon_social}" size="80" class="text ui-widget-content ui-corner-all"/>
<h:outputLabel value="Dirección :" />
<h:inputText id="txtdireccion" value="#{gasweb.proveedor.direccion}" size="80" class="text ui-widget-content ui-corner-all"/>
<h:outputLabel value="Telefono :" />
<h:inputText id="txttelefono" value="#{gasweb.proveedor.telefono}" size="20" class="text ui-widget-content ui-corner-all"/>
<h:outputLabel value="Estado :" />
<h:outputText id="txtestado" value="#{gasweb.proveedor.estado}" />
<h:commandButton id="aceptar" value="Aceptar" actionListener="#{gasweb.doGrabaProveedor}" >
<f:param name="pproveedor_id2" value="#{gasweb.proveedor.proveedor_id}" />
<f:ajax render="bProveedor" execute="#form" onevent="resetFocus" />
</h:commandButton>
<h:outputText id="bProveedor" value="#{gasweb.bProveedorExiste}" />
</h:panelGrid>
</div>
My managed bean
public class GasperWebMB implements Serializable{
private List<Contribuyente> lsContribuyente;
private List<Proveedor> lsProveedor;
private Contribuyente contribuyente;
private Proveedor proveedor;
private Declara serdec;
private FacesContext fc = FacesContext.getCurrentInstance();
private Boolean newRecord;
private String ruc_proveedor_ori;
private String bProveedorExiste;
//#ManagedProperty("#param.pproveedor_id")
//private Integer pproveedor_id;
//private HttpServletRequest request;
public GasperWebMB(){
serdec = new Declara();
contribuyente = new Contribuyente();
proveedor = new Proveedor();
lsContribuyente = serdec.getAllContribuyente();
lsProveedor = serdec.getAllProveedor();
newRecord = true;
log("creado");
//request.getHeader(ruc_proveedor_ori);
}
public String getbProveedorExiste() {
return bProveedorExiste;
}
public void setbProveedorExiste(String bProveedorExiste) {
this.bProveedorExiste = bProveedorExiste;
}
public String getRuc_proveedor_ori() {
log(ruc_proveedor_ori);
return ruc_proveedor_ori;
}
public void setRuc_proveedor_ori(String ruc_proveedor_ori) {
log(ruc_proveedor_ori);
this.ruc_proveedor_ori = ruc_proveedor_ori;
}
public Boolean getNewRecord() {
log(newRecord);
return newRecord;
}
public void setNewRecord(Boolean newRecord) {
log(newRecord);
this.newRecord = newRecord;
}
public List<Proveedor> getLsProveedor() {
log(lsProveedor);
return lsProveedor;
}
public void setLsProveedor(List<Proveedor> lsProveedor) {
log(lsProveedor);
this.lsProveedor = lsProveedor;
}
public Proveedor getProveedor() {
log(proveedor);
return proveedor;
}
public void setProveedor(Proveedor proveedor) {
log(proveedor);
this.proveedor = proveedor;
}
public List<Contribuyente> getLsContribuyente() {
return lsContribuyente;
}
public void setLsContribuyente(List<Contribuyente> lsContribuyente) {
this.lsContribuyente = lsContribuyente;
}
public Contribuyente getContribuyente() {
return contribuyente;
}
public void setContribuyente(Contribuyente contribuyente) {
this.contribuyente = contribuyente;
}
public String doEditContribuyente(){
Map<String, String> params = fc.getExternalContext().getRequestParameterMap();
contribuyente = serdec.getContribuyenteById(Integer.parseInt(par));
newRecord = false;
ruc_proveedor_ori = proveedor.getCedula_ruc();
return "FContribuyente";
}
public String doGrabaContribuyente(){
System.out.println("grabar " + contribuyente.getCedula_ruc()+ " id " + contribuyente.getContribuyente_id());
serdec.updContribuyente(contribuyente);
return "lisContribuyente";
}
public String doEditProveedor(){
System.out.println("Entra");
Map<String, String> params = fc.getExternalContext().getRequestParameterMap();
String par = params.get("pproveedor_id");
System.out.println("pro" + par);
proveedor = serdec.getProveedorById(Integer.parseInt(par));
newRecord = false;
System.out.println("va a salir");
return "editprov";
}
public void doGrabaProveedor(ActionEvent event){
System.out.println("gra"+proveedor.getNombre_comercial()+" new "+ newRecord);
Proveedor xpro = serdec.getProveedorByRuc(proveedor.getCedula_ruc());
if (xpro != null && !proveedor.getCedula_ruc().equals(ruc_proveedor_ori)){
System.out.println("Ya existe");
bProveedorExiste = xpro.getNombre_comercial();
//FacesContext.getCurrentInstance().validationFailed();
FacesMessage fmes = new FacesMessage("El Ruc "+proveedor.getCedula_ruc()+" ya se encuentra registrado para otro proveedor");
fc.addMessage(null, fmes);
//fc.addMessage("Proveedor ya existe", fmes);
//return "sucess";
return;
}
if (newRecord){
proveedor.setEstado("A");
//serdec.insProveedor(proveedor);
}
else {
//serdec.updProveedor(proveedor);
}
System.out.println("Si graba");
//return "sucess";
}
public void doEditProveedor2(ActionEvent event){
/*Map<String, String> params = fc.getExternalContext().getRequestParameterMap();
String par = params.get("pproveedor_id");
proveedor = serdec.getProveedorById(Integer.parseInt(par));
newRecord = false;
return "FProveedor";*/
String pproveedor_id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("pproveedor_id");
proveedor = serdec.getProveedorById(Integer.parseInt(pproveedor_id));
newRecord = false;
System.out.println("si edit2 param "+ pproveedor_id + " new "+ newRecord);
System.out.println("si edit2 proveedor "+ proveedor.getNombre_comercial() + " new "+ newRecord);
}
private void log(Object object) {
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
System.out.println("Bean " + methodName + ": " + object);
}
}
In this code, dropped the jquery dialog and show detail in div
you must either put <h:messages /> or <h:message /> at html page.
h:messages – Output all messages in current page.
h:message – Output a single message for a specific component.
1- in your case, try put <h:messages /> at the top page or inside the edit form.
2- or u can to put <h:message /> for each required input such as
<h:message for="txtnombre" style="color:red" /> after/before the input.

PropertyNotFoundException for filter in Richfaces datatable

I am trying to add filtering to a rich:datatable but am having problems with the PropertyNotFoundException - using an example from the showcase (Richfaces 4) I have the following
<f:facet name="noData">
Nothing found
</f:facet>
<rich:column filter="#{mailerBean.firstNameFilterImpl}">
<f:facet name="header">
<h:outputText value="First Name" />
<h:inputText value="#{mailerBean.firstNameFilter}" id="input">
<a4j:ajax event="blur" render="dataTable" execute="#this" />
</h:inputText>
</f:facet>
<h:outputText value="#{person.firstName}" />
</rich:column>
The Bean contains
#ManagedBean
#SessionScoped
public class MailerBean implements Serializable {
............
public String getFirstNameFilter() {
return firstNameFilter;
}
public void setFirstNameFilter(String firstNameFilter) {
this.firstNameFilter = firstNameFilter;
}
public Filter<?> getFirstNameFilterImpl() {
return new Filter<Person>() {
public boolean accept(Person t) {
String firstName = getFirstNameFilter();
if (firstName == null || firstName.length() == 0 ||
firstName.toLowerCase().contains(t.getFirstName().toLowerCase())) {
return true;
}
return false;
}
};
The error I get is
javax.el.PropertyNotFoundException: /mailinglistpage.xhtml #66,67
filter="#{mailerBean.firstNameFilterImpl}": Property
'firstNameFilterImpl' not found on type
com.patcomsys.zuzz.mailer.web.MailerBean
The method is in the bean and it does return a Filter object - can you see anything wrong?
Thanks

Resources