I would to display data from an arrayList into a TableView but I have some problem with the mechanism of ''setCellValueFactory''.
The code is this:
public class Example implements Comparable<Example>{
private List<Object> example=new ArrayList<Object>();
public void add(Object o){
example.add(o);
}
public Object get(int i){
return example.get(i);
}
public int compareTo(Example ex) {
int i=0;
for(Object o:ex.example){
if(!o.equals(this.example.get(i)))
return ((Comparable)o).compareTo(example.get(i));
i++;
}
return 0;
}
public String toString(){
String str="";
for(Object o:example)
str+=o.toString()+ " ";
return str;
}
}
public void start(Stage stage) throws SQLException, DatabaseConnectionException {
....
....
....
....
....
....
tab.setMinWidth(700);
tables.getSelectionModel().selectedItemProperty().addListener(
(ov,old_val,new_val)->{
tab.getColumns().clear();
try {
List<Example> data = new ArrayList<Example>();
TableData tableData = new TableData(new DbAccess((String)dataBases.getValue()));
data = tableData.getDistinctTransazioni(new_val);
TableSchema tableSchema = new TableSchema(new DbAccess((String)dataBases.getValue()),new_val);
for (int i=0;i<tableSchema.getNumberOfAttributes();i++) {
TableColumn column = new TableColumn(tableSchema.getColumn(i).getColumnName());
tab.getColumns().add(column);
}
ObservableList<Example> values = FXCollections.
observableArrayList(data);
tab.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
tab.setItems(values);
} catch (SQLException e1) {
e1.printStackTrace();
} catch (DatabaseConnectionException e1) {
e1.printStackTrace();
} catch (EmptySetException e1) {
e1.printStackTrace();
}
}
);
In the method : column.setCellValueFactory(new PropertyValueFactory<>("Here what I put?")).- I don't have a property but I have an arrayList of Object in class Example.
Related
I have a program that reads in a simple JSON file and manipulates the data. I then store this data in trees (albeit badly). I have a problem where arguments can longs e.g {1,2}, longs and variables e.g {1,x2}, or variables with other variables e.g. {x1,x2}.
I have been able to retrieve the variables from the JSONArray. The problem arises when I have a variable and a value. I can't for the life of me figure out how to deal with such an occurrence. I apologise for the excessive use of try-catch operations. If anyone could help me solve this issue, it would be much appreciated.
public class program {
public static void main(String[] args) throws IOException {
File file = new File();
File outputfile = new File();
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter(outputfile, true)));
JSONParser parser = new JSONParser();
try {
// creates object of parsed file
Object object = parser.parse(new FileReader(file));
// casts object to jsonObject
JSONObject jsonObject = (JSONObject) object;
// gets declaration-list JSONArray from the object created.
JSONArray jsonArray = (JSONArray) jsonObject.get("declaration-list");
// Surrounding this in a try-catch would allow me to deal with the
// different value cases unlike the frist time i wrote it
try {
/*
* iterator to cycle through the array. Made the mistake last
* time of continuously calling a method
*/
Iterator iterator = jsonArray.iterator();
while (iterator.hasNext()) {
JSONObject jo = (JSONObject) iterator.next();
String variableName = (String) jo.get("declared-variable");
MyTreeNode<String> root = new MyTreeNode<>(variableName);
try {
long value = (long) jo.get("value");
MyTreeNode<Long> child1 = new MyTreeNode(value);
System.out.println(root.getData());
root.addChild(child1);
for (MyTreeNode node : root.getChildren()) {
System.out.println(node.getData());
}
test.put(variableName, value);
// numPrint(test, variableName, pw);
} catch (Exception e) {
final JSONObject jsonValue = (JSONObject) jo.get("value");
final String operator = (String) jsonValue.get("operator");
final JSONArray arguments = (JSONArray) jsonValue.get("arguments");
ArrayList values[] = new ArrayList[arguments.size()];
if (operator.equals("set")) {
for(int i = 0; i < arguments.size(); i++){
try{
//prints nested variables
JSONObject jtest = (JSONObject) arguments.get(i);
String varval = (String) jtest.get("variable");
System.out.println(varval);
}catch(Exception g){
}
}
MyTreeNode<myObject> test1 = new MyTreeNode(new myObject(operator, arguments));
root.addChild(test1);
for (MyTreeNode node : root.getChildren()) {
System.out.print(root.getData());
System.out.print(" = ");
System.out.println(node.getData());
}
}
if (operator.equals("pair")) {
MyTreeNode<myObject> test1 = new MyTreeNode(new myObject(operator, arguments));
root.addChild(test1);
for (MyTreeNode node : root.getChildren()) {
System.out.print(root.getData() + " = ");
System.out.println(node.getData());
}
}
}
}
} catch (Exception e) {
System.out.println("oops");
}
} catch (FileNotFoundException e) {
System.out.println("Input file not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
System.out.println("File was not parsed");
e.printStackTrace();
}
pw.flush();
pw.close();
}
}
class MyTreeNode<T> {
private T data = null;
private List<MyTreeNode> children = new ArrayList<>();
private MyTreeNode parent = null;
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode child) {
child.setParent(this);
this.children.add(child);
}
public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<>(data);
newChild.setParent(this);
children.add(newChild);
}
public void addChildren(List<MyTreeNode> children) {
for (MyTreeNode t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public List<MyTreeNode> getChildren() {
return children;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
private void setParent(MyTreeNode parent) {
this.parent = parent;
}
public MyTreeNode getParent() {
return parent;
}
}
class myObject {
String operator;
JSONArray arguments;
public myObject(String operator, JSONArray arguments) {
this.operator = operator;
this.arguments = arguments;
}
public JSONArray get() {
return arguments;
}
public String toString() {
if (arguments.size() == 0) {
return "{}";
}
if (operator.equals("pair")) {
return "(" + arguments.get(0) + "," + arguments.get(1) + ")";
} else if (operator.equals("set")) {
String concat = "{" + arguments.get(0);
for (int i = 1; i < arguments.size(); i++) {
concat += "," + arguments.get(i);
}
return concat += "}";
}
return "wot";
}
}
In order to process the JSONArray, I suggest that you create a method which checks the type of the object first and then delegates the processing to other specialised methods based on its type.
This will allow you re-use the code in case you have arrays in arrays and also to navigate through the JSON tree.
Something along these lines:
private static void processArray(JSONArray jsonArray) {
jsonArray.forEach(o -> {
if (o instanceof Number) {
processNumber((Number) o);
} else if (o instanceof JSONObject) {
process((JSONObject) o);
} else if (o instanceof String) {
process((String) o);
} else if (o instanceof JSONArray) {
processArray((JSONArray) o); // recursive call here.
}
});
}
Other methods would look like:
private static void process(String o) {
System.out.println(o); // just an example
}
public static void processNumber(Number number) {
System.out.println(number); // just an example
}
And the most complex would be the one for processing objects:
private static void process(JSONObject o) {
o.forEach((s, o1) -> {
System.out.println(s);
if (o1 instanceof Number) {
processNumber((Number) o1);
} else if (o1 instanceof JSONObject) {
process((JSONObject) o1); // recursion
} else if (o1 instanceof String) {
process((String) o1);
} else if (o1 instanceof JSONArray) {
processArray((JSONArray) o1);
}
});
}
This method would also be recursive. With this type of approach you can navigate through all objects in the tree.
Update:
If you want to process JSON like:
{
"declared-variable": "x17",
"value": {
"operator": "set",
"arguments": [
1,
2,
{
"variable": "x8"
}
]
}
}
you can do so by creating a main method similar to this one:
public static void main(String[] args) throws IOException, ParseException {
JSONParser jsonParser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("array_mixed.json")) {
Object obj = jsonParser.parse(in);
if (obj instanceof JSONArray) {
processArray((JSONArray) obj);
}
else if(obj instanceof Object) {
process((JSONObject) obj);
}
}
}
This main method together with the other methods described can at least print out all the elements in the JSON.
You should be able to at least print out the following in the case of the specified JSON above:
declared-variable
x17
value
arguments
1
2
variable
x8
operator
set
I'm trying to populate a bean with some table driven attribute:value pairs. I retrieve them from a MySQL table, and populate a hashmap just fine. I iterate through the hashmap, and if I use PropertyUtils.setProperty() I get a "Class does not have setter for *" error. If I use BeanUtils.setProperty() the bean never gets populated. Here's the sample:
public class DBDrivenPayloadHandler extends GDE{
DbDrivenPayloadHandlerBean bean;
#SuppressWarnings("rawtypes")
public void populateBean() throws Exception {
ITransaction trans = new MySQLTransaction();
IAdapterDataMapDAO adapterDataMap = new MySQLAdapterDataMapDAO();
adapterDataMap.setTransaction(trans);
HashMap<String, String> values = adapterDataMap.getHashMap(super.getCurrentAccountId());
//hashmap gets populated correctly with correct variable names and values != "-1";
DbDrivenPayloadHandlerBean bean = new DbDrivenPayloadHandlerBean();
//We have a bean with all the intialized variable values
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
try {
PropertyUtils.setProperty(bean, (String) entry.getKey(), entry.getValue());
//PropertyUtils will give a setter not found error. BeanUtils never sets the values.
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void getInfo(String fileName) {
try {
populateBean();
} catch (Exception e) {
e.printStackTrace();
}
APPTS_FULLNAME_POS = bean.getAPPTS_FULLNAME_POS();
APPTS_DATETIME_POS = bean.getAPPTS_DATETIME_POS();
//Both still -1;
super.getInfo(filename);
}
And here's the Bean (or at least some of it):
public class DbDrivenPayloadHandlerBean {
int APPTS_FULLNAME_POS = -1;
int APPTS_DATETIME_POS = -1;
public DbDrivenPayloadHandlerBean() {
super();
}
public int getAPPTS_FULLNAME_POS() {
return APPTS_FULLNAME_POS;
}
public void setAPPTS_FULLNAME_POS(String APPTS_FULLNAME_POS) {
this.APPTS_FULLNAME_POS = Integer.parseInt(APPTS_FULLNAME_POS);
}
public int getAPPTS_DATETIME_POS() {
return APPTS_DATETIME_POS;
}
public void setAPPTS_DATETIME_POS(String APPTS_DATETIME_POS) {
this.APPTS_DATETIME_POS = Integer.parseInt(APPTS_DATETIME_POS);
}
Sorry guys, BeanUtils does the trick. I just don't want to be allowing setters that take Strings. I guess reflection does the casting for you. Apologies.
Solution as stated above: don't try to cast for BeanUtils.
public class DBDrivenPayloadHandler extends GDE{
DbDrivenPayloadHandlerBean bean;
#SuppressWarnings("rawtypes")
public void populateBean() throws Exception {
ITransaction trans = new MySQLTransaction();
IAdapterDataMapDAO adapterDataMap = new MySQLAdapterDataMapDAO();
adapterDataMap.setTransaction(trans);
HashMap<String, String> values = adapterDataMap.getHashMap(super.getCurrentAccountId());
this.bean = new DbDrivenPayloadHandlerBean();
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
try {
BeanUtils.setProperty(bean, (String) entry.getKey(), entry.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void getInfo(String fileName) {
try {
populateBean();
} catch (Exception e) {
e.printStackTrace();
}
APPTS_FULLNAME_POS = bean.getAPPTS_FULLNAME_POS();
APPTS_DATETIME_POS = bean.getAPPTS_DATETIME_POS();
//Both still -1;
super.getInfo(filename);
}
Bean
public class DbDrivenPayloadHandlerBean {
int APPTS_FULLNAME_POS = -1;
int APPTS_DATETIME_POS = -1;
public DbDrivenPayloadHandlerBean() {
super();
}
public int getAPPTS_FULLNAME_POS() {
return APPTS_FULLNAME_POS;
}
public void setAPPTS_FULLNAME_POS(int APPTS_FULLNAME_POS) {
this.APPTS_FULLNAME_POS = APPTS_FULLNAME_POS;
}
public int getAPPTS_DATETIME_POS() {
return APPTS_DATETIME_POS;
}
public void setAPPTS_DATETIME_POS(String APPTS_DATETIME_POS) {
this.APPTS_DATETIME_POS = APPTS_DATETIME_POS;
}
Im trying to read values from my jTable1
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int colum=jTable1.getSelectedColumn();
int row=jTable1.getSelectedRow();
System.out.println("row of selected is "+row+"col is "+colum);
final String remark1 = (String) jTable1.getValueAt(row, 8);
final String remark2 = (String) jTable1.getValueAt(row, 9);
final String invoiceno = (String) jTable1.getValueAt(row, 11);
final String id=(String) jTable1.getValueAt(row, 12);
System.out.println(id + "id");
try{
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
System.out.println("try loop for update");
SentenceExec followinsert = new PreparedSentence(s
, "UPDATE FOLLOWUP SET REMARK1= ?, REMARK2=?, INVOICENO=? WHERE ID= ?"
, SerializerWriteParams.INSTANCE);
followinsert.exec(new DataParams() { public void writeValues() throws BasicException {
System.out.println("executing command");
setString(1, remark1);
setString(2, remark2);
setString(3, invoiceno);
setString(2, id);
//System.out.println(" after update line");
}});
return null;
}
};
t.execute(); //im getting null pointer exception here :(
}
catch (BasicException ex) {
Logger.getLogger(FollowUp.class.getName()).log(Level.SEVERE, null, ex);
}
}
i get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.openbravo.data.loader.Transaction.execute(Transaction.java:42)
at com.openbravo.pos.followup.FollowUp.jcmdOKActionPerformed(FollowUp.java:679)
at com.openbravo.pos.followup.FollowUp.access$300(FollowUp.java:66)
at com.openbravo.pos.followup.FollowUp$5.actionPerformed(FollowUp.java:193)
Transaction.java is
public abstract class Transaction<T> {
private Session s;
/** Creates a new instance of Transaction */
public Transaction(Session s) {
this.s = s;
}
public final T execute() throws BasicException {
if (s.isTransaction()) {
return transact();
} else {
try {
try {
s.begin();
T result = transact();
s.commit();
return result;
} catch (BasicException e) {
s.rollback();
throw e;
}
} catch (SQLException eSQL) {
throw new BasicException("Transaction error", eSQL);
}
}
}
protected abstract T transact() throws BasicException;
}
My arraylist<"obj"> becomes null after trying to write to a file.
In WriteToFile class arraylist info becomes null after executing the last line
writer.write(info.get(i).getIpadd().toString()+"\n");
It works on the first instance when i am writing another list to file but does not when i run it the 2nd instance. I dun understand why its happening. Below is the whole code and the stack trace.
WriteToFile Class:
public class WriteToFile {
public WriteToFile(ArrayList<Information> info,String location)
{
FileWriter writer=null;
try
{
writer = new FileWriter(location);
System.out.println(info.size());
for(int i=0;i<info.size()-1;i++)
{
writer.write(info.get(i).getDate().toString()+",");
writer.write(info.get(i).getAccount().toString()+",");
writer.write(info.get(i).getStatus().toString()+",");
writer.write(info.get(i).getIpadd().toString()+"\n");
System.out.println(info.get(i).getAccount());
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
StackTrace:
java.lang.NullPointerException
at WriteToFile.<init>(WriteToFile.java:17)
at Gen_Report.<init>(Gen_Report.java:45)
at Gen_Report.main(Gen_Report.java:57)
main:
public class Gen_Report {
public Gen_Report()
{
// TODO Auto-generated constructor stub
//locate file and read all text from .log file to .csv
//file is found.so read text from it and extract all date/time, email add ,accepts and rejects,ip add, delete
Date date=new Date();
String[] dateTokens=date.toString().split(" ");
String dateString=dateTokens[2]+dateTokens[1]+dateTokens[5]+"_"+dateTokens[3].substring(0, 2)+dateTokens[3].substring(3,5)+dateTokens[3].substring(6, 8);
String logFileLocation = "/Users/gundu_87/Documents/workspace/GenFLRReport/";
ReaderFromLog rfl = new ReaderFromLog(logFileLocation+"radsecproxy.log");
//include duplicates
WriteToFile wtf = new WriteToFile(rfl.log,logFileLocation+dateString+"_FLRlogduplicates.txt");
//exclude duplicates
RemoveDuplicatesInList rdil = new RemoveDuplicatesInList(logFileLocation+dateString+"_FLRlogduplicates.txt");
for(int i=0;i<rdil.log.size();i++)
{
System.out.println(rdil.log.get(i).getAccount());
}
wtf = new WriteToFile(rdil.log,logFileLocation+dateString+"_FLRlog.txt");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Gen_Report gr= new Gen_Report();
}
}
Information class:
public class Information {
private String ipadd;
private String status;
private String account;
private String date;
public String getIpadd() {
return ipadd;
}
public void setIpadd(String ipadd) {
this.ipadd = ipadd;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
ReaderFromLog class
public class ReaderFromLog {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public ReaderFromLog(String logFileLocation) {
// TODO Auto-generated constructor stub
File logFile = new File(logFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Access-Accept for user"))
{
newUser.setStatus("Accept");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
else if(line.contains("Access-Reject for user"))
{
newUser.setStatus("Reject");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
}while(s1.hasNextLine());
}
}
RemoveDuplicate class:
public class RemoveDuplicatesInList {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public RemoveDuplicatesInList(String duplicateFileLocation)
{
// TODO Auto-generated constructor stub
File logFile = new File(duplicateFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
boolean sameAccount=false;
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Accept"))
{
newUser.setStatus("Accept");
String[] sb=line.split(",");
sameAccount=false;
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
else if(line.contains("Reject"))
{
newUser.setStatus("Reject");
String[] sb=line.split(",");
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
}while(s1.hasNextLine());
}
}
Check value of
info.get(i).getIpadd()
if value of this is null then .toString(0 will give you NullPointerException
Here's my code:
public String generateEISReports_PDF(){
surveyReportService.setSurveyReportDA(surveyReportDA);
surveyReportList = surveyReportService.getSurveyReport(surveyType, surveyDate, projectCode, employeeCode);
if(surveyReportList != null){
System.out.println(surveyReportList + "testing");
System.out.println(surveyReportList.size() + "size ito");
for (SurveyReport surveyReport : surveyReportList) {
System.out.println(surveyReport.getRiskRank().toString() + "asdf");
surveyReports.add(surveyReport);
}
}
this.compileTheJasperReports();
return SUCCESS;
}
I am getting the whole row values with this code as an object. I want to iterate the field values in every list of objects. How can I do that?
By using reflection you can achieve that. Following is the code. This might help you.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SurveyReport {
public int localServeryCont; // if you make it private then changes have to be done in 'SurveyIterator' inner class.
public String surveyReporterName;
public static void main(String[] args) {
List<SurveyReport> surveyReportList = new ArrayList<SurveyReport>();
SurveyReport sr = new SurveyReport(); //first object creation
sr.localServeryCont = 10;
sr.surveyReporterName = "AAA";
surveyReportList.add(sr);
sr = new SurveyReport(); //second object creation
sr.localServeryCont = 100;
sr.surveyReporterName = "BBB";
surveyReportList.add(sr); //two objects are in the list-object.
for (SurveyReport surveyReport : surveyReportList) {
Iterator<String> itr = surveyReport.iterator(); //You can work around with 'java.lang.Iterable' to use 'foreach' loop
while (itr.hasNext()) { //this is what you might be expecting
System.out.println("SurveyReport's object's values : " + itr.next());
}
}
}
public Iterator<String> iterator() { //here is method to get iterator object.
return new SurveyIterator();
}
private class SurveyIterator implements Iterator<String> { //creating 'SurveyIterator' INNER class
private int totalAvailableField = SurveyReport.class.getDeclaredFields().length;
int cursor = 0;
Field[] surveyReportFields = SurveyReport.class.getFields();
#Override
public boolean hasNext() {
return cursor != totalAvailableField;
}
#Override
public String next() {
String next = null;
try {
next = (surveyReportFields[cursor].get(SurveyReport.this)).toString();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
cursor++;
return next;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}