How to add dynamic progress bars in each file downloaded using Primefaces - jsf-2

I'm trying to develop a program using Primefaces that downloads all the images in a given URL. I've already successfully downloaded and it works fine but i need to add a functionality wherein i need to see the progress of all files being downloaded. Each file must have it's own progress bar. Also, one of the problems is having to create dynamic progress bars based on the files downloaded.
This is what i've come up so far.
#ManagedBean
public class CheckValidUrl {
private static final String FOLDERPATH = "C:/Users/jan.louise.h.casas/Downloads/";
private static final String IMAGE_PATTERN = "([^\\s]+(\\.(?i)(jpg|png|jpeg|ico|bmp))$)";
private Pattern pattern;
private Matcher matcher;
private String url;
private Integer progress;
private static boolean progressBarRendered;
private List<String> imagesList = new ArrayList<String>();
public List<String> getImagesList() {
return imagesList;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getProgress() {
return progress;
}
public void setProgress(Integer progress) {
this.progress = progress;
}
public boolean isProgressBarRendered() {
return progressBarRendered;
}
public void cancel(){
progress = null;
}
public void onComplete() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Progress Completed"));
}
public void validateUrl() throws IOException {
UrlValidator urlValidator = new UrlValidator();
if(!urlValidator.isValid(url)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Please make sure URL is valid"));
} else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "Please wait"));
downloadImages();
}
}
public void downloadImages(){
try{
Document doc = Jsoup.connect(url).get();
Elements img = doc.getElementsByTag("img");
if(img.size() > 0){
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("Image Found!");
System.out.println("src attribute is : "+src);
pattern = Pattern.compile(IMAGE_PATTERN);
if(validateImageType(src)){
imagesList.add(src);
}
}
if(!imagesList.isEmpty()){
getImages(imagesList);
} else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning", "URL only has GIFs"));
}
} else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning", "URL doesn't have any images"));
}
} catch(FileNotFoundException ex){
System.err.println("There was an error");
Logger.getLogger(CheckValidUrl.class.getName()).log(Level.SEVERE, null, ex);
} catch(IOException ex){
System.err.println("There was an error");
Logger.getLogger(CheckValidUrl.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void getImages(List<String> imageSources) throws FileNotFoundException, IOException {
for(String src : imageSources){
int indexname = src.lastIndexOf("/");
if (indexname == src.length()) {
src = src.substring(1, indexname);
}
indexname = src.lastIndexOf("/");
String name = src.substring(indexname, src.length());
System.out.println(name);
URL url = new URL(src);
InputStream in = url.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream( FOLDERPATH+ name));
for (int b; (b = in.read()) != -1;) {
progressBarRendered = true;
out.write(b);
System.out.println("Downloaded image: "+src);
System.out.println("Boolean Value: "+progressBarRendered);
}
out.close();
in.close();
}
}
public boolean validateImageType(String image){
pattern = Pattern.compile(IMAGE_PATTERN);
matcher = pattern.matcher(image);
return matcher.matches();
}
}
and in my check_valid_url.xhtml
<p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" />
<h:panelGrid columns="3" cellpadding="5">
<p:outputLabel for="url" value="Url:" />
<p:inputText id="url" value="#{checkValidUrl.url}" required="true" label="Url" />
<p:message for="url" display="icon" />
<p:commandButton value="Submit" update="progressBarPanel" actionListener="#{checkValidUrl.validateUrl}" onclick="PF('pbAjax').start()" icon="ui-icon-check" />
</h:panelGrid>
<h:panelGrid id="progressBarPanel">
<p:progressBar widgetVar="pbAjax" ajax="true" rendered="#{checkValidUr.progressBarRendered}" value="#{checkValidUrl.progress}" labelTemplate="{value}%" styleClass="animated" global="false">
<p:ajax event="complete" listener="#{checkValidUrl.onComplete}" update="panel"/>
</p:progressBar>
</h:panelGrid>
</p:panel>
</h:form>

Related

Assigning one of a <p:selectOneMenu> item in java object

