How to retrieve row's last modification timestamp in HBase? - java

Does each Cell in returned Result object have same timestamp?
Is it save to do something like this?
try (Table table = connectionFactory.getConnection().getTable(TABLE)) {
try (ResultScanner scanner = table.getScanner(generateScan(systemId))) {
for (Result result: scanner) {
if (result == null) {
break;
}
long ts = result.rawCells()[0].getTimestamp();
System.out.println("Row last update time: " + ts);
}
}
}
Will I obtain time stamp of the last row modification?

Cells in Result can have different timestamp. Each cell is a combination of CF:C:V, where CF is column family, C is a column and V is a version. Even if you store only 1 version, you can update columns of a cell independently. Cell timestamp is updated when you store something.
For example you have table user with cf:main and two columns name and age. If you update both columns in same Put they will have same timetamp. If you update only name column, timestamps will be different. So generally it depends on your usage pattern.

Related

Insert checkbox in DefaultTableModel using database data

I'm using DefaultTableModel in NetBeans in showing my records from MySQL database. My data is able to display, but what I want is that to display a checkbox column at the end of my table.
I understand it needs to be overridden, but I don't know how and where to start. I see tons of example from the internet but they are using static string data, not from database. Until now I still don't get it. A help will be much appreciated.
Below is my sample code.
try {
conn = DatabaseConnect.connect();
ps = conn.prepareStatement("SELECT productID, name, quantity, price, checked FROM tbl_inventory");
rs = ps.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch(SQLException ex) {
}
jTable2 is able to display my records from tbl_inventory. The "checked" column from my database table tbl_inventory has default boolean value of 0. But I don't know how to display it as checkbox in my JTtable.
The "checked" column from my database table tbl_inventory has default boolean value of 0. But I don't know how to display it as checkbox in my JTtable.
The easiest way is to convert the "checked" data to a Boolean value as you create the TableModel. Then the default renderer/editor will be used.
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
This means you can't use the above method. You need to copy the data yourself and do the conversion on the checked column.
Check out Table From DataBase. The last example Table From Database Example shows how to copy the data without any conversion.
You will need to modify the code with something like:
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
if (i == ?) // convert checked column
{
int value = rs.getInt(i);
row.addElement( value == 0 ? Boolean.FALSE : Boolean.TRUE );
}
else
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}

Shown JTable from Database with calculate formula

I want to shown a JTable with Value from database, but in some coloumn that calculate with a formulation. for excample like this :
Table in database :
from that table i want to shown in JTable, with calculation :
coloumn Pendidikan and Skripsi, value is direct from database.
column Penelitian and MK, value from database calculate with formula value in row minus average from that coloumn. the result shown in table:
so, how to make it like that?, but the formula building in java
this my code to show data to JTable:
tabModel = new DefaultTableModel(null,header);
tabel.setModel(tabModel);
try { String query = "SELECT NIP,Pendidikan,Penelitian,MK,Skripsi FROM table1 group by NIP";
java.sql.Statement Stat = Connect.createStatement();
java.sql.ResultSet rs = Stat.executeQuery(query);
while (rs.next()) {
String nip = rs.getString("NIP");
String bidang = rs.getString("Bidang");
String pendidikan = rs.getString("Pendidikan");
String penelitian = rs.getString("Penelitian");
String mk = rs.getString("MK");
String skripsi = rs.getString("Skripsi");
String[] dataTampil = {nip,bidang,pendidikan,penelitian,mk,skripsi};
tabModel.addRow(dataTampil);
tabel.setModel(tabModel);
}
}catch(Exception e){}
}
but, i can't calculate the table with differnt formula for every coloumn.
for coloumn Pendidikan and skripsi the value direct from database, but for coloumn Penelitian and MK the value form Value in Row minus Average for thats coloumn.
You should first be using rs.getInt() since as your sample shows in your original question, that they are in fact integers. Once you have them as Integers you can do whatever calculations you need to for Penelitian and MK instead of using the ones from the database. In other words, for these two variables, set them to whatever calculation they should be instead of just using the value from rs.getInt()

How do I use use data from a Resultset in a JTable?

