Cassandra 3.x trigger column values - java

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();
}
}

Related

sheet.getDataValidations() returns an empty list when a cell is validated by a sequence on another sheet

I have a workbook with two sheets:
Sheet1
Sheet2
And there is a sequence on Sheet2 at the range of A1 to A5:
aa
bb
cc
dd
ee
And in Sheet1, the cell A1 is validated by the sequence in Sheet2.
Excel screenshot
However, sheet.getDataValidations() returns an empty list for this case.
Did I miss something?
public static void main(String[] args) throws Exception {
String filePath = "/Users/fujiexiang/ExcelWorkbook.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath));
Sheet sheet = workbook.getSheetAt(0);
System.out.println("" + dataValidations + " " + dataValidations.size());
}
"[] 0" was printed out.
Apache POI bases on Office Open XML published for Excel 2007. And Excel 2007 had not supported data validation list constraint coming directly from another worksheet. There had must be created a named range for the data validation list constraint. Now current Excel versions support data validation list constraint coming directly from another worksheet but of course not backwards compatible. That's why apache poi also cannot read those constraints as it only reads CTDataValidations which are from Office Open XML published for Excel 2007.
In the XML the difference looks like so in /xl/worksheets/sheet1.xml:
Excel 2007:
<dataValidation type="list" allowBlank="1" showInputMessage="1" showErrorMessage="1" sqref="A1">
<formula1>Sheet2_A1_A5</formula1>
</dataValidation>
There "Sheet2_A1_A5" is a named range in the workbook that points to Sheet2!A1:A5.
Excel 365:
<x14:dataValidation type="list" allowBlank="1" showInputMessage="1" showErrorMessage="1">
<x14:formula1>
<xm:f>Sheet2!A1:A5</xm:f>
</x14:formula1>
<xm:sqref>A1</xm:sqref>
</x14:dataValidation>
There "Sheet2!A1:A5" is a direct reference to the other worksheet.
As you see, the new x14:dataValidation is in a separate name space. This is not covered by apache poi until now.
What one could do is using low level XML parsing methods to get the new XSSFX14DataValidations additional to the XSSFDataValidations. The following example shows a working draft for how to do this.
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlCursor;
import javax.xml.namespace.QName;
class ReadExcelDataValidaton {
static java.util.List<XmlObject> getX14DataValidations(XSSFSheet sheet) {
java.util.List<XmlObject> x14DataValidations = new java.util.ArrayList<XmlObject>();
XmlCursor cursor = sheet.getCTWorksheet().newCursor();
cursor.selectPath(
"declare namespace x14='http://schemas.microsoft.com/office/spreadsheetml/2009/9/main' .//x14:dataValidation");
while(cursor.hasNextSelection()) {
cursor.toNextSelection();
XmlObject obj = cursor.getObject();
x14DataValidations.add(obj);
}
return x14DataValidations;
}
static void addXSSFX14DataValidations(XSSFSheet sheet, java.util.List<DataValidation> dataValidations) {
java.util.List<XmlObject> x14DataValidations = getX14DataValidations(sheet);
for (XmlObject x14DataValidation : x14DataValidations) {
XSSFX14DataValidation xssfX14DataValidation = new XSSFX14DataValidation(x14DataValidation);
dataValidations.add(xssfX14DataValidation);
}
}
static java.util.List<DataValidation> getDataValidations(Sheet sheet) {
#SuppressWarnings("unchecked")
java.util.List<DataValidation> dataValidations = (java.util.List<DataValidation>)sheet.getDataValidations();
if (sheet instanceof XSSFSheet) {
addXSSFX14DataValidations((XSSFSheet)sheet, dataValidations);
}
return dataValidations;
}
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("./Excel.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
java.util.List<DataValidation> dataValidations = getDataValidations(sheet);
for (DataValidation dataValidation : dataValidations) {
System.out.println(dataValidation);
System.out.println(dataValidation.getValidationConstraint().getFormula1());
}
workbook.close();
}
}
class XSSFX14DataValidation implements DataValidation {
private DataValidationConstraint validationConstraint;
private int errorStyle;
private boolean emptyCellAllowed;
private boolean suppressDropDownArrow;
private boolean showPromptBox;
private boolean showErrorBox;
private String promptBoxTitle;
private String promptBoxText;
private String errorBoxTitle;
private String errorBoxText;
private CellRangeAddressList regions;
public XSSFX14DataValidation(XmlObject x14DataValidation) {
String type = "";
XmlObject typeAttribute = x14DataValidation.selectAttribute(new QName("type"));
if (typeAttribute != null) type = typeAttribute.newCursor().getTextValue();
Integer validationType = DataValidationConstraint.ValidationType.ANY;
if ("CUSTOM".equalsIgnoreCase(type)) {
validationType = DataValidationConstraint.ValidationType.FORMULA;
} else if ("DATE".equalsIgnoreCase(type)) {
validationType = DataValidationConstraint.ValidationType.DATE;
} else if ("DECIMAL".equalsIgnoreCase(type)) {
validationType = DataValidationConstraint.ValidationType.DECIMAL;
} else if ("LIST".equalsIgnoreCase(type)) {
validationType = DataValidationConstraint.ValidationType.LIST;
} else if ("NONE".equalsIgnoreCase(type)) {
validationType = DataValidationConstraint.ValidationType.ANY;
} else if ("TEXT_LENGTH".equalsIgnoreCase(type)) {
validationType = DataValidationConstraint.ValidationType.TEXT_LENGTH;
} else if ("TIME".equalsIgnoreCase(type)) {
validationType = DataValidationConstraint.ValidationType.TIME;
} else if ("WHOLE".equalsIgnoreCase(type)) {
validationType = DataValidationConstraint.ValidationType.INTEGER;
}
String operator = "";
XmlObject operatorAttribute = x14DataValidation.selectAttribute(new QName("operator"));
if (operatorAttribute != null) operator = operatorAttribute.newCursor().getTextValue();
Integer operatorType = DataValidationConstraint.OperatorType.IGNORED;
if ("BETWEEN".equalsIgnoreCase(operator)) {
operatorType = DataValidationConstraint.OperatorType.BETWEEN;
} else if ("NOT_BETWEEN".equalsIgnoreCase(operator)) {
operatorType = DataValidationConstraint.OperatorType.NOT_BETWEEN;
} else if ("EQUAL".equalsIgnoreCase(operator)) {
operatorType = DataValidationConstraint.OperatorType.EQUAL;
} else if ("NOT_EQUAL".equalsIgnoreCase(operator)) {
operatorType = DataValidationConstraint.OperatorType.NOT_EQUAL;
} else if ("GREATER_THAN".equalsIgnoreCase(operator)) {
operatorType = DataValidationConstraint.OperatorType.GREATER_THAN;
} else if ("GREATER_OR_EQUAL".equalsIgnoreCase(operator)) {
operatorType = DataValidationConstraint.OperatorType.GREATER_OR_EQUAL;
} else if ("LESS_THAN".equalsIgnoreCase(operator)) {
operatorType = DataValidationConstraint.OperatorType.LESS_THAN;
} else if ("LESS_OR_EQUAL".equalsIgnoreCase(operator)) {
operatorType = DataValidationConstraint.OperatorType.LESS_OR_EQUAL;
}
String formula1 = null;
XmlObject[] xmlObjects = x14DataValidation.selectChildren(
new QName("http://schemas.microsoft.com/office/spreadsheetml/2009/9/main", "formula1"));
if (xmlObjects.length > 0) {
XmlObject formula1Element = xmlObjects[0];
formula1 = formula1Element.newCursor().getTextValue();
}
String formula2 = null;
xmlObjects = x14DataValidation.selectChildren(
new QName("http://schemas.microsoft.com/office/spreadsheetml/2009/9/main", "formula2"));
if (xmlObjects.length > 0) {
XmlObject formula2Element = xmlObjects[0];
formula2 = formula2Element.newCursor().getTextValue();
}
this.validationConstraint = new XSSFDataValidationConstraint(validationType, operatorType, formula1, formula2);
this.regions = new CellRangeAddressList();
String sqref = "";
xmlObjects = x14DataValidation.selectChildren(
new QName("http://schemas.microsoft.com/office/excel/2006/main", "sqref"));
if (xmlObjects.length > 0) {
XmlObject sqrefElement = xmlObjects[0];
sqref = sqrefElement.newCursor().getTextValue();
}
String [] refs = sqref.split(" ");
for (String ref : refs) {
CellRangeAddress address = CellRangeAddress.valueOf(ref);
this.regions.addCellRangeAddress(address);
}
String allowBlank = "";
XmlObject allowBlankAttribute = x14DataValidation.selectAttribute(new QName("allowBlank"));
if (allowBlankAttribute != null) allowBlank = allowBlankAttribute.newCursor().getTextValue();
this.emptyCellAllowed = ("1".equals(allowBlank) || "TRUE".equalsIgnoreCase(allowBlank));
String showInputMessage = "";
XmlObject showInputMessageAttribute = x14DataValidation.selectAttribute(new QName("showInputMessage"));
if (showInputMessageAttribute != null) showInputMessage = showInputMessageAttribute.newCursor().getTextValue();
this.showPromptBox = ("1".equals(showInputMessage) || "TRUE".equalsIgnoreCase(showInputMessage));
String showErrorMessage = "";
XmlObject showErrorMessageAttribute = x14DataValidation.selectAttribute(new QName("showErrorMessage"));
if (showErrorMessageAttribute != null) showErrorMessage = showErrorMessageAttribute.newCursor().getTextValue();
this.showErrorBox = ("1".equals(showErrorMessage) || "TRUE".equalsIgnoreCase(showErrorMessage));
//TODO: complete
}
public DataValidationConstraint getValidationConstraint() {
return this.validationConstraint;
}
public void setErrorStyle(int errorStyle) {
this.errorStyle = errorStyle;
}
public int getErrorStyle() {
return this.errorStyle;
}
public void setEmptyCellAllowed(boolean allowed) {
this.emptyCellAllowed = allowed;
}
public boolean getEmptyCellAllowed() {
return this.emptyCellAllowed;
}
public void setSuppressDropDownArrow(boolean suppress) {
this.suppressDropDownArrow = suppress;
}
public boolean getSuppressDropDownArrow() {
return this.suppressDropDownArrow;
}
public void setShowPromptBox(boolean show) {
this.showPromptBox = show;
}
public boolean getShowPromptBox() {
return this.showPromptBox;
}
public void setShowErrorBox(boolean show) {
this.showErrorBox = show;
}
public boolean getShowErrorBox() {
return this.showErrorBox;
}
public void createPromptBox(String title, String text) {
this.promptBoxTitle = title;
this.promptBoxText = text;
}
public String getPromptBoxTitle() {
return this.promptBoxTitle;
}
public String getPromptBoxText() {
return this.promptBoxText;
}
public void createErrorBox(String title, String text) {
this.errorBoxTitle = title;
this.errorBoxText = text;
}
public String getErrorBoxTitle() {
return this.errorBoxTitle;
}
public String getErrorBoxText() {
return this.errorBoxText;
}
public CellRangeAddressList getRegions() {
return this.regions;
}
}