I have a list of governorates that I displayed in a <p:selectOneMenu>
the java code in the managed bean:
public List<SelectItem> gouvernorats() {
List<Gouvernorat> all = emetteursEJB.findAllGouvernorat();
List<SelectItem> items = new ArrayList<>();
for (Gouvernorat g : all) {
items.add(new SelectItem(g, g.getLibelleGouv()));
}
return items;
}
in the <p:selectOneMenu> I add <p:ajax>:
<p:selectOneMenu value="#{emetteurBean.selectedGouvernorat}" style="width:160px" >
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{emetteurBean.gouvernorats()}" />
<p:ajax event="change" listener="#{emetteursBean.handelGouvChanged()"/>
</p:selectOneMenu>
in the method handelGouvChanged() selectedGouvernorat object is always null;
Recently I added the convert I stumbled upon NullPointerException
#FacesConverter(forClass = Gouvernorat.class)
public class EmetteursConverter implements Converter {
#EJB
private ReferentielDaoLocal refEJB;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String selectedValue) {
System.out.println("Inside The Converter");
System.out.println(selectedValue.length());
if (selectedValue == null) {
return null;
} else {
return refEJB.findGouvByCode(selectedValue.trim());
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return null;
} else {
return String.valueOf(((Gouvernorat) value).getIdGouvernorat());
}
}
}
I found a solution, I injected EJB with InitilContext.lookup ()
#FacesConverter(forClass = Gouvernorat.class)
public class GouvernoratConverter implements Converter {
private static final Logger LOG = Logger.getLogger(GouvernoratConverter.class.getName());
#Override
public Object getAsObject(FacesContext context, UIComponent component, String selectedValue) {
if (selectedValue == null) {
return null;
} else {
try {
ReferentielDaoLocal myService = (ReferentielDaoLocal) new
InitialContext().lookup("java:global/ErpCCF/ErpCCF-ejb/ReferentielDaoImpl");
return myService.findGouvByCode(selectedValue);
} catch (NamingException ex) {
LOG.log(Level.SEVERE, "Converter Gouvernorat Error", ex.getMessage());
return null;
}
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return null;
} else {
return String.valueOf(((Gouvernorat) value).getIdGouvernorat());
}
}
}

PrimeFaces Export data from a Lazyloading DataTable