I am doing a school project and I am having trouble with storing the data from a resultset in a JTable. Previously I had used DButils but now I am wondering if there is a way to do the same thing without having to used external class files or if it is easier to use DButils.
The data is coming from only one table and all that needs to happen is the data must be displayed in the JTable.
I would post my code here but I have looked and the only tutorials I could find were ones on how to populate a JTable using and Object [][]. I am using JDBC to create the connection.
Thanks in advance.
Well this will require several steps.
I will explain my way, which is good for very large sets, but a little complicated if you only want to show a few lines. Still I'm sure it will help you. This method will load the required records on the fly, not the whole set before hand. It creates the illusion of having the whole set, but with out having to wait for a lengthy load.
1) Ok, first, let's assume that we have a nice JFrame that you can display, to start with. So first I will add a JScrollPane, and inside it I will add a JTable. Run it and make sure you have a nice window with an empty JTable inside scroll bars.
2) So next you need a data source for the JTable. Since a JTable is a very generic component not made specifically for SQL resultSets, it requires a data source that implements javax.swing.table.AbstractTableModel which has nothing to do with SQL. So we will now create a TableModelClass which will implement AbstractTableModel, then we will add this to the JTable and it will start working. Of course, the trick is to implement all of AbstractTableModel's methods that get data by using our SQL result set, and this is up to you. From here is my suggestion ->
3) Since this will be dynamic, we will not need to load all the data before hand, but we need an initial set to display. I will have a Object [][] of a fixed size, lets say 200 - 300 rows. So I will initially execute the SQL and fill the array with the buffer size of 200-300 rows. How much to cache will depend on 2 things: 1 It shall be enough to get all the data for the current display size of the JTable, and 2, it should be small enough so that as we scroll and get subsequent caches it executes very fast.
4) Now let's begin implementing all AbstractTableModel's interface methods.
5) First we look at the initial result set and report the number of columns. Just add a class variable, set the column count and return it using: public int getColumnCount( ). This will not change from now.
6) Also looking at the result set metadata, make a list variable in the class and add the column names returned in the meta data. Using this list return the column names in "getColumnName( int col )". Of course, the col index is the column position in the result set.
7) Now lets do "int getRowCount( )". Inside the TableModelClass keep a variable to contain the rowCount and return it in this method. TIP: Don’t worry for now, set it to a fixed large number like 65000, this will let scroll as you dynamically load the records. Once we hit the end we will set the number to the real value and the scroll pane will adjust to the correct proportions. Trust me, it works ok.
8) Now comes the fun part. As the JTable presents the first "page" of the table and as the user scrolls it will begin calling "getValueAt( int row, int col )". This will map directly to our Object[][], but since we only have a cache, and not the whole table, as the user scrolls down we will need to fetch more data. I do this:
public Object getValueAt( int row, int col )
{
// load failed before, no more trying...
if( loadExceptionOccur || ( row >= visualTableSize ) ) return( "" );
// check if requested row is OUT of cache …
try{
if(
// less than cache lower limit...
( ( row < startRow )
||
// Beyond cache upper limit...
( row >= startRow + tableDataCache.size()) )
// Stop unnecessary loading, because of Jtable readjusting
// its visual table size and redrawing the entire table.
&& !tableRedraw
// yes, get new cache...
){
load( row ); // <- below is code
}
// now we now the row is in cache, so ->
// verify requested cell in cache, or beyond data rows,
if(
// greater than lower limit
( row >= startRow )
&&
// less than upper limit...
( row < ( startRow + tableDataCache.size() ) )
){
tableRedraw = false;
// just get the data from the cache. tableDataCache is just your Object[][] array…
Object cellValue = ( ( recordClass ) tableDataCache.get( row-startRow ) ).getValueAt( col );
return ( cellValue );
}
else{
// just show as blank
return( "" );
}
}
catch( Exception error ){
…
In case of a cache miss you need to reload a cache of data. I will normally load some rows before the requested row and some beyond, at least for a JTable page size, so that we only go once to the db to render a screen. The bigger the cache the more scrolling before loading, but the larger the time it takes to load a cache. If you fine tune it, the cache processing might be almost unnoticeable.
Here is the implementation of "load":
public void load( int rowIndex )
throws KExceptionClass
{
// calculate start of new cache, if not enough rows for top half of cache
// then start from 0
int halfCache = cacheSize / 2 ;
int DBStartRow = 0;
if( rowIndex > halfCache ) DBStartRow = rowIndex - halfCache;
//Do query to DB
try{
SQLP.load( DBStartRow, cacheSize ); // <- using jdbc load from DbsartRow as many rows as cacheSize. Some sample SQL paging code below ->
}catch( Exception loadError ){
// if the database fails or something do this, so you don’t get a billion errors for each cell. ->
//set load failed flag, kill window
loadExceptionOccur = true;
visualTableSize = 0;
tableDataCache = new ArrayList< recordClass >();
fireTableDataChanged(); // clear the Jtable
// log error
log.log( this, KMetaUtilsClass.getStackTrace( loadError ) );
// show error message
throw new KExceptionClass( "Could not load table data! " , loadError );
}
//Load rows into the cache list.
//Key field values are in the cache list as the last field in each record.
tableDataCache.clear(); // the Object [][], wrapped in class
while( SQLPreprocessor.nextRowValue() ) {
SQL.fetch( record ); //<- get JDBC rows to table cache
tableDataCache.add( record ); // this uses my library, change to JDBC or what ever you use to access SQL
}
log.log( this, "cacheList size = " + tableDataCache.size());
//---------
if(
// Last requested row number
( DBStartRow + cacheSize ) >
// Last replied row number
( SQLPreprocessor.getloadedStartRowIndex() + SQLPreprocessor.getloadedRowCount() )
){
// It is the end of table.
// The visual table is readjusted accordingly.
visualTableSize = SQLPreprocessor.getloadedStartRowIndex() + SQLPreprocessor.getloadedRowCount();
fireTableDataChanged();
tableRedraw = true;
}
startRow = SQLPreprocessor.getloadedStartRowIndex();
log.log( this, "visualTableSize = " + visualTableSize );
}
Ok this will dynamically load the data in small caches which will give the impression of having the whole set.
If the user scrolls to the middle or all the way to the end, the JTable will ask only for the data need to display not all the rows as it moves, so, if you have a 10K row table, but the JTable is only 20 rows high, a scroll to the end will only take 40 - 50 rows to load. Pretty nice. Your users will be impressed.
Now the thing is that the load assumes that you have a SQL cursor that moves forward and backwards by row number. This simple thing is quite a challenge in SQL. For Oracle check : http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html
Ok, hope that helps.--
Of course there's a way: iterate through the ResultSet and add what you find to the Object [][] array that gets passed to the JTable. There's one row in the 2D array for each row in the ResultSet; the columns are the values.
The problem you'll have is that you won't know how many rows came back without iterating through it. That's why loading it into a Map<String, Object> might be a better idea.
Here's an example showing how to do it. You'll find that method (and more) at my answer to this question:
java sql connections via class
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException {
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try {
if (rs != null) {
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next()) {
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i) {
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
} finally {
close(rs);
}
return results;
}

Java - Modulus - Adding from one table to another

I have a JTable of which one column is pre-filled with 30min time slots (6.30-24.00).
Now I have another table which has a list of movie titles which contains a column with the duration of the movie (in minutes - e.g. 140 minutes).
Now I have a button that does this. I made a piece of code, which funnily enough, sometimes works and sometimes doesn't (after I add 3-4 titles). It adds to the time slots according to the math equation.It gives me :
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "DRAMA"
This is the code:
btnAddProg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int dur = Integer.parseInt(progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+1).toString()) / 30;
int durT = Integer.parseInt(progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+1).toString());
if(durT % 30 != 0)
{
dur += 1;
}
for(int i = 0; i < dur; i++)
{
String value = progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()).toString();
String value2 = progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+2).toString();
channel1DataTitle.set(chOneTable.getSelectedRow()+i, value);
channel1DataGenre.set(chOneTable.getSelectedRow()+i, value2);
}
chOneTable.repaint();
} catch (IndexOutOfBoundsException f) {
JOptionPane.showMessageDialog(frame,
"Please select a row in the Channel table!",
"Channel row not selected",
JOptionPane.PLAIN_MESSAGE);
}
}
});
Can anyone tell me what's wrong?
It works when you click on the proper column and fails when you click on another, doesn't it? You have fixed logic (parsing the duration number) applied to a variable column (depending on the exact column the user clicked). Access the column with a fixed number, don't check for the selected column index.
You are trying to parse a String which does not translate into a number. It looks like the problem is you are working off of whatever the user has selected. You either need to restrict the data you are processing to be from certain columns in your table, or validate the data before trying to process it.