How to retrieve tables which exists in a pdf using AWS Textract in java

I found article below to do in python.
https://docs.aws.amazon.com/textract/latest/dg/examples-export-table-csv.html
also I used article below to extract text.
https://docs.aws.amazon.com/textract/latest/dg/detecting-document-text.html
but above article helped to get only text, I also used function "block.getBlockType()"
of Block but none of block returned its type as "CELL" even tables are there in image/pdf.
Help me found java library similar to "boto3" to extract all tables.
What I did, I created models of each dataset in the json response and can use this models to build a table view in jsf.
public static List<TableModel> getTablesFromTextract(TextractModel textractModel) {
List<TableModel> tables = null;
try {
if (textractModel != null) {
tables = new ArrayList<>();
List<BlockModel> tableBlocks = new ArrayList<>();
Map<String, BlockModel> blockMap = new HashMap<>();
for (BlockModel block : textractModel.getBlocks()) {
if (block.getBlockType().equals("TABLE")) {
tableBlocks.add(block);
}
blockMap.put(block.getId(), block);
}
for (BlockModel blockModel : tableBlocks) {
Map<Long, Map<Long, String>> rowMap = new HashMap<>();
for (RelationshipModel relationship : blockModel.getRelationships()) {
if (relationship.getType().equals("CHILD")) {
for (String id : relationship.getIds()) {
BlockModel cell = blockMap.get(id);
if (cell.getBlockType().equals("CELL")) {
long rowIndex = cell.getRowIndex();
long columnIndex = cell.getColumnIndex();
if (!rowMap.containsKey(rowIndex)) {
rowMap.put(rowIndex, new HashMap<>());
}
Map<Long, String> columnMap = rowMap.get(rowIndex);
columnMap.put(columnIndex, getCellText(cell, blockMap));
}
}
}
}
tables.add(new TableModel(blockModel, rowMap));
}
System.out.println("row Map " + tables.toString());
}
} catch (Exception e) {
LOG.error("Could not get table from textract model", e);
}
return tables;
}
private static String getCellText(BlockModel cell, Map<String, BlockModel> blockMap) {
String text = "";
try {
if (cell != null
&& CollectionUtils.isNotEmpty(cell.getRelationships())) {
for (RelationshipModel relationship : cell.getRelationships()) {
if (relationship.getType().equals("CHILD")) {
for (String id : relationship.getIds()) {
BlockModel word = blockMap.get(id);
if (word.getBlockType().equals("WORD")) {
text += word.getText() + " ";
} else if (word.getBlockType().equals("SELECTION_ELEMENT")) {
if (word.getSelectionStatus().equals("SELECTED")) {
text += "X ";
}
}
}
}
}
}
} catch (Exception e) {
LOG.error("Could not get cell text of table", e);
}
return text;
}
TableModel to create the view from:
public class TableModel {
private BlockModel table;
private Map<Long, Map<Long, String>> rowMap;
public TableModel(BlockModel table, Map<Long, Map<Long, String>> rowMap) {
this.table = table;
this.rowMap = rowMap;
}
public BlockModel getTable() {
return table;
}
public void setTable(BlockModel table) {
this.table = table;
}
public Map<Long, Map<Long, String>> getRowMap() {
return rowMap;
}
public void setRowMap(Map<Long, Map<Long, String>> rowMap) {
this.rowMap = rowMap;
}
#Override
public String toString() {
return table.getId() + " - " + rowMap.toString();
}
I have something similar:
public class AnalyzeDocument {
public DocumentModel startProcess(byte[] content) {
Region region = Region.EU_WEST_2;
TextractClient textractClient = TextractClient.builder().region(region)
.credentialsProvider(EnvironmentVariableCredentialsProvider.create()).build();
return analyzeDoc(textractClient, content);
}
public DocumentModel analyzeDoc(TextractClient textractClient, byte[] content) {
try {
SdkBytes sourceBytes = SdkBytes.fromByteArray(content);
Util util = new Util();
Document myDoc = Document.builder().bytes(sourceBytes).build();
List<FeatureType> featureTypes = new ArrayList<FeatureType>();
featureTypes.add(FeatureType.FORMS);
featureTypes.add(FeatureType.TABLES);
AnalyzeDocumentRequest analyzeDocumentRequest = AnalyzeDocumentRequest.builder().featureTypes(featureTypes)
.document(myDoc).build();
AnalyzeDocumentResponse analyzeDocument = textractClient.analyzeDocument(analyzeDocumentRequest);
List<Block> docInfo = analyzeDocument.blocks();
// util.displayBlockInfo(docInfo);
PageModel pageModel = util.getTableResults(docInfo);
DocumentModel documentModel = new DocumentModel();
documentModel.getPages().add(pageModel);
Iterator<Block> blockIterator = docInfo.iterator();
while (blockIterator.hasNext()) {
Block block = blockIterator.next();
log.debug("The block type is " + block.blockType().toString());
}
return documentModel;
} catch (TextractException e) {
System.err.println(e.getMessage());
}
return null;
}
and this is the util file:
public PageModel getTableResults(List<Block> blocks) {
List<Block> tableBlocks = new ArrayList<>();
Map<String, Block> blockMap = new HashMap<>();
for (Block block : blocks) {
blockMap.put(block.id(), block);
if (block.blockType().equals(BlockType.TABLE)) {
tableBlocks.add(block);
log.debug("added table: " + block.text());
}
}
PageModel page = new PageModel();
if (tableBlocks.size() == 0) {
return null;
}
int i = 0;
for (Block table : tableBlocks) {
page.getTables().add(generateTable(table, blockMap, i++));
}
return page;
}
private TableModel generateTable(Block table, Map<String, Block> blockMap, int index) {
TableModel model = new TableModel();
Map<Integer, Map<Integer, String>> rows = getRowsColumnsMap(table, blockMap);
model.setTableId("Table_" + index);
for (Map.Entry<Integer, Map<Integer, String>> entry : rows.entrySet()) {
RowModel rowModel = new RowModel();
Map<Integer, String> value = entry.getValue();
for (int i = 0; i < value.size(); i++) {
rowModel.getCells().add(value.get(i));
}
model.getRows().add(rowModel);
}
return model;
}
private Map<Integer, Map<Integer, String>> getRowsColumnsMap(Block block, Map<String, Block> blockMap) {
Map<Integer, Map<Integer, String>> rows = new HashMap<>();
for (Relationship relationship : block.relationships()) {
if (relationship.type().equals(RelationshipType.CHILD)) {
for (String childId : relationship.ids()) {
Block cell = blockMap.get(childId);
if (cell != null) {
int rowIndex = cell.rowIndex();
int colIndex = cell.columnIndex();
if (rows.get(rowIndex) == null) {
Map<Integer, String> row = new HashMap<>();
rows.put(rowIndex, row);
}
rows.get(rowIndex).put(colIndex, getText(cell, blockMap));
}
}
}
}
return rows;
}
public String getText(Block block, Map<String, Block> blockMap) {
String text = "";
if (block.relationships() != null && block.relationships().size() > 0) {
for (Relationship relationship : block.relationships()) {
if (relationship.type().equals(RelationshipType.CHILD)) {
for (String childId : relationship.ids()) {
Block wordBlock = blockMap.get(childId);
if (wordBlock != null && wordBlock.blockType() != null) {
if (wordBlock.blockType().equals(BlockType.WORD))) {
text += wordBlock.text() + " ";
}
}
}
}
}
}
return text;
}

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});