I want to export a dataTable (with Pagination) having LazyLoad DataModel during Report Generation.
Problem :
When I export, the report is getting generated page by page from Database and then getting exported to Excel/PDF that consumes more time. I would like to get it in a single database access by skipping the page by page generation of dataset.
I'm producing my code snippet as follows:
JSF:
<p:dataTable id="dTable" var="dev" value="#{ReportAction.lazyModel}"
styleClass ="table_paginator" rowKey="#{device.macAddress}" paginatorPosition="bottom"
paginator="true" rowsPerPageTemplate="10,20,30" rows="10" lazy="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
emptyMessage="Select appropriate conditions and click 'Generate Report'">
<f:facet name="header">
<h:commandLink actionListener="#{ReportAction.doExport}">
<p:graphicImage value="../../../resources/images/excel.png"
alt="XLS" style="float:right;width:32px;height:32px" />
<p:dataExporter type="xls" target="dTable" fileName="#{ReportAction.fileName}"
preProcessor="#{ReportAction.preProcess}"
postProcessor="#{ReportAction.postProcessXLS}" />
</h:commandLink>
</f:facet>
<!-- All the columns in Data Table -->
</p:dataTable>
Managed Bean:
public class ReportAction {
private ConfigurationReportDataModel mediumConfigModel;
private List<FieldReportModel> configModelList;
private String fileName;
private LazyDataModel<ConfigurationReportModel> lazyModel;
private boolean export;
public ReportAction() {
configModelList = new ArrayList<ConfigurationReportModel>();
export = false;
mediumConfigModel = new ReportDataModel();
}
public void generateFieldReport() {
lazyFieldModel = new ConfigurationReportDataModel(day, fromDate,
location,store,engineer, status, toDate, export);
}
public void preProcess(Object document) {
export = true;
log.info("preProcess::Lazy model : Page Sizing");
if(lazyFieldModel != null) {
lazyFieldModel.setPageSize(1000000);
}
log.info("preProcess::Export All Details");
mediumConfigModel.setExport(true);
}
public void postProcessXLS(Object document) {
HSSFWorkbook wb = (HSSFWorkbook) document;
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow header = sheet.getRow(0);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GREEN.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
HSSFCell cell = header.getCell(i);
cell.setCellValue(cell.getStringCellValue().toUpperCase());
cell.setCellStyle(cellStyle);
sheet.autoSizeColumn(i);
}
export = false;
mediumConfigModel.setExport(false);
}
public List<ConfigurationReportModel> getConfigModelList() {
return configModelList;
}
public void setConfigModelList(
ArrayList<ConfigurationReportModel> configModelList) {
this.configModelList = configModelList;
}
public String getFileName() {
SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy_HHmmss");
fileName = "Config_Report_".concat(formatter.format(new Date()));
return fileName;
}
public void setMediumConfigModel(
ConfigurationReportDataModel mediumConfigModel) {
this.mediumConfigModel = mediumConfigModel;
}
public void setConfigModelList(
List<ConfigurationReportModel> configModelList) {
this.configModelList = configModelList;
}
public LazyDataModel<ConfigurationReportModel> getLazyFieldModel() {
log.info("##########getLazyFieldModel###########");
if(export) {
log.info("getLazyFieldModel::Will get Exported........");
lazyFieldModel = new ConfigurationReportDataModel(day, fromDate,
location, store, engineer, status, toDate, true);
lazyFieldModel.load(1, 1000000000, null, null, null);
}
return lazyFieldModel;
}
public void setLazyFieldModel(
LazyDataModel<ConfigurationReportModel> lazyFieldModel) {
this.lazyFieldModel = lazyFieldModel;
}
}
DataModel:
public class ConfigurationReportDataModel extends
LazyDataModel<ConfigurationReportModel> {
private List<ConfigurationReportModel> configReport;
private boolean export;
public ConfigurationReportDataModel() {
this.export = false;
}
public List<ConfigurationReportModel> load(int first, int pageSize,
String sortField, SortOrder sortOrder, Map<String, String> filters) {
UIClient client = new UIClient();
ReportData data = null;
// ///////////////////
if(export) {
log.info("Do Export....");
first = 1;
pageSize = 1000000000;
}
deviceList = new ArrayList<DeviceGlobal>();
// Retrieves data from Database with the number of record (page size)
data = client.generateFieldReport(first, pageSize,
Integer.parseInt(location), Integer.parseInt(store),
engineer, getTimeToBeginningOfDay(), getTimeToEndofDay(),
status);
log.info("Obtained data : " + data);
if (data != null) {
log.info("Got devices : " + data.getRecords().size());
deviceList = (ArrayList<DeviceGlobal>) data.getRecords();
// ///////////////////
int record = first + 1;
ConfigurationReportModel storeModel = null;
DeviceGlobal deviceGlobal = null;
configReport = new ArrayList<ConfigurationReportModel>();
for (Iterator<DeviceGlobal> iterator = deviceList.iterator(); iterator
.hasNext();) {
deviceGlobal = (DeviceGlobal) iterator.next();
storeModel = new ConfigurationReportModel(deviceGlobal,
record++);
configReport.add(storeModel);
}
log.info("Total Config Report : " + configReport.size());
// rowCount
int dataSize = data.getReportCount();
this.setRowCount(dataSize);
log.info("Report Count: " + data.getReportCount());
if(export) {
return configReport;
}
else {
// paginate
if (dataSize > pageSize) {
try {
return configReport;
} catch (IndexOutOfBoundsException e) {
return configReport;
}
} else {
return configReport;
}
}
} else {
log.info("Got no devices");
deviceList = new ArrayList<DeviceGlobal>();
configReport = new ArrayList<ConfigurationReportModel>();
this.setRowCount(0);
return configReport;
}
}
}
Note:
There's no syntax error.
All the custom type classes are defined.
How do I get the Excel report by skipping the page by page generation of records?
You have to add pageOnly="false" to dataExporter
for zero devision issue just override an extra LaztDataModel method as given below.
#Override
public void setRowIndex(int rowIndex) {
// TODO Auto-generated method stub
if (rowIndex == -1 || getPageSize() == 0) {
super.setRowIndex(-1);
}
else
super.setRowIndex(rowIndex % getPageSize());
}

PrimeFaces DataTable with required Radiobutton

