Selection doesn't work in extendedDataTable, RichFaces 4 + JSF 2.0 - java

I have an app with RichFaces 4.0.0.Final and JSF 2.0. When I try to use selection in extendedDataTable, it doesn`t work.
<rich:extendedDataTable
id="shipmentList" value="#{shipmentListBean.shipmentList}" var="shipment"
rowClasses="#{shipment.paymentDate == null ? 'unpaidShipment' : null}"
selectionMode="single" noDataLabel="#{msgs.emptyList}"
selection="#{shipmentListBean.selection}"
style="width: 1200px; font-size: 10px; ">
ShipmentListBean:
#ManagedBean
#ApplicationScoped
public class ShipmentListBean implements Serializable {
private Collection<Object> selection = null;
public ShipmentListBean() {
}
public List<ShipmentValueObject> getShipmentList() {
....
}
public Collection<Object> getSelection() {
return selection;
}
public void setSelection(Collection<Object> selection) {
this.selection = selection;
}
}
Why in method selSelection(Collection selection) empty collection come when I select row in table?

you can use selection like this
in ShipmentListBean
private SimpleSelection selection = new SimpleSelection();
// now time to get a selected Row id from the extendedDataTable.
// this method you can call on any button after selecting the row from the extendedDataTable
public void selectedRecord(){
try{
Iterator<Object> iterator = getSelection().getKeys();
while(iterator.hasNext()){
// Here you will get all the selected roes id from the Data table
Object obj = iterator.next();
info("GET SELECTED ROWS ID ::::: " + obj.toString());
}
}catch(Exception e){
e.printStackTrace();
}
}

Related

Update the content of a ComboBox dynamically created in Javafx, from another ComboBox dynamically created

In a GridPane I am dynamically creating two ComboBox's. For the first ComboBox I am charging the items when the Scene is loaded. Then I want that when I perform an action in this ComboBox, the items of the other ComboBox are loaded according to the value selected.
ComboBox<String> combobox1 = loadItems();
ComboBox<String> combobox2 = new ComboBox<String>();
gridpane.add(combobox1, 0, 0);
gridpane.add(combobox2, 1, 0);
I've tried by using a listener, but it didn't seem to work:
combobox1.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
loadList(combobox2, newValue);
}
});
private void loadList(ComboBox<String> combobox, String value) {
combobox = getCorrespondingList(value);
}
public ComboBox<String> getCorrespondingList(String value) {
ComboBox<String> combobox = new ComboBox<String>();
ArrayList<String> list = new ArrayList<String>();
try {
String query = "select ... where Item = '" + value
+ "' order by c";
statement = connection.prepareStatement(query);
result = statement.executeQuery();
while (result.next()) {
list.add(result.getString(1));
}
}
catch (SQLException e) {
e.getMessage();
}
ObservableList<String> observableList = FXCollections.observableArrayList(list);
combobox.setItems(observableList);
return combobox;
}
I really appreciate any help.
Java is call by reference. Any assignment to a method parameter will only have an effect inside the method. Furthermore as far as I can tell you did create the ComboBox you want to modify earlier. Instead of creating a new ComboBox, just fill the modify the existing one:
private void loadList(ComboBox<String> combobox, String value) {
combobox.getItems().setAll(getCorrespondingList(value));
}
public List<String> getCorrespondingList(String value) {
ArrayList<String> list = new ArrayList<String>();
try {
// use PreparedStatement's placeholder functionality to avoid
// issues with quotes inside the string
String query = "SELECT ... WHERE Item = ? ORDER BY c";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, value);
// no need to keep this after the method exits
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace(System.err); // should provide more info in case an exception happens
}
return list;
}

Cassandra 3.x trigger column values

I'm using the 3.4 Cassandra trigger API, that introduced the modified ITrigger interface, example: https://github.com/apache/cassandra/blob/trunk/examples/triggers/src/org/apache/cassandra/triggers/AuditTrigger.java
My question is what is the way to extract the column values from Partition object for insert/update statements? If so how can I do this?
public interface ITrigger
{
public Collection<Mutation> augment(Partition update);
}
Some code snippet would be useful.
Try this !!!
public Collection<Mutation> augment(Partition update) {
try {
UnfilteredRowIterator it = update.unfilteredIterator();
while (it.hasNext()) {
Unfiltered un = it.next();
Clustering clt = (Clustering) un.clustering();
Iterator<Cell> cls = update.getRow(clt).cells().iterator();
while(cls.hasNext()){
Cell cell = cls.next();
String data = new String(cell.value().array()); // If cell type is text
}
}
} catch (Exception e) {
...
}
return null;
}
I use this code for static columns
#Override
public Collection<Mutation> augment(Partition update) {
String keyspaceName = update.metadata().ksName;
//for static columns
Row dataRow = update.getRow(Clustering.STATIC_CLUSTERING);
for (Cell cell : dataRow.cells()) {
ColumnDefinition cDefinition = cell.column();
String colName = cDefinition.name.toString();
ByteBuffer value = cell.value();
}
return Collections.EMPTY_LIST;
}
The colName and value variables are data of cell.
public class HelloWorld implements ITrigger
{
private static final Logger logger = LoggerFactory.getLogger(HelloWorld.class);
public Collection<Mutation> augment(Partition partition)
{
String tableName = partition.metadata().cfName;
logger.info("Table: " + tableName);
JSONObject obj = new JSONObject();
obj.put("message_id", partition.metadata().getKeyValidator().getString(partition.partitionKey().getKey()));
try {
UnfilteredRowIterator it = partition.unfilteredIterator();
while (it.hasNext()) {
Unfiltered un = it.next();
Clustering clt = (Clustering) un.clustering();
Iterator<Cell> cells = partition.getRow(clt).cells().iterator();
Iterator<ColumnDefinition> columns = partition.getRow(clt).columns().iterator();
while(columns.hasNext()){
ColumnDefinition columnDef = columns.next();
Cell cell = cells.next();
String data = new String(cell.value().array()); // If cell type is text
obj.put(columnDef.toString(), data);
}
}
} catch (Exception e) {
}
logger.debug(obj.toString());
return Collections.emptyList();
}
}

How to update JTable data with MySQL database properly?

I'm working on a Swing app which is connected to MySQL database. It fetches some data from the DB and shows in the table. Besides, there are 3 buttons that suppose to changes table data ( Add row to table ), update the database (Update database ) and to discard the changes ( Discard changes ) as following,
After clicking the Add row to table button, the new entries from the form should be added in the table. Afterwards if the update button is clicked, the data will be updated in the db. Discard changes will delete the data from the last row of the table and will have nothing to do with db. The app has two classes CoffeesFrame.java and CoffeesTableModel.java I provided the sample code from both of the classes below,
public class CoffeesFrame extends JFrame implements RowSetListener {
private static final long serialVersionUID = 1L;
private static Connection myConn = null;
private static String url = "jdbc:mysql://localhost:3306/myDemo";
private static String user = "student";
private static String password = "student";
// initiate a table object
JTable table;
// labels of the table
// text data fields of the table
// buttons of the table
// initiate a table model object
CoffeesTableModel myCoffeesTableModel;
// table constructor
public CoffeesFrame(Connection myConn) throws SQLException {
table = new JTable();
createNewTableModel(myConn);
/*
label, text field and buttons
*/
Container contentPane = getContentPane();
contentPane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
contentPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
/*
Code for making the GUI
*/
button_ADD_ROW.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// showMessageDialog works
JOptionPane.showMessageDialog(CoffeesFrame.this, new String[] {
"Adding the following row:",
"Coffee name: [" + textField_COF_NAME.getText() + "]",
"Supplier ID: [" + textField_SUP_ID.getText() + "]",
"Price: [" + textField_PRICE.getText() + "]",
"Sales: [" + textField_SALES.getText() + "]",
"Total: [" + textField_TOTAL.getText() + "]" });
try {
// Insert row is not adding data to the table
myCoffeesTableModel.insertRow(
textField_COF_NAME.getText(),
Integer.parseInt(textField_SUP_ID.getText().trim()),
Float.parseFloat(textField_PRICE.getText().trim()),
Integer.parseInt(textField_SALES.getText().trim()),
Integer.parseInt(textField_TOTAL.getText().trim()));
// table.getModel();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
button_UPDATE_DATABASE.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
myCoffeesTableModel.coffeesRowSet.acceptChanges(myConn);
}
catch (Exception ex) {
ex.printStackTrace();
}
try {
createNewTableModel(myConn);
}
catch (Exception el) {
el.printStackTrace();
}
}
});
button_DISCARD_CHANGES.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The changes are DISCARDED");
}
});
}
private void createNewTableModel(Connection myConn) throws SQLException {
myCoffeesTableModel = new CoffeesTableModel(getContentsOfCoffeesTable(myConn));
myCoffeesTableModel.addEventHandlersToRowSet(this);
table.setModel(myCoffeesTableModel);
}
#Override
public void rowSetChanged(RowSetEvent event) {
// TODO Auto-generated method stub
}
#Override
public void rowChanged(RowSetEvent event) {
// TODO Auto-generated method stub
}
#Override
public void cursorMoved(RowSetEvent event) {
// TODO Auto-generated method stub
}
public CachedRowSet getContentsOfCoffeesTable(Connection mycConn)
throws SQLException {
CachedRowSet crs = null;
ResultSet resultSet = null;
Statement stmt = null;
String sql = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
try {
stmt = myConn.createStatement();
resultSet = stmt.executeQuery(sql);
crs = new CachedRowSetImpl();
crs.populate(resultSet);
}
catch (Exception e) {
e.printStackTrace();
}
return crs;
}
public static void main(String[] args) throws SQLException {
try {
myConn = DriverManager.getConnection(url, user, password);
if (myConn != null) {
System.out.println("Connected to the database myDemo");
}
}
catch (SQLException ex) {
System.out
.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
myConn.setAutoCommit(false);
CoffeesFrame coffeesFrame = new CoffeesFrame(myConn);
coffeesFrame.pack();
coffeesFrame.setVisible(true);
}
}
The CoffeesTableModel.java as follows, //
public class CoffeesTableModel implements TableModel {
CachedRowSet coffeesRowSet; // The ResultSet to interpret
ResultSetMetaData metadata; // Additional information about the results
int numcols, numrows; // How many rows and columns in the table
public CoffeesTableModel(CachedRowSet rowSetArg) throws SQLException {
this.coffeesRowSet = rowSetArg;
this.metadata = this.coffeesRowSet.getMetaData();
numcols = metadata.getColumnCount();
// Retrieve the number of rows.
this.coffeesRowSet.beforeFirst();
this.numrows = 0;
while (this.coffeesRowSet.next()) {
this.numrows++;
}
this.coffeesRowSet.beforeFirst();
}
public CachedRowSet getCoffeesRowSet() {
return coffeesRowSet;
}
public void addEventHandlersToRowSet(RowSetListener listener) {
this.coffeesRowSet.addRowSetListener(listener);
}
public void insertRow(String coffeeName, int supplierID, float price,
int sales, int total) throws SQLException {
try {
this.coffeesRowSet.moveToInsertRow();
this.coffeesRowSet.updateString("COF_NAME", coffeeName);
this.coffeesRowSet.updateInt("SUP_ID", supplierID);
this.coffeesRowSet.updateFloat("PRICE", price);
this.coffeesRowSet.updateInt("SALES", sales);
this.coffeesRowSet.updateInt("TOTAL", total);
this.coffeesRowSet.insertRow();
this.coffeesRowSet.moveToCurrentRow();
}
catch (SQLException e) {
e.printStackTrace();
// JDBCTutorialUtilities.printSQLException(e);
}
}
public void close() {
try {
coffeesRowSet.getStatement().close();
}
catch (SQLException e) {
e.printStackTrace();
// JDBCTutorialUtilities.printSQLException(e);
}
}
/** Automatically close when we're garbage collected */
protected void finalize() {
close();
}
/** Method from interface TableModel; returns the number of columns */
public int getColumnCount() {
return numcols;
}
/** Method from interface TableModel; returns the number of rows */
public int getRowCount() {
return numrows;
}
/**
* Method from interface TableModel; returns the column name at columnIndex
* based on information from ResultSetMetaData
*/
public String getColumnName(int column) {
try {
return this.metadata.getColumnLabel(column + 1);
}
catch (SQLException e) {
return e.toString();
}
}
/**
* Method from interface TableModel; returns the most specific superclass
* for all cell values in the specified column. To keep things simple, all
* data in the table are converted to String objects; hence, this method
* returns the String class.
*/
public Class getColumnClass(int column) {
return String.class;
}
/**
* Method from interface TableModel; returns the value for the cell
* specified by columnIndex and rowIndex. TableModel uses this method to
* populate itself with data from the row set. SQL starts numbering its rows
* and columns at 1, but TableModel starts at 0.
*/
public Object getValueAt(int rowIndex, int columnIndex) {
try {
this.coffeesRowSet.absolute(rowIndex + 1);
Object o = this.coffeesRowSet.getObject(columnIndex + 1);
if (o == null)
return null;
else
return o.toString();
}
catch (SQLException e) {
return e.toString();
}
}
/**
* Method from interface TableModel; returns true if the specified cell is
* editable. This sample does not allow users to edit any cells from the
* TableModel (rows are added by another window control). Thus, this method
* returns false.
*/
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
// Because the sample does not allow users to edit any cells from the
// TableModel, the following methods, setValueAt, addTableModelListener,
// and removeTableModelListener, do not need to be implemented.
public void setValueAt(Object value, int row, int column) {
System.out.println("Calling setValueAt row " + row + ", column "
+ column);
}
public void addTableModelListener(TableModelListener l) {
}
public void removeTableModelListener(TableModelListener l) {
}
}
The data shows in the table is grabbed from the db and presented as table. The "Add row to table" shows the pop-up from the form insertion but don't put the data as new row in the end of the table. However, I'm not getting any error. The "Update database" button is not working and provides java.sql.SQLException: Table not specified.. How can I improve the code ?
Instead of implementing the TableModel interface, you should be extending from the AbstractTableModel, this has default functionality of some of the "normal" functionality you don't want to replicated.
Remove the addTableModelListener and removeTableModelListener, your current implementation has essentially broken the model's contract by not providing the ability to make notifications to other observers (like the JTable)
Your insertRow method MUST call fireTableRowsInserted (from AbstractTableModel) in order to notify the JTable that the model has changed and that it needs to update itself with the new data
Java makes no guarantees that finalize will be called, don't rely on it
getRowCount will be effected by the size of the RowSet, therefore, you need to be able to either keep a running value (ie you need to increment it when you add new rows) or calculate the number of rows from the RowSet itself. I believe you can do this by moving the cursor to the end (or beyond the last position) and using getRow, don't forget though, ResultSet is 1 based, not 0 based which JTable expects

how to list an items to a JTable

I am trying to create a checkout simulation for my coursework. So every time I search for an item I can retrieve it from the database and display it on the JTable. However, once I add an item to the list and try to add another item the old item get replaced by the new item.
I am trying to list all the item in the JTable, this is my code:
DBConnection db = new DBConnection();
try {
ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '"+ id + "'");
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
System.out.println(e);
}`
The main problem is DbUtils.resultSetToTableModel(rs), which is creating a brand new TableModel, filled with the contents of the ResultSet, this, when applied to the JTable is replacing the view with the contents of the TableModel.
In order to be able to update the table, you need to update the existing TableModel...
There are a few ways this might be achieved, by the simplest might be to use a DefaultTableModel...
Start by creating a class instance field of a DefaultTableModel...
public class ... {
//...
private DefaultTableModel stockTableModel;
//...
Then, when you want to load the stock items, you will need to initialise the model, if it's not already initialised, and then add the new results to it...
DBConnection db = new DBConnection();
try (ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '" + id + "'")) {
if (stockTableModel == null) {
stockTableModel = new DefaultTableModel();
for (int col = 0; col < metaData.getColumnCount(); col++) {
stockTableModel.addColumn(metaData.getColumnName(col + 1));
}
jTable.setModel(model);
}
while (rs.next()) {
Vector rowData = new Vector(metaData.getColumnCount());
for (int col = 0; col < metaData.getColumnCount(); col++) {
rowData.add(rs.getObject(col + 1));
}
stockTableModel.addRow(rowData);
}
} catch (SQLException exp) {
exp.printStackTrace();
}
Take a look at How to Use Tables and JDBC Database Access for more details
You can create a custom data model that allows you to insert new rows to table.
lets say that you have class, that can hold your query result fields.
public class Item implements Comparable<Item> {
private Long id;
private String message;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
public String getMessage() {
return message;
}
public void setMessage(String value) {
this.message= value;
}
#Override
public int compareTo(Item o) {
return id.compareTo(o.id);
}
}
and it needs to go to table, which has been defined somewhere like:
JTable table =new JTable();
this is a data model to your table
public class Model extends AbstractTableModel {
private List<Item> items;
public Model() {
items = new ArrayList<>();
}
#Override
public int getRowCount() {
return items.size();
}
#Override
public int getColumnCount() {
return 3;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex > items.size() - 1 || rowIndex < 0) {
return "";
}
final Item get = items.get(rowIndex);
switch (columnIndex) {
case 0:
return get.getId();
case 1:
return get.getMessage();
}
return "";
}
#Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "id";
case 1:
return "message";
}
return "";
}
public void addItem(Item i) {
items.add(i);
fireTableDataChanged();
}
public void addItem(ResultSet rs) {
try {
Item item = new Item();
item.setId(rs.getLong("ID"));
item.setMessage(rs.getString("MESSAGE"));
items.add(item);
fireTableDataChanged();
} catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
now create field
Model myModel=new Model();
and set it as a table model
table.setModel(myModel);
now every time you need to add something to table, just use our table model (i created two methods to insert data public void addItem(Item i) and public void addItem(ResultSet rs).
this should work. If you need to clear table sometimes, just add pubic method public void clear() to your model, in which you will clear items list and call fireTableDataChanged();. It is necessary, otherwise GUI will not refresh.
EDIT
Your code should be like
DBConnection db = new DBConnection();
try {
ResultSet rs = DBConnection.stmt.executeQuery("SELECT ID, MESSAGE FROM STOCK WHERE ID = '" + id + "'");
myModel.add(rs);
} catch (Exception e) {
System.out.println(e);
}
Just add a row to your JTable Model every time you have your result...
refer to this SO question
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
or in your case
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{searchResultData});

Spring mvc category tree

I have category tree.My category has n number subcategories.How do list recursion category on jsp?
List<Category> categories = categoryService.findAll();
modelMap.put("categories",categories)
Using JSTL, try something like this:
Simple List of Items
<c:forEach var="category" items="${categories}">
${category.id} -> ${category.name}
</c:forEach>
Nested List of Items
If you have nested categories, try something like the following custom tag.
public class CategoryDisplayTag extends TagSupport
{
public int doStartTag() throws JspException
{
Category rootCategory = new Category();
printEachCategory(rootCategory);
return SKIP_BODY;
}
private void printEachCategory(Category category)
{
JspWriter out = pageContext.getOut();
try
{
out.write("Category: " + category.getName());
for (Category c : category.getCategories())
{
out.write("Sub-category: " + c.getName());
printEachCategory(c);
}
}
catch (IOException e1)
{
throw new RuntimeException(e1);
}
}
}

Categories