How to cast to your Model object at reading from Mongo instead reading DBObject?

I wondering to know how to read saced object from MongoDB.
I just saved it with key (dataStatus) and object was converted to JSON.
When I tryng to retrieve it - I have DBObject instead of my model.
easy main():
public static void main(String[] args) {
LowFareSearchRQDao searchRQDao = new LowFareSearchRQDao();
searchRQDao.connect();
System.out.println(ToStringBuilder.reflectionToString(searchRQDao.read(DataStatus.SUCCESS_LOW_FARE_SEARCH_REQUEST), ToStringStyle.MULTI_LINE_STYLE));
searchRQDao.disconnect();
}
Output:
com.mongodb.BasicDBObject#76e134e6[
_isPartialObject=false
accessOrder=false
threshold=12
loadFactor=0.75
]
Here is my create():
#Override
public void create(MODEL model) {
try {
Field keyField1 = getKeyField(model);
String fieldValue = getKeyFieldValue(keyField1, model);
BasicDBObject query = createQuery(keyField1.getName(), fieldValue);
DBCursor cursor = dbCollection.find(query);
if (!cursor.hasNext()) {
DBObject dbObject = getDbObject(model);
dbCollection.insert(dbObject);
} else {
throw new RuntimeException(String.format("Duplicate data status %s with value %s", keyField1.getName(), fieldValue));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private Field getKeyField(MODEL model) {
Field keyField = null;
for (Field field : model.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(KeyField.class)) {
keyField = field;
}
}
if (keyField == null) {
throw new RuntimeException(String.format("Couldn't find KeyField annotation at class '%s'", model.getClass().getName()));
}
return keyField;
}
private String getKeyFieldValue(Field keyField, Object model) {
String result = null;
try {
if(keyField.isAnnotationPresent(KeyField.class)) {
keyField.setAccessible(true);
result = keyField.get(model).toString();
}
if(result == null || result.equals("")) {
throw new NullPointerException();
}
} catch(NullPointerException e) {
throw new RuntimeException("KeyField property is empty");
}catch (Exception e) {
throw new RuntimeException(String.format("Couldn't find KeyField annotation at class '%s'", model.getClass().getName()));
}
return result;
}
private BasicDBObject createQuery(String key, String value) {
BasicDBObject query = new BasicDBObject();
query.put(key, value);
return query;
}
#Override
#SuppressWarnings("unchecked")
public MODEL read(ID id) {
Field keyField2 = getKeyField(model);
BasicDBObject query = createQuery(keyField2.getName(), id.toString());
DBCursor cursor = dbCollection.find(query);
if (!cursor.hasNext()) {
throw new RuntimeException(String.format("This id %s isn't presented at collection %s", id.toString(), dbCollection.getFullName()));
}
return (MODEL) JSON.parse(String.valueOf(cursor.next()));
}
How to convert from DBObject to your model object?
How to convert from DBObject to your model object?
This is one way where you can achieve it in a simplified manner:
Make your class extend BasicDBObject, with a parameterized constructor.
class Model extends BasicDBObject
{
public Model(DBObject object) {
super(object.toMap());
}
}
Setting values in a Model.
Model model = new Model();
model.put("key","value");
Inserting a Model into the database.
dbCollection.insert(model);
Retrieving a Model from the database.
while(cursor.hasNext()){
DbObject obj = cursor.next();
Model model = new Model(obj);
//do something with the Model
}
I found solution.
For this purpose I used ObjectMapper. And I want to skip when my objet contains unknown properties as _id.
Here is code snippet:
#SuppressWarnings("unchecked")
public MODEL read(ID id) {
Field keyField2 = getKeyField(model);
BasicDBObject query = createQuery(keyField2.getName(), id.toString());
DBCursor cursor = dbCollection.find(query);
if (!cursor.hasNext()) {
throw new RuntimeException(String.format("This id %s isn't presented at collection %s", id.toString(), dbCollection.getFullName()));
}
String json = cursor.next().toString();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MODEL value = null;
try {
value = mapper.readValue(json, model);
} catch (IOException e) {
e.printStackTrace();
}
return value;
}

ParseObject as a data to the table/chart

I'm new in coding and I have a problem to understand something. I follow the example form Parse.com Doc and wrote this.
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
int object_value = Integer.parseInt(obiect);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
I understand this like:
I send query to server
get obiect with "lxFzCTeOcl" id
if there is no exception I create String object which takes string
form "value" column.
convert String to int
My question is: How can I use object_value for example to make a chart or put it into a table?
Here we will add the array list to your code and start to store an object inside the array every time we call the getData method in your class.
private ArrayList<Integer> dataArray;
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(obiect);
if(dataArray==null)
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
And here I'm just adding a simple example of how to create a simple pie chart using our array list (note that I used the lib AChartEngine http://www.achartengine.org/):
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };
private GraphicalView createPieChart(ArrayList<Integer> data){
GraphicalView chartView;
CategorySeries series = new CategorySeries("PIE");
for (int i = 0; i < VALUES.length; i++) {
series.add(i, data.get(i));
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(series.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
chartView = ChartFactory.getPieChartView(this, series, new DefaultRenderer());
chartView.repaint();
return chartView;
}
Now you can add this GraphicalView to your view.
The returned object is much like a map, with key/value pairs. In your example, the key is "value", which makes it a little confusing, but it would be like this if you wanted all fields:
for (Field field : myInstance.getClass().getDeclaredFields()) {
String name = field.getName();
value = field.get(myInstance).toString();
map.put(name, value);
}

Categories