popupPanel not show in rich:dataTable - google-app-engine

Base on the sample from:
http://showcase.richfaces.org/richfaces/component-sample.jsf?demo=dataTable&sample=dataTableEdit&skin=blueSky
I did a bit modify on the xhtml page and CarBean to include a button to display the result. Result display as expected but the popup panel not working (ie. no popup).
Software version I use:
richface 4.3.0 Final
GAE 1.7.2
Note: It work fine on my local notebook and problem mention above apply when deploy online.
Here the online url
http://cloudenterpriseapps.appspot.com/public/test/testPopup5.jsf
Any help?
[CarsBean.java]
package test.faces.bean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import org.richfaces.demo.common.data.RandomHelper;
import org.richfaces.demo.tables.model.cars.InventoryItem;
import org.richfaces.demo.tables.model.cars.InventoryVendorItem;
import org.richfaces.demo.tables.model.cars.InventoryVendorList;
#ManagedBean(name = "carsBean2")
#SessionScoped
public class CarsBean2 implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3832235132261771583L;
private static final int DECIMALS = 1;
private static final int CLIENT_ROWS_IN_AJAX_MODE = 15;
private static final int ROUNDING_MODE = BigDecimal.ROUND_HALF_UP;
private List<InventoryItem> allInventoryItems = null;
private List<InventoryVendorList> inventoryVendorLists = null;
private int currentCarIndex;
private InventoryItem editedCar;
private int page = 1;
private int clientRows;
public void switchAjaxLoading(ValueChangeEvent event) {
this.clientRows = (Boolean) event.getNewValue() ? CLIENT_ROWS_IN_AJAX_MODE : 0;
}
public void remove() {
allInventoryItems.remove(allInventoryItems.get(currentCarIndex));
}
public void store() {
allInventoryItems.set(currentCarIndex, editedCar);
}
public List<SelectItem> getVendorOptions() {
List<SelectItem> result = new ArrayList<SelectItem>();
result.add(new SelectItem("", ""));
for (InventoryVendorList vendorList : getInventoryVendorLists()) {
result.add(new SelectItem(vendorList.getVendor()));
}
return result;
}
public List<String> getAllVendors() {
List<String> result = new ArrayList<String>();
for (InventoryVendorList vendorList : getInventoryVendorLists()) {
result.add(vendorList.getVendor());
}
return result;
}
public List<InventoryVendorList> getInventoryVendorLists() {
synchronized (this) {
if (inventoryVendorLists == null) {
inventoryVendorLists = new ArrayList<InventoryVendorList>();
List<InventoryItem> inventoryItems = getAllInventoryItems();
Collections.sort(inventoryItems, new Comparator<InventoryItem>() {
public int compare(InventoryItem o1, InventoryItem o2) {
return o1.getVendor().compareTo(o2.getVendor());
}
});
Iterator<InventoryItem> iterator = inventoryItems.iterator();
InventoryVendorList vendorList = new InventoryVendorList();
vendorList.setVendor(inventoryItems.get(0).getVendor());
while (iterator.hasNext()) {
InventoryItem item = iterator.next();
InventoryVendorItem newItem = new InventoryVendorItem();
itemToVendorItem(item, newItem);
if (!item.getVendor().equals(vendorList.getVendor())) {
inventoryVendorLists.add(vendorList);
vendorList = new InventoryVendorList();
vendorList.setVendor(item.getVendor());
}
vendorList.getVendorItems().add(newItem);
}
inventoryVendorLists.add(vendorList);
}
}
return inventoryVendorLists;
}
private void itemToVendorItem(InventoryItem item, InventoryVendorItem newItem) {
newItem.setActivity(item.getActivity());
newItem.setChangePrice(item.getChangePrice());
newItem.setChangeSearches(item.getChangeSearches());
newItem.setDaysLive(item.getDaysLive());
newItem.setExposure(item.getExposure());
newItem.setInquiries(item.getInquiries());
newItem.setMileage(item.getMileage());
newItem.setMileageMarket(item.getMileageMarket());
newItem.setModel(item.getModel());
newItem.setPrice(item.getPrice());
newItem.setPriceMarket(item.getPriceMarket());
newItem.setPrinted(item.getPrinted());
newItem.setStock(item.getStock());
newItem.setVin(item.getVin());
}
public String queryRec(){
String result = "";
synchronized (this) {
getAllInventoryItems();
}
return result;
}
public String initQuery(){
String result = "";
synchronized (this) {
allInventoryItems = null;
}
return result;
}
public List<InventoryItem> getInventoryItems() {
return allInventoryItems;
}
public List<InventoryItem> getAllInventoryItems() {
synchronized (this) {
if (allInventoryItems == null) {
allInventoryItems = new ArrayList<InventoryItem>();
for (int k = 0; k <= 5; k++) {
try {
switch (k) {
case 0:
allInventoryItems.addAll(createCar("Chevrolet", "Corvette", 5));
allInventoryItems.addAll(createCar("Chevrolet", "Malibu", 8));
allInventoryItems.addAll(createCar("Chevrolet", "Tahoe", 6));
break;
case 1:
allInventoryItems.addAll(createCar("Ford", "Taurus", 12));
allInventoryItems.addAll(createCar("Ford", "Explorer", 11));
break;
case 2:
allInventoryItems.addAll(createCar("Nissan", "Maxima", 9));
allInventoryItems.addAll(createCar("Nissan", "Frontier", 6));
break;
case 3:
allInventoryItems.addAll(createCar("Toyota", "4-Runner", 7));
allInventoryItems.addAll(createCar("Toyota", "Camry", 15));
allInventoryItems.addAll(createCar("Toyota", "Avalon", 13));
break;
case 4:
allInventoryItems.addAll(createCar("GMC", "Sierra", 8));
allInventoryItems.addAll(createCar("GMC", "Yukon", 10));
break;
case 5:
allInventoryItems.addAll(createCar("Infiniti", "G35", 6));
allInventoryItems.addAll(createCar("Infiniti", "EX35", 5));
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return allInventoryItems;
}
public List<InventoryItem> createCar(String vendor, String model, int count) {
ArrayList<InventoryItem> iiList = null;
try {
int arrayCount = count;
InventoryItem[] demoInventoryItemArrays = new InventoryItem[arrayCount];
for (int j = 0; j < demoInventoryItemArrays.length; j++) {
InventoryItem ii = new InventoryItem();
ii.setVendor(vendor);
ii.setModel(model);
ii.setStock(RandomHelper.randomstring(6, 7));
ii.setVin(RandomHelper.randomstring(17, 17));
ii.setMileage(new BigDecimal(RandomHelper.rand(5000, 80000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setMileageMarket(new BigDecimal(RandomHelper.rand(25000, 45000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setPrice(new Integer(RandomHelper.rand(15000, 55000)));
ii.setPriceMarket(new BigDecimal(RandomHelper.rand(15000, 55000)).setScale(DECIMALS, ROUNDING_MODE));
ii.setDaysLive(RandomHelper.rand(1, 90));
ii.setChangeSearches(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setChangePrice(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setExposure(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setActivity(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setPrinted(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
ii.setInquiries(new BigDecimal(RandomHelper.rand(0, 5)).setScale(DECIMALS, ROUNDING_MODE));
demoInventoryItemArrays[j] = ii;
}
iiList = new ArrayList<InventoryItem>(Arrays.asList(demoInventoryItemArrays));
} catch (Exception e) {
e.printStackTrace();
}
return iiList;
}
public int getCurrentCarIndex() {
return currentCarIndex;
}
public void setCurrentCarIndex(int currentCarIndex) {
this.currentCarIndex = currentCarIndex;
}
public InventoryItem getEditedCar() {
return editedCar;
}
public void setEditedCar(InventoryItem editedCar) {
this.editedCar = editedCar;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getClientRows() {
return clientRows;
}
public void setClientRows(int clientRows) {
this.clientRows = clientRows;
}
}
[testPopup5.xhtml]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<ui:composition>
<h:head>
<title>RichFaces Showcase</title>
</h:head>
<h:body>
<h:outputStylesheet>
a.no-decor>img {
border: none;
}
</h:outputStylesheet>
<a4j:status onstart="#{rich:component('statPane')}.show()"
onstop="#{rich:component('statPane')}.hide()" />
<h:form>
<h:panelGrid columns="2">
<a4j:commandButton id="search" action="#{carsBean2.queryRec}"
value="Search" render="table" />
<a4j:commandButton id="reset" action="#{carsBean2.initQuery}"
value="Reset" type="reset" render="table" />
</h:panelGrid>
</h:form>
<h:form>
<rich:dataTable value="#{carsBean2.inventoryItems}" var="car"
id="table" rows="5">
<rich:column>
<f:facet name="header">Model</f:facet>
<h:outputText value="#{car.model}" />
</rich:column>
<rich:column>
<f:facet name="header">Price</f:facet>
<h:outputText value="#{car.price}" />
</rich:column>
<rich:column>
<a4j:commandLink styleClass="no-decor" render="editGrid"
execute="#this" oncomplete="#{rich:component('editPanel')}.show()">
<h:graphicImage value="/images/icons/common/edit.gif" alt="edit" />
<f:setPropertyActionListener target="#{carsBean2.editedCar}"
value="#{car}" />
</a4j:commandLink>
</rich:column>
</rich:dataTable>
<rich:popupPanel id="statPane" autosized="true" rendered="true">
<h:graphicImage value="/images/common/ai.gif" alt="ai" />
Please wait...
</rich:popupPanel>
<rich:popupPanel header="Edit Car Details" id="editPanel">
<h:panelGrid columns="3" id="editGrid">
<h:outputText value="Model" />
<h:outputText value="#{carsBean2.editedCar.model}" />
<h:panelGroup />
<h:outputText value="Price" />
<h:outputText value="#{carsBean2.editedCar.price}" />
<h:panelGroup />
</h:panelGrid>
<a4j:commandButton value="Cancel"
onclick="#{rich:component('editPanel')}.hide(); return false;" />
</rich:popupPanel>
</h:form>
</h:body>
</ui:composition>
</html>
Using firebug, I manage discover few diff between local and online GAE version.
1) editPanel # local change it style stage from 'visibility hidden' to 'display none' and then 'display block' when click on edit icon.
However editPanel # GAE still remain unchange with 'visibility hidden'
[Local]
<div id="j_idt9:editPanel" style="visibility: hidden;">
<div id="j_idt9:editPanel" style="display: none;">
<div id="j_idt9:editPanel" style="display: block;">
[GAE]
<div id="j_idt9:editPanel" style="visibility: hidden;">
2) under , local version contain value in table tag
3) Shown in firebug's script tab, when click on edit link, local version display as: and follow by table values.
However online version display it as and without any table values
p/s: Online: http://cloudenterpriseapps.appspot.com/public/test/testPopup5.jsf
By the way the GAE display below warning when page first load. Don't know is related to the problem or not.
[s~cloudenterpriseapps/0.365021621033424561].: SystemId Unknown; Line #57; Column #31; Failed calling setMethod method
[FireBug Script tab, Local. Click on edit link]
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="j_idt9:editGrid"><![CDATA[<table id="j_idt9:editGrid">
<tbody>
<tr>
<td>Model</td>
<td>Corvette</td>
<td></td>
</tr>
<tr>
<td>Price</td>
<td>47405</td>
<td></td>
</tr>
</tbody>
</table>
]]></update><update id="javax.faces.ViewState"><![CDATA[H4sIAAAAAAEUTEh...EUXAkFAAA]]></update></changes><extension id="org.richfaces.extension"><complete>RichFaces.$('j_idt9:editPanel').show();</complete><render>j_idt9:editGrid</render></extension></partial-response>
[FireBug Script tab, GAE. Click on edit link]
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="javax.faces.ViewState"><![CDATA[H4sIAAAAAAAAANVYbW....KBTUkFAAA]]></update></changes></partial-response>

Solved after upgrade JSF api and implementation jar from 2.0 to 2.1

Related

Unable to display data fetched from the database

I am new to stackoverflow and to Java. I am trying to fetch the data from the database then display it in a JSF page.
For the table I have a model : BusesInfo.java that contains getters and setters for the attributes of the table.
then I also have BusesDao that fetches the data from DB and stores it in an array list. BusesInfoBean that links these data to the JSF page. The connection to the database is success. the JSF page contains a table that calls BusesInfobean.busesInfo in the columns i call BusesInfo.attribute
Please I need your help! Below you can find sample codes:
package beans;
import daos.BusesDao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import models.BusesInfo;
#ViewScoped
public class BusesInfoBean implements Serializable {
private final BusesDao busesDao = new BusesDao();
private ArrayList<BusesInfo> busesInfo;
public BusesInfoBean(){}
#PostConstruct
public void init(){
try {
busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(ManageEventsBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ArrayList<BusesInfo> getBusesInfo() {
return busesInfo;
}
public void setBusesInfo(ArrayList<BusesInfo> busesInfo) {
this.busesInfo = busesInfo;
}
}
BusesDao.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import models.BusesInfo;
import java.util.logging.Logger;
import java.util.logging.Level;
public class BusesDao extends ConnectionDao {
public ArrayList<BusesInfo> buildBusesInfo() throws Exception {
ArrayList<BusesInfo> list = new ArrayList<>();
Connection conn = getConnection();
try {
String sql = "SELECT * FROM BUSES_INFO";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(populateBusesInfo(rs));
}
rs.close();
ps.close();
return list;
} catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
private BusesInfo populateBusesInfo(ResultSet rs) throws SQLException {
BusesInfo busesInfo = new BusesInfo();
busesInfo.setBusID(rs.getInt("BUS_ID"));
busesInfo.setDriverID(rs.getInt("DRIVER_ID"));
busesInfo.setDepartureTime(rs.getString("DEPARTURE_TIME"));
busesInfo.setArrivalTime(rs.getString("ARRIVAL_TIME"));
busesInfo.setRouteEn(rs.getString("ROUTE_EN"));
busesInfo.setRouteAr(rs.getString("ROUTE_AR"));
busesInfo.setLicensePlate(rs.getString("LICENSE_PLATE"));
busesInfo.setCapacity(rs.getInt("CAPACITY"));
return busesInfo;
}
public static void main(String [] args){
try {
BusesDao busesDao = new BusesDao();
ArrayList<BusesInfo> busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(EventsDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
the model class BusesInfo only contains getters and setters:
public class BusesInfo implements Serializable {
private int busID;
private int driverID;
private String departureTime;
private String arrivalTime;
private String routeEn;
private String routeAr;
private String licensePlate;
private int capacity;
public BusesInfo(){}
/**
*
* #param busID
* #param driverID
* #param departureTime
* #param arrivalTime
* #param routeEn
* #param routeAr
* #param licensePlate
* #param capacity
*/
public BusesInfo(int busID, int driverID, String departureTime, String arrivalTime, String routeEn, String routeAr, String licensePlate, int capacity) {
this.busID = busID;
this.driverID = driverID;
this.departureTime = departureTime;
this.arrivalTime = arrivalTime;
this.routeEn = routeEn;
this.routeAr = routeAr;
this.licensePlate = licensePlate;
this.capacity = capacity;
}
public int getBusID() {
return busID;
}
public void setBusID(int busID) {
this.busID = busID;
}
public int getDriverID() {
return driverID;
}
public void setDriverID(int driverID) {
this.driverID = driverID;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getRouteEn() {
return routeEn;
}
public void setRouteEn(String routeEn) {
this.routeEn = routeEn;
}
public String getRouteAr() {
return routeAr;
}
public void setRouteAr(String routeAr) {
this.routeAr = routeAr;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
JSF page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>#{msgs.buses}</title>
</h:head>
<h:body>
<div>
<ui:decorate template="/app_templates/app_template.xhtml">
<h:form id="bus_info_form">
<p:dataTable
id="bus_info_tbl"
value = "#{busesInfoBean.busesInfo}"
class = "dataTable"
var="event"
rows="2"
dir="#{langBean.dir}"
emptyMessage="#{msgs.no_buses}"
paginator="true"
paginatorPosition="top"
paginatorTemplate="#{langBean.isEnglish? '{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}' : '{RowsPerPageDropdown} {LastPageLink} {NextPageLink} {PageLinks} {PreviousPageLink} {FirstPageLink}'}"
>
<p:ajax event="rowSelectRadio"
update=":bus_info_form:bus_info_tbl"/>
<f:facet name="header" id="header">
#{msgs.buses}
</f:facet>
<p:column selectionMode="single" style="width:5%"/>
<p:column headerText="#{msgs.bus_id}"
style="width:15%"
sortBy="#{busesInfo.busID}">
<h:outputText value="#{busesInfo.busID}"/>
</p:column>
<p:column headerText="#{msgs.driver_id}"
style="width:15%"
sortBy="#{busesInfo.driverID}">
<h:outputText value="#{busesInfo.driverID}"/>
</p:column>
<p:column headerText="#{msgs.departure_time}"
style="width:15%"
sortBy="#{busesInfo.departureTime}">
<h:outputText value="#{busesInfo.departureTime}"/>
</p:column>
<p:column headerText="#{msgs.arrival_time}"
style="width:15%"
sortBy="#{busesInfo.arrivalTime}">
<h:outputText value="#{busesInfo.arrivalTime}"/>
</p:column>
<p:column headerText="#{msgs.route}"
style="width:20%"
filterBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"
filterMatchMode="contains"
sortBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}">
<h:outputText value="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"/>
</p:column>
<p:column headerText="#{msgs.license_plate}"
style="width:15%"
sortBy="#{busesInfo.licensePlate}">
<h:outputText value="#{busesInfo.licensePlate}"/>
</p:column>
<p:column headerText="#{msgs.capacity}"
style="width:15%"
sortBy="#{busesInfo.capacity}">
<h:outputText value="#{busesInfo.capacity}"/>
</p:column>
</p:dataTable>
</h:form>
</ui:decorate>
</div>
</h:body>
</html>

Multiple, but limited, CheckBoxes in FXML/JavaFX

I'm trying to find a way to use check boxes to allow the user to pick two things from a list of three, and then have the remaining check box become disabled until one of the others is un-selected. I have a ChangeListener attached to all three check boxes, so I can register when two have been selected, but I don't know how to target the "other" box/boxes to disable/enable them.
ChangeListener checkboxlistener = new ChangeListener() {
int i = 0;
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue) {
if((boolean) observable.getValue() == true) {
i++;
System.out.println(i);
} else {
i--;
System.out.println(i);
}
if(i == 2) {
//What should I put here, if anything?//
}
}
};
checkbox1.selectedProperty().addListener(checkboxlistener);
checkbox2.selectedProperty().addListener(checkboxlistener);
checkbox3.selectedProperty().addListener(checkboxlistener);
}
Keep a collection of selected check boxes and unselected check boxes. Add a listener to each check box's selectedProperty and make sure it is in the correct collections when the selection changes.
Then you can just observe the size of the collection of selected check boxes, and update the disable state of all the unselected check boxes accordingly.
Here's an example:
MultipleCheckBoxExampleController.java:
package multiplecheckbox;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
public class MultipleCheckBoxExampleController {
#FXML
private CheckBox checkBox1 ;
#FXML
private CheckBox checkBox2 ;
#FXML
private CheckBox checkBox3 ;
#FXML
private Button submitButton ;
private ObservableSet<CheckBox> selectedCheckBoxes = FXCollections.observableSet();
private ObservableSet<CheckBox> unselectedCheckBoxes = FXCollections.observableSet();
private IntegerBinding numCheckBoxesSelected = Bindings.size(selectedCheckBoxes);
private final int maxNumSelected = 2;
public void initialize() {
configureCheckBox(checkBox1);
configureCheckBox(checkBox2);
configureCheckBox(checkBox3);
submitButton.setDisable(true);
numCheckBoxesSelected.addListener((obs, oldSelectedCount, newSelectedCount) -> {
if (newSelectedCount.intValue() >= maxNumSelected) {
unselectedCheckBoxes.forEach(cb -> cb.setDisable(true));
submitButton.setDisable(false);
} else {
unselectedCheckBoxes.forEach(cb -> cb.setDisable(false));
submitButton.setDisable(true);
}
});
}
private void configureCheckBox(CheckBox checkBox) {
if (checkBox.isSelected()) {
selectedCheckBoxes.add(checkBox);
} else {
unselectedCheckBoxes.add(checkBox);
}
checkBox.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
unselectedCheckBoxes.remove(checkBox);
selectedCheckBoxes.add(checkBox);
} else {
selectedCheckBoxes.remove(checkBox);
unselectedCheckBoxes.add(checkBox);
}
});
}
}
MultipleCheckBoxExample.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Button?>
<?import javafx.geometry.Insets?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="multiplecheckbox.MultipleCheckBoxExampleController"
alignment="center" spacing="5">
<padding>
<Insets top="10" bottom="10" left="10" right="10" />
</padding>
<CheckBox fx:id="checkBox1" text="Choice 1" />
<CheckBox fx:id="checkBox2" text="Choice 2" />
<CheckBox fx:id="checkBox3" text="Choice 3" />
<Button fx:id="submitButton" text="Submit" />
</VBox>
Main.java:
package multiplecheckbox;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.fxml.FXMLLoader;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
VBox root = FXMLLoader.load(getClass().getResource("MultipleCheckBoxExample.fxml"));
Scene scene = new Scene(root,400,400);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}

Struts2 execAndWait and file upload no work

I have this problem and I'm really going crazy without having a result.
I have a form and all fields are required through validator.xml
My form contains a field for the upload image (required)
When I click the submit button present a paggina waiting through (execAndWait configured in struts.xml).
my big problem is this:
the waiting page always redirect to my form page with text (the file field and mandatory).
Here is the code:
/register.jsp
<!-- al submit chiama l'action register -->
<action name="register" class="action.Register" method="execute" >
<interceptor-ref name="defaultStack" />
<interceptor-ref name="fileUpload">
<param name="maximumSize">10000000</param>
<param name="allowedTypes">image/jpeg,image/gif,image/jpg</param>
</interceptor-ref>
<interceptor-ref name="params"></interceptor-ref>
<interceptor-ref name="execAndWait">
</interceptor-ref>
<result name="success">index.jsp</result>
<result name="input">/register.jsp</result>
<result name="wait">/test.jsp</result>
</action>
waiting page:
<meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />"/>
</head>
<body>
<p>your request is processing...</p>
<img src="images/indicator.gif"/>
my form:
<s:form method="post" action="register" validate="false" enctype="multipart/form-data">
<s:textfield key="utenteBean.nome" name="utenteBean.nome" value="a" />
<s:textfield key="utenteBean.nickname" name="utenteBean.nickname" value="a" />
<sj:datepicker key="utenteBean.nato" name="utenteBean.nato"
showButtonPanel="true" displayFormat="dd/mm/yy" value="25/09/1983"/>
<s:textfield key="utenteBean.professione" name="utenteBean.professione" value="a"/>
<s:textfield key="utenteBean.eta" name="utenteBean.eta" value="3"/>
<s:textfield key="utenteBean.dj_preferito" name="utenteBean.dj_preferito" value="a" />
<s:textfield key="utenteBean.rave_fatti" name="utenteBean.rave_fatti" value="3" />
<s:textfield key="utenteBean.sito_preferito" name="utenteBean.sito_preferito" value="a" />
<s:textfield key="utenteBean.come_siveste" name="utenteBean.come_siveste" value="a" />
<s:textarea key="utenteBean.messaggio" name="utenteBean.messaggio" value="a"/>
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
really thanks for your help
I suppose that you have put wrong field name for the file tag. Can you show us your action class? Regarding to that instead of:
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
try to use:
<s:file label="file" name="utenteBean.file" requiredLabel="true"" ></s:file>
or just check in your action class the name of the file property.
yes sure ... below my Action class:
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private File file;
private String fileContentType;
private String fileFileName;
private String filesPath;
private ServletContext context;
Map<String, Object> session;
public String execute(){
if (file != null) {
File file = this.file;
// /System.out.println(file.getName());
try {
Util.saveFile(file, fileFileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate(){
if(this.fileFileName==null){
this.addFieldError("file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFilesPath() {
return filesPath;
}
public void setFilesPath(String filesPath) {
this.filesPath = filesPath;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
Thank you so much for your help ...
I solved it by putting my bean in session. I could not find a better solution after many hours of work.
If other people have the same problem I can see the changes I made in my. Action
package action;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import Bean.UtenteBeanAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import Utility.Util;
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private ServletContext context;
Map<String, Object> session;
public String execute(){
session.put("utente", utenteBean);
if (utenteBean.getFile() != null) {
File file = utenteBean.getFile();
// /System.out.println(file.getName());
try {
Util.saveFile(file, utenteBean.getFileFileName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate() {
if (session.get("utente") != null) {
this.utenteBean = (UtenteBeanAction) session.get("utente");
}
if (this.utenteBean.getFileFileName() == null) {
this.addFieldError("utenteBean.file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
I hope I can be of help.
Thanks for the support.

Primefaces dataTable with checkbox not work

I am using Primefaces 4.0 with jsf2.2.
When I use dataTable with checkbox, it won't send back any record whenever I select records.
It supposed to send back the record once I click the checkbox.
I remove extra stuff and make my code simple to test it:
There is a polling printing selected items every second, so that I can check is there something sent back.
And after doing this, I found there's nothing sent back.
Here's my code:
Page:
<h:head>
<title>System Monitor</title>
</h:head>
<h:body>
<h:form>
<p:poll interval="1" listener="#{indexBean.printSelect()}"/>
</h:form>
<h:form>
<p:dataTable id='data' var="proc" value="#{indexBean.procStatus}"
rowKey="#{proc.pid}" selection="#{indexBean.selectedProcs}">
<p:column>
<f:facet name='header'>
<h:outputText value='Process Name'/>
</f:facet>
<h:outputText styleClass="outputCell" id="pname" value='#{proc.name}'/>
</p:column>
<p:column selectionMode="multiple"/>
</p:dataTable>
</h:form>
</h:body>
Backing Bean:
#ManagedBean(name = "indexBean")
#ViewScoped
public class indexBean implements Serializable {
private ProcStatDataModel procStatus;
private SingleProcess[] selectedProcs;
#PostConstruct
public void loadProcStat() {
List<SingleProcess> temp = new ArrayList<>();
temp.add(new SingleProcess("test1"));
temp.add(new SingleProcess("test2"));
temp.add(new SingleProcess("test3"));
procStatus = new ProcStatDataModel(temp);
}
public void printSelect() {
if (selectedProcs != null) {
String str = "";
for (SingleProcess sp : selectedProcs) {
str += sp.getName() + "_";
}
System.out.print(str);
} else {
System.out.println("selectedProcs is null");
}
}
public ProcStatDataModel getProcStatus() {
return procStatus;
}
public SingleProcess[] getSelectedProcs() {
return selectedProcs;
}
public void setSelectedProcs(SingleProcess[] selectedProcs) {
this.selectedProcs = selectedProcs;
}
}
I've tried attaching rowCheckListener like this before but in vain.
Also, I tried adding f:view contentType="text/html" like this and it was not help.
It's weird because I do the same thing with the case of primefaces show case and it acts as I think. So I think this approach is OK, there should be something wrong in my code.
Any help is appreciated. Thanks in advance.
I made a few changes and it worked. Not sure, which one is the solution.
1) Changed all the ' to ".
2) Datatable's value="#{indexBean.procStatus}" is wrong i think. I changed it to the name of the ArrayList inside the class. So, it became value="#{indexBean.procStatus.mylist}"
3) Added an ajax listener, like the one you mentioned in the question. <p:ajax event="rowSelectCheckbox" listener="#{indexBean.check}" />.
4) Added pid to the constructor which will be our rowKey.
5) Now, the poll prints the array.
Resultin xhtml is as follows:
<h:head>
<title>System Monitor</title>
</h:head>
<h:body>
<h:form>
<p:poll interval="1" listener="#{indexBean.printSelect()}"/>
</h:form>
<h:form>
<p:dataTable id="data" var="proc" value="#{indexBean.procStatus.mylist}"
rowKey="#{proc.pid}" selection="#{indexBean.selectedProcs}">
<p:ajax event="rowSelectCheckbox" listener="#{indexBean.check}" />
<p:column>
<f:facet name="header">
<h:outputText value="Process Name"/>
</f:facet>
<h:outputText styleClass="outputCell" id="pname" value="#{proc.name}"/>
</p:column>
<p:column selectionMode="multiple"/>
</p:dataTable>
</h:form>
</h:body>
</ui:composition>
Bean:
#ManagedBean(name = "indexBean")
#ViewScoped
public class indexBean implements Serializable {
private ProcStatDataModel procStatus;
private SingleProcess[] selectedProcs;
#PostConstruct
public void loadProcStat() {
List<SingleProcess> temp = new ArrayList<SingleProcess>();
temp.add(new SingleProcess("test1",1));
temp.add(new SingleProcess("test2",2));
temp.add(new SingleProcess("test3",3));
procStatus = new ProcStatDataModel(temp);
}
public void printSelect() {
if (selectedProcs != null) {
String str = "";
for (SingleProcess sp : selectedProcs) {
str += sp.getName() + "_";
}
System.out.print(str);
} else {
System.out.println("selectedProcs is null");
}
}
public ProcStatDataModel getProcStatus() {
return procStatus;
}
public SingleProcess[] getSelectedProcs() {
return selectedProcs;
}
public void setSelectedProcs(SingleProcess[] selectedProcs) {
this.selectedProcs = selectedProcs;
}
public void check(SelectEvent event) {
System.out.println("in check");
}
}

program data randomizes only when run with break point

i have a program that generates a 2 question test from an SQL DB by question and by answers, the questions are selected randomly by a question id. the problem I'm having is when run normally from net beans the the questions don't randomize in fact on a new system that hasn't run before it doesn't show any questions. but when it is debugged with break points it works perfectly fine. i had something like this happen to another program a while ago and not sure how i fixed it, i believe it was an issue between caching and the math Random.
welcome page load to the quizzical controller which on init generates a test in TestDA servlet
package org.citatscc.quiz.controller;
import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.citatscc.quiz.business.*;
import org.citatscc.quiz.business.TestTaker;
import org.citatscc.quiz.data.TestDA;
public class Quizzical extends HttpServlet {
//the test will be available to all threads
//eventually each TestTaker will store their Test in a Session
private Test myQuiz=null;
#Override
public void init(){
String testName = getServletConfig().getInitParameter("QuizName");
//generate the basic Test which will be used to create each TestTaker's myQuiz
myQuiz = TestDA.generateTest(testName);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("myQuiz", myQuiz);
//here we are simply showing the test generated from the database
String action = request.getParameter("action");
String url = "/QuizView.jsp";
if(action == null)
{
url = "/QuizMain.jsp";
}
else if(action.equals("AddTest"))
{
url = "/QuizAdd.jsp";
}
else if(action.equals("addNewTest"))
{
addNewTest(request);
}
RequestDispatcher dispatch = getServletContext().getRequestDispatcher(url);
dispatch.forward(request, response);
}
public boolean addNewTest(HttpServletRequest request)
{
return false;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
TestDA
package org.citatscc.quiz.data;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.citatscc.quiz.business.Question;
import org.citatscc.quiz.business.Test;
public class TestDA{
public static Test generateTest(String testName) {
List<Question> questions = new ArrayList<Question>();
Test test = null;
boolean sameNum = true;
int randNum1 = 0;
int randNum2 = 0;
while(sameNum == true)
{
randNum1 = getRandomNumber();
randNum2 = getRandomNumber();
if(randNum1 == 0 || randNum2 == 0 || randNum1 > 7 || randNum2 > 7 ||
randNum1 == 6 || randNum2 == 6)
{
sameNum = true;
}
else
{
if(randNum1 != randNum2)
{
sameNum = false;
}
}
}
String questionID1 = getQuestionID(randNum1);
String questionID2 = getQuestionID(randNum2);
try {
String questionTxt1 = getQuestionStringByQID(questionID1);
String questionTxt2 = getQuestionStringByQID(questionID2);
questions.add(getAnswers(questionTxt1, questionID1));
questions.add(getAnswers(questionTxt2, questionID2));
test = new Test(testName,questions);
} catch (Exception ex) {
String message = ex.getMessage();
}
return test;
}
public static Question getAnswers(String questionTxt, String questionID) throws Exception
{
Connection connection = DBUtil.getConnection();
Statement statement = connection.createStatement();
int counter = 0;
int correctAnswer = 0;
ArrayList<String> answers = new ArrayList<String>();
String preparedQuery = "SELECT * FROM `answers` WHERE `qID` = " + questionID;
ResultSet resultSet = statement.executeQuery(preparedQuery);
while (resultSet.next())
{
answers.add(resultSet.getString(2));
if(resultSet.getInt(3) == 1)
{
correctAnswer = counter;
}
else
{
counter++;
}
}
Question question = new Question(questionTxt, answers, correctAnswer);
return question;
}
public static String getQuestionStringByQID(String qID) throws Exception
{
Connection connection = DBUtil.getConnection();
Statement statement = connection.createStatement();
String preparedQuery = "SELECT `question` FROM `questions` WHERE `qID` = " + qID;
ResultSet resultSet = statement.executeQuery(preparedQuery);
String questionText = "";
while (resultSet.next())
{
questionText = resultSet.getString(1);
}
connection.close();
return questionText;
}
public static int getRandomNumber()
{
Random rnd = new Random();
int randomNum = rnd.nextInt(8);
return randomNum;
}
public static String getQuestionID(int randNum)
{
int intqID = randNum * 111;
String qID = "" + intqID;
return qID;
}
public static void insertQuestion(String qID, String qText, List<String>qChoices, int correct)throws SQLException{
String preparedQuestion = "INSERT INTO questions VALUES(?,?)";
}
public static void upDateQuestion(String qID, String qText, List<String>qChoices, int correct) throws SQLException{
}
}
after init is finished it redirects to a menu jsp, after a link to take a test is clicked it hits the quizzical controller before being redirected to QuizView.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Quiz View</title>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="cit" uri="/WEB-INF/tld/test.tld" %>
<%#taglib prefix="includes" tagdir="/WEB-INF/tags/" %>
<%# page import="org.citatscc.quiz.business.Test, org.citatscc.quiz.business.Question" %>
<%# page import="java.util.*" %>
<link href="quiz.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="top"><includes:Header image="cit_logo.jpg" alt="cit logo image" tagline="${myQuiz.testName}"/></div>
<div id="leftnav">
</div>
<div id="content">
<form action="Quiz" method="post">
<c:forEach var="question" items="${myQuiz.questionList}" varStatus="qCount">
<h2>${qCount.count}. ${question.questionText} </h2>
<c:forEach var="choice" items="${question.choices}" varStatus="choiceCount" >
<!-- custom tag here -->
<cit:quiz_choiceButton groupName="choice${qCount.count}" text="${choice}" value="${choiceCount.index}" />
</c:forEach>
<br />
</c:forEach>
<input type="submit" name="done" value="Submit" />
</form>
</div>
<div id="footer"><includes:Footer /></div>
</div>
</body>
</html>
any help is appreciated.
The servlet method init() is called once during servlet initialisation. So, you have the same Test for all your following requests.
private Test myQuiz=null;
has the same value for all requests.
More in docs: http://docs.oracle.com/javaee/5/api/javax/servlet/Servlet.html#init(javax.servlet.ServletConfig)

Resources