How to get columns from Excel files using Apache POI?

In order to do some statistical analysis I need to extract values in a column of an Excel sheet. I have been using the Apache POI package to read from Excel files, and it works fine when one needs to iterate over rows. However I couldn't find anything about getting columns neither in the API (link text) nor through google searching.
As I need to get max and min values of different columns and generate random numbers using these values, so without picking up individual columns, the only other option is to iterate over rows and columns to get the values and compare one by one, which doesn't sound all that time-efficient.
Any ideas on how to tackle this problem?
Thanks,
Excel files are row based rather than column based, so the only way to get all the values in a column is to look at each row in turn. There's no quicker way to get at the columns, because cells in a column aren't stored together.
Your code probably wants to be something like:
List<Double> values = new ArrayList<Double>();
for(Row r : sheet) {
Cell c = r.getCell(columnNumber);
if(c != null) {
if(c.getCellType() == Cell.CELL_TYPE_NUMERIC) {
valuesadd(c.getNumericCellValue());
} else if(c.getCellType() == Cell.CELL_TYPE_FORMULA && c.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC) {
valuesadd(c.getNumericCellValue());
}
}
}
That'll then give you all the numeric cell values in that column.
Just wanted to add, in case you have headers in your file and you are not sure about the column index but want to pick columns under specific headers (column names) for eg, you can try something like this
for(Row r : datatypeSheet)
{
Iterator<Cell> headerIterator = r.cellIterator();
Cell header = null;
// table header row
if(r.getRowNum() == 0)
{
// getting specific column's index
while(headerIterator.hasNext())
{
header = headerIterator.next();
if(header.getStringCellValue().equalsIgnoreCase("column1Index"))
{
column1Index = header.getColumnIndex();
}
}
}
else
{
Cell column1Cells = r.getCell(column1);
if(column1Cells != null)
{
if(column1Cells.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
// adding to a list
column1Data.add(column1Cells.getNumericCellValue());
}
else if(column1Cells.getCellType() == Cell.CELL_TYPE_FORMULA && column1Cells.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC)
{
// adding to a list
column1Data.add(column1Cells.getNumericCellValue());
}
}
}
}

Categories

Resources