jsf primefaces download file in dilogue box is not working - jsf

I want to download file in my jsf page, and below is my jsf page
<h:form id="MyListForm">
<p:commandButton value="Attachments" icon="ui-icon-transferthick-e-w" actionListener="#{myTeam.downloadImageDialogue}"
style="font-size: 10px;font-weight: bolder;vertical-align: text-bottom;width: 80px;" >
</p:commandButton>
</h:form>
and my bean code is:
public void downloadImageDialogue() {
RequestContext.getCurrentInstance().openDialog("AttachmentDialog");
}
and my dilogue xhtml page is:
<h:body>
<h:form>
<p:dataTable var="Attachment" value="#{attachmentDialogView.attachmentList}" rows="10">
<p:column headerText="File Name">
<h:outputText value="#{Attachment.fileName}" />
</p:column>
<p:column headerText="Download Attachment">
<p:commandLink ajax="false" id="dwldLink" action="#{attachmentDialogView.downloadImage}">
<f:setPropertyActionListener value="#{Attachment.id.itemId}" target="#{attachmentDialogView.imageItemId}" />
<f:setPropertyActionListener value="#{Attachment.fileName}" target="#{attachmentDialogView.fileName}" />
<f:setPropertyActionListener value="#{Attachment.id.callId}" target="#{attachmentDialogView.callID}" />
<p:graphicImage value="images/dnld1.png" width="25" height="25"/>
<p:fileDownload value="#{attachmentDialogView.file}"/>
</p:commandLink>
</p:column>
</p:dataTable>
</h:form>
</h:body>
and bean code is:
#ManagedBean(name = "attachmentDialogView")
#ViewScoped
public class AttachmentDialogView implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Attachment> attachmentList;
private String imageItemId;
private String fileName;
private DefaultStreamedContent file;
String callID;
#ManagedProperty("#{myTeamService}")
private MyTeamService service;
#PostConstruct
public void init() {
attachmentList = service.getAttachmentList(service.getCallId());
}
public void downloadImage() {
Session session = HibernateUtil.getSessionFactory().openSession();
Attachment attachment = null;
byte[] bImage;
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
try {
if (getCallID() == null || getCallID().equals("")) {
RequestContext.getCurrentInstance().execute("PF('check_dialog').show()");
} else {
attachment = (Attachment) session.createCriteria(Attachment.class).add(Restrictions.eq("id.itemId", getImageItemId())).add(Restrictions.eq("id.callId", getCallID())).uniqueResult();
bImage = attachment.getFileData();
InputStream stream = new ByteArrayInputStream(bImage);
file = new DefaultStreamedContent(stream,externalContext.getMimeType(getFileName()),getFileName());
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
session.close();
}
}
public List<Attachment> getAttachmentList() {
return attachmentList;
}
public void setAttachmentList(List<Attachment> attachmentList) {
this.attachmentList = attachmentList;
}
public MyTeamService getService() {
return service;
}
public void setService(MyTeamService service) {
this.service = service;
}
public String getImageItemId() {
return imageItemId;
}
public void setImageItemId(String imageItemId) {
this.imageItemId = imageItemId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public DefaultStreamedContent getFile() {
return file;
}
public void setFile(DefaultStreamedContent file) {
this.file = file;
}
public String getCallID() {
return callID;
}
public void setCallID(String callID) {
this.callID = callID;
}
}
here dilogue opens correctly but image will not opened please help me.

Related

Passing additional Objects to commandLink

I want to use the same View for different states of a bean. Therefore I need to Inject/pass/whatever get the current bean I want to modify, but I always get null.
I already tried it with , with #Inject, and the other solutions given in How can I pass selected row to commandLink inside dataTable or ui:repeat?
The View:
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import org.primefaces.PrimeFaces;
import de.auticon.beans.Mitarbeiter;
import de.auticon.beans.Skill;
#Named(value = "skillView")
#ViewScoped
public class SkillView implements Serializable {
private static final long serialVersionUID = -3256509521249071048L;
private Mitarbeiter employee;
private Skill skill = new Skill();
private List<String> expertises = new ArrayList<String>();
#PostConstruct
public void init() {
List<Expertise_String> expertiseObjects = Queries.findAllExpertises();
for (Expertise_String singleExpertise : expertiseObjects) {
expertises.add(singleExpertise.getExpertise() + " - " + singleExpertise.getFullNameString());
}
}
//Here employee is null, but I need the new/existing employee
public void addSkill() {
employee.getSkills().add(skill);
PrimeFaces.current().dialog().closeDynamic(null);
}
public void closeDialog() {
PrimeFaces.current().dialog().closeDynamic(null);
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
public Mitarbeiter getEmployee() {
return employee;
}
public void setEmployee(Mitarbeiter employee) {
this.employee = employee;
}
}
XHTML from which it is called for existing employees:
<h:form id="form">
<p:panelGrid columns="2" styleClass="ui-noborder">
<p:menu toggleable="true">
<p:submenu label="Verwaltung">
<p:menuitem>
<p:commandButton value="Mitarbeiter anlegen" action="#{adminView.addNewEmployee}" icon="pi pi-users"
process="#this :form:skillsDialog">
<p:ajax event="dialogReturn" listener="#{mitarbeiterView.update}" update=":form, :form:table"/>
</p:commandButton>
</p:menuitem>
</p:submenu>
</p:menu>
<p:dataTable id="table" var="row" value="#{mitarbeiterView.mitarbeiter}" liveResize="true" resizableColumns="true">
<p:column headerText="Skillset">
<p:commandLink update=":form:skillsDialog, :form:skillsDetails" oncomplete="PF('skillsDialog').show()" title="Detail"
styleClass="ui-icon pi pi-search">
<f:setPropertyActionListener value="#{row}" target="#{mitarbeiterView.selectedEmployee}" />
</p:commandLink>
<p:commandLink action="#{adminView.openNewSkillDialog(row)}" title="add" styleClass="ui-icon pi pi-plus">
<!-- <f:setPropertyActionListener value="#{row}" target="#{skillView.employee}" /> -->
</p:commandLink>
</p:column>
</p:dataTable>
</p:panelGrid>
<p:dialog id="skillsDialog" header="Skillsheet von #{mitarbeiterView.selectedEmployee.vorname} #{mitarbeiterView.selectedEmployee.name}"
showEffect="fade" widgetVar="skillsDialog" modal="true" resizable="true">
<p:outputPanel id="skillsDetails">
<p:dataTable var="skillRow" value="#{mitarbeiterView.selectedEmployee.skills}">
<p:column headerText="Skill">
<h:outputText value="#{skillRow.name}" />
</p:column>
<p:column headerText="Ausprägung">
<h:outputText value="#{skillRow.expertise} - #{skillRow.expertiseString.fullName}" />
</p:column>
<p:column headerText="Beschreibung">
<h:outputText value="#{skillRow.description}" />
</p:column>
</p:dataTable>
</p:outputPanel>
</p:dialog>
</h:form>
Second XHTML, for new employees:
<h:form id="newForm">
<h3>Skillsheet</h3>
<p:panelGrid id="skillPanel" columns="2" cellpadding="5" styleClass="ui-noborder">
<p:column style="width:50px">
<p:commandButton id="openAddSkill" process="#this" action="#{adminView.openNewSkillDialog}"
title="Neuer Skill" icon="pi pi-plus">
<!-- <f:setPropertyActionListener target="#{skillView.employee}" value="#{newEmployeeView.newEmployee}"/> -->
<p:ajax event="dialogReturn" update=":newForm :newForm:skillPanel"/>
</p:commandButton>
</p:column>
</p:panelGrid>
<p:commandButton value="Hinzufügen" id="addSkill" icon="pi pi-plus" action="#{skillView.addSkill()}"/>
</h:form>
AdminView.java:
#Named(value = "adminView")
#ViewScoped
public class AdminView implements Serializable {
private static final long serialVersionUID = 5252224062484767900L;
#Inject
private SkillView skillView;
public void addNewEmployee() {
Map<String, Object> options = new HashMap<String, Object>();
options.put("id", "newEmployeeDialogID");
options.put("widgetVar", "newEmployeeDialogVar");
options.put("resizable", false);
options.put("modal", false);
PrimeFaces.current().dialog().openDynamic("/dialogs/newEmployee", options, null);
}
public void openNewSkillDialog(Mitarbeiter employee) {
Map<String, Object> options = new HashMap<String, Object>();
options.put("resizable", true);
options.put("modal", false);
options.put("contentWidth", 420);
PrimeFaces.current().dialog().openDynamic("/dialogs/skill", options, null);
skillView.setEmployee(employee);
}
}
Skill.java:
public class Skill {
#NotNull(message = "Skill fehlt")
private String name;
#NotNull(message = "Bitte Ausprägung angeben")
private short expertise;
private String description;
private String expertiseFullname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public short getExpertise() {
return expertise;
}
public void setExpertise(short expertise) {
this.expertise = expertise;
}
public String getExpertiseFullname() {
return expertiseFullname;
}
public void setExpertiseFullname(String expertiseFullname) {
this.expertiseFullname = expertiseFullname;
}
public void setExpertise(String fullName) {
try {
this.expertise = Short.valueOf(fullName.substring(0, fullName.indexOf(" - ")));
} catch (Exception e) {
this.expertise = 0;
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Mitarbeiter.java:
public class Mitarbeiter {
private int id;
#NotNull(message = "Nachname fehlt")
private String name;
#NotNull(message = "Vorname fehlt")
private String vorname;
private Date entryDate;
private List<Skill> skills = new ArrayList<Skill>();
private int expertise;
public Mitarbeiter() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public List<Skill> getSkills() {
return skills;
}
public void setSkills(List<Skill> skills) {
this.skills = skills;
}
public int getExpertise() {
return expertise;
}
public void setExpertise(int expertise) {
this.expertise = expertise;
}
MitarbeiterView.java:
#Named(value = "mitarbeiterView")
#ViewScoped
public class MitarbeiterView implements Serializable {
private static final long serialVersionUID = 7924178697538784022L;
#Inject
MitarbeiterService mitarbeiterService;
private List<Mitarbeiter> mitarbeiter;
private Mitarbeiter selectedEmployee;
#PostConstruct
public void init() {
SessionConfig.initSession();
new Commons();
updateMitarbeiter();
}
private void updateMitarbeiter() {
mitarbeiter = new ArrayList<Mitarbeiter>();
List<EmployeeDTO> dtos = Queries.findAllEmployees();
for (EmployeeDTO employeeDTO : dtos) {
mitarbeiter.add(mitarbeiterService.convertToMitarbeiter(employeeDTO));
}
}
public void update() {
updateMitarbeiter();
PrimeFaces.current().ajax().update("form:table");
}
public List<Mitarbeiter> getMitarbeiter() {
return mitarbeiter;
}
public void setMitarbeiter(List<Mitarbeiter> mitarbeiter) {
this.mitarbeiter = mitarbeiter;
}
public void setSelectedEmployee(Mitarbeiter selectedEmployee) {
this.selectedEmployee = selectedEmployee;
}
public Mitarbeiter getSelectedEmployee() {
return selectedEmployee;
}
NewEmployeeView.java:
#Named(value = "newEmployeeView")
#ViewScoped
public class NewEmployeeView implements Serializable {
private static final long serialVersionUID = 789108010781037452L;
#ManagedProperty(value = "#{mitarbeiter}")
private Mitarbeiter newEmployee = new Mitarbeiter();
#PostConstruct
public void init() {
}
public Mitarbeiter getNewEmployee() {
return newEmployee;
}
public void setNewEmployee(Mitarbeiter mitarbeiter) {
this.newEmployee = mitarbeiter;
}
Calling adSkill() from the first XHTML should have the selected employee from the Datatable. In the second case, it should have a freshly created, "empty" employee, which I already provide.
I think that major cause of your problems is that skillView bean is #RequestScoped meaning that it is being constructed and destroyed on each request and thus your employee is being reinitialized/reset to null every time. Check out this accepted answer for details.
Hints that might lead you to solution:
put debug lines in at least init() and setEmployee(..) methods of skillView and observe behaviour,
change scope of skillView to #ViewScoped which will preserve employee object across multiple Ajax requests

why the form is submitted by the SelectOneMenu instead of the submit button

my pb is that when I select an item to display items in the second selectOneMenu () the submit button does not work.
at the second click the button tries to submit the form but (this action emptie the second SOM) as the second SelectOneMenu becomes empty its trigger a validation error.
primefaces 6.1
jsf2.2
tomcat8.5
<h:form id="create_intervention_form">
<h:messages id="errorMessages" style="color:red;margin:8px;" />
<h:panelGroup id="addProjet2" rendered="true">
<table>
<tr>
<td><h:outputLabel value="Structure à visiter:" for="Client2">
</h:outputLabel></td>
<td><p:selectOneMenu id="Client2"
value="#{creerintervention.selected_client}" effect="fade"
style="width:100px" filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{creerintervention.list_client}" var="cl"
itemValue="#{cl}" itemLabel="#{cl.nom_client}" />
<f:converter converterId="ClientConverter" />
<p:ajax update="create_intervention_form:station1_client"
listener="#{creerintervention.getStructureByClient}"
process="Client2" />
</p:selectOneMenu> <p:selectOneMenu id="station1_client"
value="#{creerintervention.selectedStation}" style="width:100px"
filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{creerintervention.list_Station}"
var="entry1" itemValue="#{entry1}" itemLabel="#{entry1.nom_stat}" />
<f:converter converterId="StationConverter" />
<p:ajax partialSubmit="false" />
</p:selectOneMenu></td>
</tr>
<tr>
<p:commandButton value="Valider" pdate="create_intervention_form"
id="valide" actionListener="#{creerintervention.addOdm}"
styleClass="ui-priority-primary" />
</tr>
</table>
</h:panelGroup>
</h:form>
ManagedBean
#RequestScoped
#Management(name = "creerintervention")
public class CreerIntervention {
private String matricule;
private agentService agentservice = new agentServiceImpl();
private usersService usersService = new usersServiceImpl();
private clientService clientService = new clientServiceImpl();
private List<client> list_client;
private List<station> list_Station;
private List<SelectItem> clientList;
//private Map<String, String> clientList;
//private Map<String, String> StationList;
private List<SelectItem> StationList;
private station selectedStation;
private client Selected_client;
{
//*** initialiser la liste des client dans le SelectOnMenu
list_client = clientService.findAll();
}
public void getStructureByClient()
{
// ######## Préparer la liste des nom des clients ######## //
list_Station=stationService.findByRefClient(getSelected_client().getRef());
log.info("La refernce du client est ---"+ Selected_client.getRef());
log.info("LES STIONS SONT D UN NBR DE ---"+ list_Station.size());
}
public void addOdm(ActionEvent e)
{
log.info("Matricule:" + matricule) ;
log.info("destination:" +destination);
log.info("client:"+Selected_client.getNom_client()) ;
log.info("station:"+ selectedStation.getNom_stat());
log.info("objet mission:"+ obj_mission );
log.info("date depart:"+ date_dep );
log.info("date ret:"+ date_retour );
log.info("moyen transp:"+ moyen_transport) ;
log.info("imma:"+ immatriculation) ;
log.info("prise en charge :"+ prise_en_charge) ;
log.info("struct:"+ structure) ;
}
.....
Setters and Getters...
I have get the solution ; the problem was in the Scope the right one is #ViewScoped.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h:form id="create_intervention_form">
<h:messages id="errorMessages" style="color:red;margin:8px;" />
<table>
<tr>
<td><p:outputLabel value="Matricule:" for="Matricule" /></td>
<td><p:inputText id="Matricule"
value="#{teststation.matricule}" size="5" /></td>
</tr>
<tr>
<td><h:outputLabel value="Structure à visiter:" for="Client2"></h:outputLabel> </td>
<td>
<p:panel id="st">
<p:selectOneMenu id="Client2" value="#{teststation.selected_client}">
<f:selectItems value="#{teststation.list_client}" var="cl" itemValue="#{cl}" itemLabel="#{cl.nom_client}" />
<f:converter converterId="ClientConverter" />
<p:ajax update="station1_client" listener ="#{teststation.getStructureByClient}" />
</p:selectOneMenu>
<p:selectOneMenu id="station1_client" value="#{teststation.selectedStation}" >
<f:attribute name="selected_station" value="#{teststation.selectedStation}" />
<f:selectItems value="#{teststation.list_Station}" var="entry1" itemValue="#{entry1}" itemLabel="#{entry1.nom_stat}" />
<f:converter converterId="StationConverter" />
</p:selectOneMenu>
</p:panel>
</td>
</tr>
<tr>
<td><h:outputLabel value="Immatriculation:" for="imma"></h:outputLabel> </td>
<td><p:inputText size="20" value="#{teststation.immatriculation}" id="imma"></p:inputText></td>
</tr>
<tr>
<p:growl id="growl" life="2000" />
<td></td>
<td><p:commandButton value="Valider" id="valide" update="errorMessages" actionListener="#{teststation.addOdm}" styleClass="ui-priority-primary" />
</td>
</tr>
</table>
</h:form>
</h:body>
</html>
the ManagedBean
#ViewScoped
#ManagedBean(name = "teststation")
public class TestStation {
private String matricule;
private stationService stationService = new stationServiceImpl();
private clientService clientService = new clientServiceImpl();
public static Logger log = LogManager.getLogger(CreerIntervention.class.getName());
private String nom;
private String client_name;
private List<client> list_client;
private List<station> list_Station;
private List<SelectItem> clientList;
//private Map<String, String> clientList;
//private Map<String, String> stationList;
private List<SelectItem> stationList;
private String immatriculation;
private String ref_Selected_client;
private String Nom_Selected_client;
private String ref_Selected_station;
private String Nom_Selected_station;
private List<station> station;
private station selectedStation;
private client Selected_client;
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
Map<String, String> selectedStationParam= fc.getExternalContext().getRequestParameterMap();
#PostConstruct
public void initMyBean()
{
log.info("ici PosteConstract"+this.getClass().hashCode());
}
public TestStation()
{
super();
log.info("ici Constract "+this.getClass().hashCode());
}
{
list_client = clientService.findAll();
}
public void updateSelectedStation()
{
log.info("LES updateSelectedStatio ---"+ list_Station.get(0).getNom_stat());
}
public void getStructureByClient()
{
log.info("La refernce du client selectioné est --- "+ Selected_client.getRef());
list_Station=stationService.findByRefClient(getSelected_client().getRef());
stationList= new ArrayList<>();
for (station o : list_Station)
{
stationList.add(new SelectItem(o.getNom_stat(),o.getRef_stat()));
}
log.info("LES STIONS SONT D UN NBR DE ---"+ list_Station.get(0).getNom_stat());
}
public void addOdm()
{ Nom_Selected_station=selectedStation.getNom_stat();
//log.info("num_odm :" + num_odm) ;
log.info("Matricule:" + matricule) ;
log.info("client:"+Selected_client.getNom_client()) ;
log.info("station:"+ Nom_Selected_station);
log.info("imma:"+ immatriculation) ;
}
public void addMessage(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
public void cancelAction(ActionEvent e)
{
log.info("etat valeur ShowForm555 = ");
}
public String getMatricule() {
return matricule;
}
public void setMatricule(String matricule) {
this.matricule = matricule;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getNom_Selected_client() {
return Nom_Selected_client;
}
public void setNom_Selected_client(String nom_Selected_client) {
Nom_Selected_client = nom_Selected_client;
}
public String getRef_Selected_client() {
return ref_Selected_client;
}
public void setRef_Selected_client(String Ref_Selected_client) {
this.ref_Selected_client = Ref_Selected_client;
}
public String getClient_name() {
return client_name;
}
public void setClient_name(String client_name) {
this.client_name = client_name;
}
/*public Map<String, String> getClientList() {
return clientList;
}
public void setClientList(Map<String, String> clientList) {
this.clientList = clientList;
}
public List<client> getList_client() {
return list_client;
}
public void setList_client(List<client> list_client) {
this.list_client = list_client;
}*/
public String getImmatriculation() {
return immatriculation;
}
public void setImmatriculation(String immatriculation) {
this.immatriculation = immatriculation;
}
public List<station> getStation() {
return station;
}
public void setStation(List<station> station) {
this.station = station;
}
/*public List<station> getList_Station() {
return list_Station;
}
public void setList_Station(List<station> list_Station) {
this.list_Station = list_Station;
}*/
/*public Map<String, String> getStationList() {
return stationList;
}
public void setStationList(Map<String, String> stationList) {
stationList = stationList;
}*/
public void setClientList(List<SelectItem> clientList) {
this.clientList = clientList;
}
public List<SelectItem> getStationList() {
return stationList;
}
public void setStationList(List<SelectItem> stationList) {
this.stationList = stationList;
}
public List<SelectItem> getClientList() {
return clientList;
}
public station getSelectedStation() {
return selectedStation;
}
public void setSelectedStation(station selectedStation) {
this.selectedStation = selectedStation;
}
public client getSelected_client() {
return Selected_client;
}
public void setSelected_client(client selected_client) {
Selected_client = selected_client;
}
public List<client> getList_client() {
return list_client;
}
public void setList_client(List<client> list_client) {
this.list_client = list_client;
}
public List<station> getList_Station() {
return list_Station;
}
public void setList_Station(List<station> list_Station) {
this.list_Station = list_Station;
}
public String getRef_Selected_station() {
return ref_Selected_station;
}
public void setRef_Selected_station(String ref_Selected_station) {
this.ref_Selected_station = ref_Selected_station;
}
public String getNom_Selected_station() {
return Nom_Selected_station;
}
public void setNom_Selected_station(String nom_Selected_station) {
Nom_Selected_station = nom_Selected_station;
}
}
the StationConverter
#FacesConverter("StationConverter")
public class StationConverter implements Converter {
public static Logger log = LogManager.getLogger(StationConverter.class.getName());
stationService statServ = new stationServiceImpl();
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
log.info("4- submitted value for Station Converter ********** "+submittedValue);
log.info("5- returned Object for Station Converter ********** "+statServ.findByRef(submittedValue).getNom_stat());
return statServ.findByRef(submittedValue);
} catch (NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Client ID"));
}}
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
log.info(modelValue.getClass());
if (modelValue instanceof station ) {
log.info( "6- la valeur en String Converter Station est ****** "+String.valueOf(((station) modelValue).getNom_stat()));
return String.valueOf(((station) modelValue).getRef_stat());
} else {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Station instance"));
}
}
}

p:dataTable single row selection

I have a problem selecting a row from a datatable in PrimeFaces. My selected object in the managed bean is null. For some reason, selected object from the datatable is not setting up correctly the property selectedItinerary in my managed bean.
<p:dataTable id="singleDT" value="#{travellerSearchFlightsManagedBean.searchList}" var="s" selectionMode="single" selection="#{travellerSearchFlightsManagedBean.selectedItinerary}" rowKey="#{s.iden}" >
<f:facet name="header">
Found itineraries
</f:facet>
<p:column headerText="Departure Location">
<h:outputText value="#{s.departureLocation}" />
</p:column>
<p:column headerText="Arrival Location">
<h:outputText value="#{s.arrivalLocation}" />
</p:column>
<p:column headerText="Departure Date">
<h:outputText value="#{s.departureDate}" />
</p:column>
<p:column headerText="Cost">
<h:outputText value="#{s.cost}" />
</p:column>
<p:column headerText="Stops">
<h:outputText value="#{s.stopPrint}" />
</p:column>
<f:facet name="footer">
<p:commandButton process="singleDT" value="Reserve itinerary" action="#{travellerSearchFlightsManagedBean.reserveFlight()}" />
</f:facet>
</p:dataTable>
and the managed bean is like this:
#Named(value = "travellerSearchFlightsManagedBean")
#RequestScoped
public class travellerSearchFlightsManagedBean{
#EJB
private itineraryTravellerFacadeLocal itineraryTravellerFacade;
#EJB
private itineraryFacadeLocal itineraryFacade;
#ManagedProperty(value="#{travellerLoginManagedBean}")
private travellerLoginManagedBean loginBean;
private String departureLocation;
private String arrivalLocation;
private Date departureDate;
private int departureHour;
private int departureMinute;
private int numPassengers;
private int maxStops;
private String economyOrBusiness;
private ArrayList<itineraryDTO> itinerariesList;
private ArrayList<itineraryTraveller> searchList;
private itineraryTraveller selectedItinerary;
private String stopPrint;
private static final Logger LOG = Logger.getLogger(travellerSearchFlightsManagedBean.class.getName());
public String getStopPrint() {
return stopPrint;
}
public travellerLoginManagedBean getLoginBean() {
return loginBean;
}
public void setLoginBean(travellerLoginManagedBean loginBean) {
this.loginBean = loginBean;
}
public void setStopPrint(String stopPrint) {
this.stopPrint = stopPrint;
}
public itineraryTraveller getSelectedItinerary() {
return selectedItinerary;
}
public void setSelectedItinerary(itineraryTraveller selectedItinerary) {
this.selectedItinerary = selectedItinerary;
}
public ArrayList<itineraryTraveller> getSearchList() {
return searchList;
}
public void setSearchList(ArrayList<itineraryTraveller> searchList) {
this.searchList = searchList;
}
public ArrayList<itineraryDTO> getItinerariesList() {
return itinerariesList;
}
public void setItinerariesList(ArrayList<itineraryDTO> itinerariesList) {
this.itinerariesList = itinerariesList;
}
public itineraryFacadeLocal getItineraryFacade() {
return itineraryFacade;
}
public String getEconomyOrBusiness() {
return economyOrBusiness;
}
public void setEconomyOrBusiness(String economyOrBusiness) {
this.economyOrBusiness = economyOrBusiness;
}
public void setItineraryFacade(itineraryFacadeLocal itineraryFacade) {
this.itineraryFacade = itineraryFacade;
}
public String getDepartureLocation() {
return departureLocation;
}
public void setDepartureLocation(String departureLocation) {
this.departureLocation = departureLocation;
}
public String getArrivalLocation() {
return arrivalLocation;
}
public void setArrivalLocation(String arrivalLocation) {
this.arrivalLocation = arrivalLocation;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public int getDepartureHour() {
return departureHour;
}
public void setDepartureHour(int departureHour) {
this.departureHour = departureHour;
}
public int getDepartureMinute() {
return departureMinute;
}
public void setDepartureMinute(int departureMinute) {
this.departureMinute = departureMinute;
}
public int getNumPassengers() {
return numPassengers;
}
public void setNumPassengers(int numPassengers) {
this.numPassengers = numPassengers;
}
public int getMaxStops() {
return maxStops;
}
public void setMaxStops(int maxStops) {
this.maxStops = maxStops;
}
public travellerSearchFlightsManagedBean() {
}
public void searchFlights(){
try{
int numPassengersEconomy=0;
int numPassengersBusiness=0;
if (economyOrBusiness.equals("Economy")){
numPassengersEconomy=numPassengers;
}else{
numPassengersBusiness=numPassengers;
}
searchList = new ArrayList<itineraryTraveller>();
itinerariesList= new ArrayList<itineraryDTO>();
int id=itineraryFacade.findItineraries(itinerariesList,departureLocation, arrivalLocation,departureDate,numPassengersEconomy, numPassengersBusiness);
searchList=itineraryFacade.listItineraries(maxStops,itinerariesList,arrivalLocation, departureLocation, numPassengersEconomy, numPassengersBusiness);
} catch(NullPointerException e) {}
}
public void reserveFlight(){
//if (){
try{
//status reserved when traveller reserves an itinerary
selectedItinerary.setStatus('r');
//set the userName from the user who reserved this itinerary before persist it in a shared among all users db
//persist the reserved itinerary in the db
itineraryTravellerFacade.create(selectedItinerary);
} catch(NullPointerException e) {}
}
}

primefaces not show dataTable values with lazyModel

I'm starting with primefaces and I try use LazyModel in p:dataTable.
I already implemented the LazyModel, bean and jsf. The call's to bean and model occur's correctly and my bean return a list with elements, but my jsf show nothing.
Please, somebody know whats happen?
Bellow is my code:
JSF:
<ui:composition template="./newTemplate.xhtml">
<ui:define name="content">
content
<h:form>
<p:panel id="formFiltro">
<p:messages id="messages"/>
<h:panelGrid>
<h:outputLabel for="fieldConta" value="Número da Conta:"/>
<p:inputText id="fieldConta" value="#{log.nrConta}" label="Número da Conta">
<f:convertNumber integerOnly="true" type="number"/>
</p:inputText>
<!--<p:message for="fieldConta" />-->
<h:outputLabel for="fieldAgencia" value="Código da Agência:"/>
<p:inputText id="fieldAgencia" value="#{log.nrAgencia}" label="Código da Agência">
<f:convertNumber integerOnly="true" type="number"/>
</p:inputText>
<!--<p:message for="fieldAgencia" />-->
<center>
<p:commandButton ajax="false" value="Pesquisar" action="#{log.search}" />
</center>
</h:panelGrid>
</p:panel>
<p:dataTable var="l" value="#{log.lazyLogModel}" paginator="true" rows="5"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" id="logTable" lazy="true">
<p:column headerText="ID">
<h:outputText value="#{l.logId}" />
</p:column>
<p:column headerText="Agência">
<h:outputText value="#{l.logAgencia}" />
</p:column>
<p:column headerText="Conta">
<h:outputText value="#{l.logConta}" />
</p:column>
<p:column headerText="SO">
<h:outputText value="#{l.logSo}" />
</p:column>
<p:column headerText="Plugin">
<h:outputText value="#{l.logVersaoPlugin}" />
</p:column>
<p:column headerText="Tam F10">
<h:outputText value="#{l.logTamF10}" />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
My bean:
#ManagedBean(name="log")
#RequestScoped
public class consultaJsf implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of consultaJsf
*/
private List<TbLogLog> listaLog;
private LazyLogModel lazyLogModel;
private int nrConta;
private int nrAgencia;
public consultaJsf() {
try{
//this.listaLog = new ConsultarDados().getListLogAll();
}catch(Exception e){
e.printStackTrace();
}
}
#PostConstruct
public void init()
{
this.lazyLogModel = new LazyLogModel();
}
public List<TbLogLog> getListaLog()
{
return listaLog;
}
public int getNrConta()
{
return nrConta;
}
public void setNrConta(int nrConta)
{
this.nrConta = nrConta;
}
public int getNrAgencia()
{
return nrAgencia;
}
public void setNrAgencia(int nrAgencia)
{
this.nrAgencia = nrAgencia;
}
public LazyLogModel getLazyLogModel()
{
return this.lazyLogModel;
}
public String search() throws Exception
{
if(nrConta != 0)
this.listaLog = new ConsultarDados().getListLogByConta(nrConta);
else if(nrAgencia != 0)
this.listaLog = new ConsultarDados().getListLogByAgencia(nrAgencia);
return null;
}
}
My LazyModel:
public class LazyLogModel extends LazyDataModel<TbLogLog> {
private String nrConta;
private String cdAgencia;
#Override
public List<TbLogLog> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
List<TbLogLog> listaLog = null;
try{
listaLog = new ConsultarDados().getListLogAll(first, pageSize);
}catch(Exception e){
return null;
}
return listaLog;
}
/**
* #return the nrConta
*/
public String getNrConta() {
return nrConta;
}
/**
* #param nrConta the nrConta to set
*/
public void setNrConta(String nrConta) {
this.nrConta = nrConta;
}
/**
* #return the cdAgencia
*/
public String getCdAgencia() {
return cdAgencia;
}
/**
* #param cdAgencia the cdAgencia to set
*/
public void setCdAgencia(String cdAgencia) {
this.cdAgencia = cdAgencia;
}
}
Consult Method called by LazyModel:
private List<TbLogLog> getListLog(String hql, int firstResult, int sizePage) throws Exception {
List resultList = null;
try {
Session session = HubernateUtil.getSessionFactory().openSession();
if ((hql == null) || (hql.trim().length() == 0)) {
hql = QUERY_PESQUISAR_TODOS;
}
Query q = session.createQuery(hql);
if(firstResult > 0 )
q.setFirstResult(firstResult);
if(sizePage > 0)
q.setMaxResults(sizePage);
resultList = q.list();
} catch (HibernateException he) {
he.printStackTrace();
}
return resultList;
}
Everything work's fine, but my jsf don't show any result.
Thanks in advance.
Remove the init() in consultaJsf Class and update the getLazyLogModel() as follows
#ManagedBean(name="log")
#RequestScoped
public class consultaJsf implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of consultaJsf
*/
private List<TbLogLog> listaLog;
private LazyLogModel<TbLogLog> lazyLogModel;
private int nrConta;
private int nrAgencia;
public consultaJsf() {
try{
//this.listaLog = new ConsultarDados().getListLogAll();
}catch(Exception e){
e.printStackTrace();
}
}
public List<TbLogLog> getListaLog()
{
return listaLog;
}
public int getNrConta()
{
return nrConta;
}
public void setNrConta(int nrConta)
{
this.nrConta = nrConta;
}
public int getNrAgencia()
{
return nrAgencia;
}
public void setNrAgencia(int nrAgencia)
{
this.nrAgencia = nrAgencia;
}
public LazyLogModel<TbLogLog> getLazyLogModel()
{
if (lazyLogModel== null) {
lazyLogModel= new LazyDataModel<TbLogLog>() {
#Override
public List<TbLogLog> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, String> filters) {
List<TbLogLog> listaLog = null;
try{
listaLog = new ConsultarDados().getListLogAll(first, pageSize);
}catch(Exception e){
return null;
}
return listaLog;
}
};
}
return listaLog;
}
public String search() throws Exception
{
if(nrConta != 0)
this.listaLog = new ConsultarDados().getListLogByConta(nrConta);
else if(nrAgencia != 0)
this.listaLog = new ConsultarDados().getListLogByAgencia(nrAgencia);
return null;
}
}

JSF dataTable and fileUpload (fileupload issue)

Please let me know your suggestion. I want to build fileUpload with specific design and having issue with getting hold of the uploadedFile.
My design:
DataModel class:
#Named
#SessionScoped
public class NJDataModel implements Serializable {
private static final long serialVersionUID = 1L;
private String sectionName;
private UploadedFile file;
public NJDataModel(String sectionName) {
this.sectionName = sectionName;
}
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
}
Data class:
#ManagedBean(name = "NJData")
#SessionScoped
public class Data implements Serializable {
private static final long serialVersionUID = 1L;
private List<NJDataModel> dataModel;
#PostConstruct
public void init() {
/** defaults */
dataModel = new ArrayList<NJDataModel>();
dataModel.add(new NJDataModel("Title page"));
}
public void upload() {
System.out.println("upload method triggered");
String msg = null;
for (NJDataModel i : dataModel) {
UploadedFile file = i.getFile();
// ERROR: file is always null? so could not get hold of file
if (file != null) {
System.out.println("Uploaded file:" + file.getFileName());
msg += "file:" + file.getFileName() + "size:" + file.getSize() + ", ";
}
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg));
}
}
XHTML:
<p:dataTable var="item" value="#{NJData.dataModel}"
draggableColumns="true">
<p:column>
<p:panel>
<f:facet name="header">
<h:outputText value="#{item.sectionName}" />
</f:facet>
<p:fileUpload value="#{item.file}" mode="simple" />
</p:panel>
</p:column>
</p:dataTable>
<p:commandButton value="Submit" ajax="false"
actionListener="#{NJData.upload}" />
And finally, i need to get hold of file in method: NJData.upload() - where i always get null?
My console output:
file object:null & section name:first page
file object:null & section name:second page

Resources