I want to retrieve some data from a filtered row.
This is how i filter my table :
String makeText = makeFilterCombo.getSelectedItem().toString();
if (makeText == "All") {
makeText = "";
}
String numar = getEssRegex();
String impact = impactBox.getSelectedItem().toString();
if (impact == "All") {
impact = "";
}
TableModel model;
model = jTable1.getModel();
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
jTable1.setRowSorter(sorter);
List<RowFilter<Object, Object>> rfs = new ArrayList<RowFilter<Object, Object>>(2);
rfs.add(RowFilter.regexFilter(makeText, 2));
rfs.add(RowFilter.regexFilter(numar, 5));
rfs.add(RowFilter.regexFilter(impact, 9));
RowFilter<Object, Object> af = RowFilter.andFilter(rfs);
sorter.setRowFilter(af);
And this is how i try to get a value from a filtered row:
int f = search(connectedCarIndex);
connectedImage1 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 10).toString();
connectedImage2 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 11).toString();
connectedImage3 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 12).toString();
System.out.println(connectedImage1 + "-------" + connectedImage2 + "------" + connectedImage3);
But none of this works ?
Can anybody help me ?
The code works and i can see the connected image name if the rows are shown
int f = search(connectedCarIndex);
I have no idea what the search(...) method does.
If you are searching the data that is displayed in the table then you would just use:
table.getValueAt(...);
If you are searching all the data that is stored in the TableModel then you would use:
table.getModel().getValueAt(...);
there is no need to convert the index if you know what you are searching.
Related
So I'm trying to after searching a name click on the table and then edit it in other table, the problem is that I'm not getting the right ID but instead only getting the ID that is the first.
JTable
Search in action
ID wrong
Edit Code
int linha = this.jTable1.getSelectedRow();
int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(linha, 0));
Utilizador uti = UtilizadorJpaController.read(idUtilizador);
CriarCliente updateCliente = new CriarCliente(uti);
updateCliente.setVisible(true);
Search Code
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
TableRowSorter<DefaultTableModel> tr = new TableRowSorter<DefaultTableModel>(model);
jTable1.setRowSorter(tr);
tr.setRowFilter(RowFilter.regexFilter(jTextField1.getText().trim(),1))
When you sort or filter a table, the data in the TableModel doesn't change. Only the view of the data changes.
If you want to get the data from the model, then you need to convert the "view row" to the "model row":
int linha = this.jTable1.getSelectedRow();
int modelRow = jTable1.convertRowIndexToModel(linha);
int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(modelRow, 0));
//int idUtilizador = Integer.parseInt((String)(this.jTable1.getModel() ).getValueAt(linha, 0));
Also, why are you using Integer.parseInt(...)? If the data in the model is an integer value, then it should be stored as an Integer value, not a String value.
I would like to ask how to display all rows in Java using JTable.
I tried using a while condition inside is a result.next() to be evaluated.
I tried printing it using System.out.println and it display all records however when I tried it on JTable it only displays the last row.
while(results.next()) {
String id = results.getString("id");
String date_collected = results.getString("date_collected");
String date_disposed = results.getString("date_disposed");
String person_in_charged = results.getString("person_in_charged");
String status = results.getString("status");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][]){
{id, date_collected, date_disposed, person_in_charged, status}
},
new String [] {
"ID", "Date collected", "Date disposed", "person in charged",
"status"
}
));
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
}
}
Can you help me? Thanks!
Summary of the solution:
Solved by Usagi Miyamoto and isaace
The solution was to create the List this way
List<Object[]> data = new ArrayList<>()
Reason:
List is an interface, an abstract, and cannot be instantiated directly
ArrayList is a class that implements List
Complete solution of Usagi Miyamoto
// to hold the data
List<Object[]> data = new ArrayList<>();
// loop through the ResultSet
while(results.next())
{
String id = results.getString("id");
String date_collected = results.getString("date_collected");
String date_disposed = results.getString("date_disposed");
String person_in_charged = results.getString("person_in_charged");
String status = results.getString("status");
// add a new row of data
data.add(new Object[] {id, date_collected, date_disposed, person_in_charged, status});
}
// after the loop: set the data as the model
jTable1.setModel(new javax.swing.table.DefaultTableModel(
// convert from List to array
data.toArray(new Object[][data.size()],
// column headers
new String [] { "ID", "Date collected", "Date disposed", "person in charged", "status" }
));
// other details from your code: moved outside of the loop...
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0)
{
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
}
Try cumulating the data, something like this:
// to hold the data
List<Object[]> data = new ArrayList<>();
// loop through the ResultSet
while(results.next())
{
String id = results.getString("id");
String date_collected = results.getString("date_collected");
String date_disposed = results.getString("date_disposed");
String person_in_charged = results.getString("person_in_charged");
String status = results.getString("status");
// add a new row of data
data.add(new Object[] {id, date_collected, date_disposed, person_in_charged, status});
}
// after the loop: set the data as the model
jTable1.setModel(new javax.swing.table.DefaultTableModel(
// convert from List to array
data.toArray(new Object[][data.size()],
// column headers
new String [] { "ID", "Date collected", "Date disposed", "person in charged", "status" }
));
// other details from your code: moved outside of the loop...
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0)
{
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
}
The DefaultTableModel should be created and set outside of the loop.
DefaultTableModel model = new DefaultTableModel();
model.addColumn("you column names");
model.addColumn("another column name");
//you can add all your column headers here
JTable table = new JTable();
table.setModel(model);
while(rs.next())
{
String id = results.getString("id");
String date_collected = results.getString("date_collected");
String date_disposed = results.getString("date_disposed");
String person_in_charged = results.getString("person_in_charged");
String status = results.getString("status");
model.addRow(new Object[]{id, date_collected, date_disposed, person_in_charge, status });
}
and continue with the rest of your code here.
I would like to print the labels of traindata / testdata used in classification. Here is the definition of both inputs (using deep4j).
InputSplit[] inputSplit = fileSplit.sample(pathFilter, splitTrainTest, 1 - splitTrainTest);
InputSplit trainData = inputSplit[0];
InputSplit testData = inputSplit[1];
that are then transformed in DataSetIterator like this :
ImageRecordReader recordReader = new ImageRecordReader(height, width, channels, labelMaker);
recordReader.initialize(trainData, null);
trainIter = new RecordReaderDataSetIterator(recordReader, batchSize, 1, numLabels);
Then I want to print how many examples per labels where found in each iterator in this function :
public void print(DataSetIterator iter){
HashMap<String, Integer> hash = new HashMap<String, Integer>();
while(iter.hasNext()){
DataSet example = iter.next();
for(int i = 0 ; i<numLabels ; i++){
if(example.getLabels().getDouble(i)==1.){
String label = example.getLabelName(i);
if(hash.containsKey(label))
hash.put(label, hash.get(label)+1);
else
hash.put(label, 1);
}
}
}
for (String label: hash.keySet()){
System.out.println(" label : " + label.toString() + ", " + hash.get(label) + " examples");
}
}
The issue is that it displays only one example per label, whereas there should much more... And when I don't split my dataset using fileSplit.sample() the function displays the right number of examples.
Any suggestion ?
If you use a dataset you can use the toString() of the dataset.getFeatureMatrix() and dataset.getLabels()
If you want to print just the label counts, you can use dataset.labelCounts() I would look more at the dl4j javadoc:
http://deeplearning4j.org/doc
How do I return all timestamped versions of an HBase cell with the Get.setMaxVersions(10) method where 10 is an arbitrary number (could be something else like 20 or 5)? The following is a console main method that creates a table, inserts 10 random integers, and tries to retrieve all of them to print out.
public static void main(String[] args)
throws ZooKeeperConnectionException, MasterNotRunningException, IOException, InterruptedException {
final String HBASE_ZOOKEEPER_QUORUM_IP = "localhost.localdomain"; //set ip in hosts file
final String HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT = "2181";
final String HBASE_MASTER = HBASE_ZOOKEEPER_QUORUM_IP + ":60010";
//identify a data cell with these properties
String tablename = "characters";
String row = "johnsmith";
String family = "capital";
String qualifier = "A";
//config
Configuration config = HBaseConfiguration.create();
config.clear();
config.set("hbase.zookeeper.quorum", HBASE_ZOOKEEPER_QUORUM_IP);
config.set("hbase.zookeeper.property.clientPort", HBASE_ZOOKEEPER_PROPERTY_CLIENTPORT);
config.set("hbase.master", HBASE_MASTER);
//admin
HBaseAdmin hba = new HBaseAdmin(config);
//create a table
HTableDescriptor descriptor = new HTableDescriptor(tablename);
descriptor.addFamily(new HColumnDescriptor(family));
hba.createTable(descriptor);
hba.close();
//get the table
HTable htable = new HTable(config, tablename);
//insert 10 different timestamps into 1 record
for(int i = 0; i < 10; i++) {
String value = Integer.toString(i);
Put put = new Put(Bytes.toBytes(row));
put.add(Bytes.toBytes(family), Bytes.toBytes(qualifier), System.currentTimeMillis(), Bytes.toBytes(value));
htable.put(put);
Thread.sleep(200); //make sure each timestamp is different
}
//get 10 timestamp versions of 1 record
final int MAX_VERSIONS = 10;
Get get = new Get(Bytes.toBytes(row));
get.setMaxVersions(MAX_VERSIONS);
Result result = htable.get(get);
byte[] value = result.getValue(Bytes.toBytes(family), Bytes.toBytes(qualifier)); // returns MAX_VERSIONS quantity of values
String output = Bytes.toString(value);
//show me what you got
System.out.println(output); //prints 9 instead of 0 through 9
}
The output is 9 (because the loop ended at i=9, and I don't see multiple versions in Hue's HBase Browser web UI. What can I do to fix the versions so it gives me 10 individual results for 0 - 9 instead of one result of only the number 9?
You should use getColumnCells on Result to get all versions (depending on MAX_VERSION_COUNT you have set in Get). getValue returns the latest value.
Sample Code:
List<Cell> values = result.getColumnCells(Bytes.toBytes(family), Bytes.toBytes(qualifier));
for ( Cell cell : values )
{
System.out.println( Bytes.toString( CellUtil.cloneValue( cell ) ) );
}
This is a deprecated approach which matches the version of HBase I am currently working on.
List<KeyValue> kvpairs = result.getColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
String line = "";
for(KeyValue kv : kvpairs) {
line += Bytes.toString(kv.getValue()) + "\n";
}
System.out.println(line);
Then, going one step further, it is important to note the setMaxVersions method must be called at table creation to allow for more than a default three values to be inserted into a cell. Here's the updated table creation:
//create a table based on variables from question above
HTableDescriptor tableDescriptor = new HTableDescriptor(tablename);
HColumnDescriptor columnDescriptor = new HColumnDescriptor(columnFamily);
columnDescriptor.setMaxVersions(MAX_VERSIONS);
tableDescriptor.addFamily(columnDescriptor);
hba.createTable(tableDescriptor);
hba.close();
I have a HBase table (from java) and i want to query the table by list of keys. I did the following, but its not working.
mFilterFeatureIt = mFeatureSet.iterator();
FilterList filterList=new FilterList(FilterList.Operator.MUST_PASS_ONE);
while (mFilterFeatureIt.hasNext()) {
long myfeatureId = mFilterFeatureIt.next();
System.out.println("FeatureId:"+myfeatureId+" , ");
RowFilter filter = new RowFilter(CompareOp.EQUAL,new BinaryComparator(Bytes.toBytes(myfeatureId)) );
filterList.addFilter(filter);
}
outputMap = HbaseUtils.getHbaseData("mytable", filterList);
System.out.println("Size of outputMap map:"+ outputMap.szie());
public static Map<String, Map<String, String>> getHbaseData(String table, FilterList filter) {
Map<String, Map<String, String>> data = new HashMap<String, Map<String, String>>();
HTable htable = null;
try {
htable = new HTable(HTableConfiguration.getHTableConfiguration(),table);
Scan scan = new Scan();
scan.setFilter(filter);
ResultScanner resultScanner = htable.getScanner(scan);
Iterator<Result> results = resultScanner.iterator();
while (results.hasNext()) {
Result result = results.next();
String rowId = Bytes.toString(result.getRow());
List<KeyValue> columns = result.list();
if (null != columns) {
HashMap<String, String> colData = new HashMap<String, String>();
for (KeyValue column : columns) {
colData.put(Bytes.toString(column.getFamily()) + ":"+ Bytes.toString(column.getQualifier()),Bytes.toString(column.getValue()));
}
data.put(rowId, colData);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (htable != null)
try {
htable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
FeatureId:80515900 ,
FeatureId:80515901 ,
FeatureId:80515902 ,
Size of outputMap map: 0
I see that value of feature id is what i want , but I always get the above output even if the key is present in the hbase table. Can anyone tell me what am i doing wrong ?
EDIT:
I posted the code for my hbase util method too above, so that you can point me to any bugs there.
I am trying to do an SQL equivalent of select * FROM mytable where featureId in (80515900, 80515901, 80515902) My idea to achieve the same in HBase was to create a filter list with one filter for each featureId. Is that correct ?
Here is the content of my table
scan 'mytable', {COLUMNS => ['sample:tag_count'] }
80515900 column=sample:tag_count, timestamp=1339304052748, value=4
80515901 column=sample:tag_count, timestamp=1339304052748, value=0
80515902 column=sample:tag_count, timestamp=1339304052748, value=3
80515903 column=sample:tag_count, timestamp=1339304052748, value=1
80515904 column=sample:tag_count, timestamp=1339304052748, value=2
Its not returning any data as while inserting the data into hbase,
the data-type for key is 'String' (from your scan result) & while fetching, the value passed in RowFilter has 'long' data type. Use this filter:
RowFilter filter = new RowFilter(CompareOp.EQUAL,new
BinaryComparator(Bytes.toBytes(myfeatureId.toString())) );
the while loop will always generate a new filter and added to the filter list.
The circuit are all the keys in the filter. This filter can never apply to a single row. Create only one filter in the while loop pointing to a knowing "myfeatureId".
while (mFilterFeatureIt.hasNext()) {
long myfeatureId = mFilterFeatureIt.next();
System.out.println("FeatureId:"+myfeatureId+" , ");
if ( myfeatureId=="80515902") {
RowFilter filter = new RowFilter(CompareOp.EQUAL,new BinaryComparator(Bytes.toBytes(myfeatureId)) );
filterList.addFilter(filter);
}
}
EDIT
For rows quantity, the query is responsible. HBase is not
HBase filters
Filters push row selection criteria out to the HBase. Rows can be filtered remotely and in parallel. Using these functions helps you to avoid sending rows to the client that are not needed.
To get a part out of the key, gets all from 80515900 .. 80515909 try this
of course remove from the loop
RowFilter filter = new RowFilter(CompareOp.EQUAL,new BinaryComparator(Bytes.toBytes(myfeatureId)) );
filterList.addFilter(filter);
and add above the line outputMap = HbaseUtils.getHbaseData("mytable", filterList);
....
RowFilter filter = new RowFilter(CompareOp.EQUAL,new SubStringComparator("8051590"));
filterList.addFilter(filter);
outputMap = HbaseUtils.getHbaseData("mytable", filterList);