I am using PrimeFaces DataTable with Radiobuttons inside a one wizard tab. Is possible to somehow set Radiobuttons like required?
User shouldn't go to the next wizard tab until he will choose one option in DataTable with Radiobuttons.
Or have you any ideas how to resolve this problem? Thanks for any replies!
JSP page
<p:tab id="test" title="Test">
<p:panel header="Term page">
<p:dataTable id="collection" value="#{register.dataList}" var="dl" rowKey="#{dl.c_id}" selection="#{register.selectedTerm}"">
<p:column selectionMode="single" style="width:2%" />
<p:column>
#{dl.c_id}
</p:column>
</p:dataTable>
</p:panel>
</p:tab>
You can check for data selection in flowListener of <p:wizard> tag that is triggered when next/previous buttons are clicked and conditionally add FacesMessage:
public String onFlowProcess(FlowEvent event) {
String current = event.getOldStep();
String next = event.getNewStep();
boolean proceed = true;
if(current.equals("first") && next.equals("second") && (selectedData == null)) {
//proceed only when data was selected and user is moving to the next step
FacesMessage facesMessage = new FacesMessage("You need to make a selection in a datatable to proceed!");
FacesContext.getCurrentInstance().addMessage("form:selection", facesMessage);
proceed = false;
}
return proceed ? next : current;
}
The full example is provided below.
The view:
<h:form id="form">
<p:wizard widgetVar="wiz" flowListener="#{q16439053Bean.onFlowProcess}">
<p:tab id="first" title="First">
<p:message for="selection"/>
<p:panel id="selection" header="Term page">
<p:dataTable id="collection" value="#{q16439053Bean.list}" var="data" rowKey="#{data.name}" selection="#{q16439053Bean.selectedData}">
<p:column selectionMode="single" style="width:2%" />
<p:column>
#{data.name}
</p:column>
</p:dataTable>
</p:panel>
</p:tab>
<p:tab id="second" title="Second">
Done!
</p:tab>
</p:wizard>
</h:form>
The bean:
#ManagedBean
#ViewScoped
public class Q16439053Bean implements Serializable {
private List<Data> list;
private Data selectedData;
public List<Data> getList() {
return list;
}
public void setList(List<Data> list) {
this.list = list;
}
public Data getSelectedData() {
return selectedData;
}
public void setSelectedData(Data selectedData) {
this.selectedData = selectedData;
}
public class Data {
private String name;
private String value;
public Data() {
}
public Data(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public Q16439053Bean() {
list = new ArrayList<Data>();
Data d;
d = new Data("name", "value");
list.add(d);
d = new Data("name1", "value1");
list.add(d);
d = new Data("name2", "value2");
list.add(d);
d = new Data("name3", "value3");
list.add(d);
}
public String onFlowProcess(FlowEvent event) {
String current = event.getOldStep();
String next = event.getNewStep();
boolean proceed = true;
if(current.equals("first") && next.equals("second") && (selectedData == null)) {
FacesMessage facesMessage = new FacesMessage("You need to make a selection in a datatable to proceed!");
FacesContext.getCurrentInstance().addMessage("form:selection", facesMessage);
proceed = false;
}
return proceed ? next : current;
}
}

Can't get all values from web page

I am working with JSF 2 and Hibernate. I have XHTML page where bean is get from database and inserted into page. When I change the values of bean and submit for savign I am getting only the last value. What I making wrong?
Here is my XHTML page form code:
<h:form id="edit-slide-form">
<h:panelGrid columns="2">
<h:outputText value="#{msgs.slideTitle}" styleClass="label"/>
<h:inputText id="title" value="#{sliderAction.newSlide.title}" name="#{sliderAction.slide.title}" required="true"/>
<p></p><h:message for="title" errorClass="error"/>
<h:outputText value="#{msgs.description}" styleClass="label"/>
<h:inputTextarea id="description" value="#{sliderAction.newSlide.description}" name="#{sliderAction.slide.description}" required="true"/>
<p></p><h:message for="description" errorClass="error"/>
<p></p>
<h:commandButton value="#{msgs.save}" action="#{sliderAction.saveChanges}" styleClass="button"/>
<h:message for="edit-slide-form"/>
</h:panelGrid>
</h:form>
When I submit this form I can get only last value (e.g id="description").
SliderAction.class
#Named
#SessionScoped
public class SliderAction implements Serializable {
private static final long serialVersionUID = 1L;
private EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("iaau");
private EntityManager entityManager;
private int id;
private Integer coordinates[] = new Integer[4];
private Image image = new Image();
private Slide slide = new Slide();
private Slide newSlide = new Slide();
private List<Slide> slides = new ArrayList<Slide>();
private UploadedFile uploadedFile;
private boolean uploaded;
public String uploadSlideImage() {
ImageAction imageAction = new ImageAction();
if( uploaded ) {
imageAction.delete( image.getUniqueName(), image.getThumb() );
for( int i = 0; i < coordinates.length; i++ ) {
coordinates[i] = null;
}
}
imageAction.upload(uploadedFile, false);
setImage( imageAction.getImage() );
uploaded = true;
return null;
}
public String cropAndSave(){
ImageAction imageAction = new ImageAction();
imageAction.cropSlide( image, coordinates, 928, 318 );
newSlide = new Slide();
newSlide.setImage( image );
startTransaction();
entityManager.persist(image);
entityManager.persist(newSlide);
endTransaction();
closeTransaction();
uploaded = false;
setId(newSlide.getId());
return "edit";
}
public String saveChanges() {
startTransaction();
entityManager.merge(newSlide);
endTransaction();
closeTransaction();
return "list";
}
public void deleteSlide() {
startTransaction();
slide = (Slide)entityManager.find(Slide.class, id);
entityManager.remove(slide);
endTransaction();
closeTransaction();
ImageAction imageAtion = new ImageAction();
imageAtion.delete(slide.getImage().getUniqueName(), slide.getImage().getThumb());
}
public Slide getSlide() {
startTransaction();
slide = entityManager.find(Slide.class, id);
endTransaction();
closeTransaction();
return slide;
}
public void setSlide(Slide slide) {
this.slide = slide;
}
public Slide getNewSlide() {
startTransaction();
newSlide = entityManager.find(Slide.class, id);
endTransaction();
closeTransaction();
return newSlide;
}
public void setNewSlide(Slide newSlide) {
this.newSlide = newSlide;
}
#SuppressWarnings("unchecked")
public List<Slide> getSlides() {
startTransaction();
slides = entityManager.createQuery("from Slide").getResultList();
endTransaction();
closeTransaction();
return slides;
}
/*Declaration of EntityManager and other getter and setter methods*/
}
Slide.class
#Entity
public class Slide extends AbstractEntity<Integer>{
private static final long serialVersionUID = 1L;
private String title;
private String description;
private Image image;
private String link;
private Page page;
private boolean showOnFeed;
private boolean approved;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#OneToOne
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
#OneToOne
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
#Column(name="show_on_feed")
public boolean isShowOnFeed() {
return showOnFeed;
}
public void setShowOnFeed(boolean showOnFeed) {
this.showOnFeed = showOnFeed;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
}
Also I have notices this warning message:
[org.hibernate.ejb.internal.EntityManagerFactoryRegistry] (http-localhost-127.0.0.1-8080-1) HHH000436: Entity manager factory name (iaau) is already registered. If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name'
can this cause such problems

on clicking a4j:commandbutton, method does not get executed

I am developing an application using jsf2.0, richfaces 4.0, tomcat 6.0. On a page I am trying to delete a row . But when I click the delete icon, sometimes popup panel does not appear and when it is shown , nothing happens on clicking the delete button.
Following is my .xhtml file:
<!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:c="http://java.sun.com/jsp/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<ui:composition template="template.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:viewParam name="meetingId" required="true" value="#{meetingBean.selectedMeetId}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h3>List of Employees in selected meeting</h3>
<a4j:status onstart="#{rich:component('statPane')}.show()"
onstop="#{rich:component('statPane')}.hide()" />
<h:form>
<c:if test="#{! empty meetingBean.selectedMeeting}">
<c:set target="#{flash}" property="selectedMeeting"
value="#{meetingBean.selectedMeeting}" />
</c:if>
<c:if test="#{! empty flash.selectedMeeting}">
<c:set target="#{meetingBean}" property="selectedMeeting"
value="#{flash.selectedMeeting}" />
</c:if>
<rich:extendedDataTable value="#{meetingBean.selectedMeeting.employees}" var="empMeet" border="1" id="table">
<rich:column>
<f:facet name="header">Employee Id</f:facet>
#{empMeet.empId}
</rich:column>
<rich:column>
<f:facet name="header"> Employee Name</f:facet>
#{empMeet.firstName} #{empMeet.lastName}
</rich:column>
<rich:column>
<a4j:commandLink execute="#this" render="#none" oncomplete="#{rich:component('confirmPanel')}.show();">
<h:graphicImage value="/images/icons/delete.gif" alt="delete" />
<a4j:param value="#{empMeet.empId}" assignTo="#{meetingBean.deleteEmpId}" />
</a4j:commandLink>
</rich:column>
</rich:extendedDataTable>
<a4j:jsFunction name="removeEmp" action="#{meetingBean.deleteEmployee}" render="table" execute="#this"
oncomplete="#{rich:component('confirmPanel')}.hide();" >
</a4j:jsFunction>
<rich:popupPanel id="statPane" autosized="true">
<h:graphicImage value="/images/ai.gif" />
Please wait...
</rich:popupPanel>
<rich:popupPanel id="confirmPanel" autosized="true" >
Are you sure you want to delete the row?
<a4j:commandButton value="Cancel" onclick="#{rich:component('confirmPane')}.hide(); return false;" />
<a4j:commandButton value="Delete" onclick="removeEmp(); return false;" />
</rich:popupPanel>
<h:commandButton action="addEmpMeeting" value="Invite More Employees" />
</h:form>
</ui:define>
</ui:composition>
</html>
Following is my bean class:
package com.drishti.apps.mommanager.meeting;
/**
* this class represents a meeting object
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.richfaces.component.SortOrder;
import com.drishti.apps.mommanager.employee.AbstractBacking;
import com.drishti.apps.mommanager.employee.EmployeeEntity;
import com.drishti.apps.mommanager.employee.EmployeeService;
#ManagedBean
public class MeetingBean extends AbstractBacking {
#ManagedProperty(value = "#{requestScope}")
private Map<String, Object> requestMap;
private int meetingId;
private Date meetingTime;
private String agenda;
private String result;
public String[] empIdsInMeeting;
private List<EmployeeEntity> employees = new ArrayList<EmployeeEntity>();
private Integer selectedMeetId;
private MeetingEntity selectedMeeting;
private String selectedAgenda;
private int deleteEmpId;
private EmployeeEntity deletableEmployee;
/**
* this method is used to load a meeting object when it is being updated
*
* #param cse
*/
public void loadMeeting(ComponentSystemEvent cse) {
if (null == getSelectedMeeting()) {
Integer meetId = getSelectedMeetId();
if (meetId == null) {
meetId = (Integer)getFlash().get("selectedMeetId");
}
if (meetId == null) {
getFacesContext().addMessage(null, new FacesMessage("The meeting is invalid"));
getFlash().setKeepMessages(true);
getFacesContext().getApplication().getNavigationHandler()
.handleNavigation(getFacesContext(), null, "listMeetings");
} else {
MeetingEntity meet = MeetingService.getCurrentInstance().getMeetingForId(meetId);
if (meet == null) {
getFacesContext().addMessage(null, new FacesMessage("The meeting is invalid"));
getFlash().setKeepMessages(true);
getFacesContext().getApplication().getNavigationHandler()
.handleNavigation(getFacesContext(), null, "listMeetings");
} else {
getFlash().put("selectedMeeting", meet);
getSelectedMeeting();
}
}
}
}
/**
* this method updates a meeting object
*
* #return
*/
public void updateMeeting() {
//String result = null;
MeetingService meetSer = MeetingService.getCurrentInstance();
MeetingEntity meeting = getSelectedMeeting();
meetSer.updateMeeting(meeting);
getFlash().clear();
//result = "meetUpdated";
//return result;
}
/**
* this method adds a meeting object to database
*
* #return
*/
public void addMeeting() {
MeetingEntity meeting = (MeetingEntity)getRequestMap().get("meetingEntity");
MeetingService.getCurrentInstance().addMeeting(meeting);
//return "successMeeting";
}
/**
* this method is used to delete a meeting
*/
public void deleteMeeting(){
MeetingService meetSer = MeetingService.getCurrentInstance();
MeetingEntity meeting = getSelectedMeeting();
meetSer.deleteMeeting(meeting);
getFlash().clear();
}
/**
* returns data model containing all meetings present in database
*
* #return
*/
public DataModel<MeetingEntity> getMeetingList() {
DataModel<MeetingEntity> meetingList = new ListDataModel<MeetingEntity>(MeetingService.getCurrentInstance()
.getMeetings());
return meetingList;
}
/**
* returns list containing agenda of all meetings
*
* #return
*/
public ArrayList<String> getAgendaList() {
ArrayList<String> agendaList = new ArrayList<String>();
agendaList.add(getSelectedMeeting().getAgenda());
return agendaList;
}
/**
* this method is used to get a list of employee names for employees who are not invited to a particular meeting
*/
public List<String> getEmpNameIdList() {
List<EmployeeEntity> employeeList = new ArrayList<EmployeeEntity>(EmployeeService.getCurrentInstance()
.getEmployeeList());
List<String> uninvitedEmpList = new ArrayList<String>();
ListIterator<EmployeeEntity> empIter = employeeList.listIterator();
ArrayList<Integer> idList = new ArrayList<Integer>();
while (empIter.hasNext()) {
idList.add(empIter.next().getEmpId());
}
MeetingEntity meeting = getSelectedMeeting();
List<EmployeeEntity> employees = meeting.getEmployees();
if(employees!=null){
ListIterator<EmployeeEntity> invitedIter = employees.listIterator();
ArrayList<Integer> invitedIds = new ArrayList<Integer>();
while (invitedIter.hasNext()) {
invitedIds.add(invitedIter.next().getEmpId());
}
idList.removeAll(invitedIds);
}
EmployeeEntity emp;
ListIterator<Integer> idIter = idList.listIterator();
while (idIter.hasNext()) {
int id = idIter.next();
emp = EmployeeService.getCurrentInstance().getEmployeeForId(id);
uninvitedEmpList.add(emp.getFirstName() + " " + emp.getLastName() + " (" + emp.getEmpId() + ")");
}
return uninvitedEmpList;
}
/**
* this method adds employees to a meeting
* #return
*/
public String addEmpToMeeting() {
MeetingEntity meeting = MeetingService.getCurrentInstance().getMeetingFromAgenda(
getSelectedMeeting().getAgenda());
for (int i = 0; i < empIdsInMeeting.length; i++) {
String id = null;
id = empIdsInMeeting[i].substring(empIdsInMeeting[i].lastIndexOf("(") + 1,
empIdsInMeeting[i].lastIndexOf(")"));
int empId = Integer.parseInt(id);
meeting.getEmployees().add(EmployeeService.getCurrentInstance().getEmployeeForId(empId));
}
MeetingService.getCurrentInstance().addMeeting(meeting);
return "empAddedToMeeting";
}
/**
* this method removes employee from a meeting
* #return
*/
public void deleteEmployee(){
List<EmployeeEntity>inviteEmployees=getSelectedMeeting().getEmployees();
EmployeeEntity emp=getDeletableEmployee();
inviteEmployees.remove(emp);
}
public Integer getSelectedMeetId() {
return selectedMeetId;
}
public void setSelectedMeetId(Integer selectedMeetId) {
this.selectedMeetId = selectedMeetId;
setSelectedMeeting(MeetingService.getCurrentInstance().getMeetingForId(selectedMeetId));
}
public MeetingEntity getSelectedMeeting() {
return selectedMeeting;
}
public void setSelectedMeeting(MeetingEntity selectedMeeting) {
this.selectedMeeting = selectedMeeting;
}
public Map<String, Object> getRequestMap() {
return requestMap;
}
public void setRequestMap(Map<String, Object> requestMap) {
this.requestMap = requestMap;
}
public Date getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(Date meetingTime) {
this.meetingTime = meetingTime;
}
public String getAgenda() {
return agenda;
}
public void setAgenda(String agenda) {
this.agenda = agenda;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public int getMeetingId() {
return this.meetingId;
}
public List<EmployeeEntity> getEmployees() {
return employees;
}
public String[] getEmpIdsInMeeting() {
return empIdsInMeeting;
}
public void setEmpIdsInMeeting(String[] empIdsInMeeting) {
this.empIdsInMeeting = empIdsInMeeting;
}
public void setEmployees(List<EmployeeEntity> employees) {
this.employees = employees;
}
public String getSelectedAgenda() {
return selectedAgenda;
}
public void setSelectedAgenda(String selectedAgenda) {
this.selectedAgenda = selectedAgenda;
}
public void setTimeOrder(SortOrder timeOrder) {
this.timeOrder = timeOrder;
}
public int getDeleteEmpId() {
return deleteEmpId;
}
public void setDeleteEmpId(int deleteEmpId) {
this.deleteEmpId = deleteEmpId;
setDeletableEmployee(EmployeeService.getCurrentInstance().getEmployeeForId(deleteEmpId));
}
public EmployeeEntity getDeletableEmployee() {
return deletableEmployee;
}
public void setDeletableEmployee(EmployeeEntity deletableEmployee) {
this.deletableEmployee = deletableEmployee;
}
}
Please help .
The problem is probably related to JSF overriding your custom onclick.
The work-around would be to use onmousedown instead of onclick, with the potential caveat described here:
http://blogs.oracle.com/jtb/entry/jsf_h_commandlink_and_onclick
i had the same problem few days ago, changing the return to true may work for you.

Resources