parse xml nested nodes that repeat with SAX - java

I have looked for days and I can't seem to wrap my head around my issue. I have been able to parse the xml doc but it has child nodes that repeat before moving back up to the parent node. My parser seems to be iterating through the child nodes correctly but I can only see the results of the last child node which is repeated multiple times.
If a parent node contains 5 child nodes, it prints the result of the last of the 5 nodes 5 times.
I need the xml tags after "portfolio" and "trade" to parse correctly. Ultimately get the xml tags before the tag to line up and print with the child nodes after "trade" without repeating the last node inside "trade"
Examples are appreciated
Thank you
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandler extends DefaultHandler {
//List to hold trade object
private List<Portfolio> tradeList = null;
private Portfolio trd = null;
//getter method for trade list
public List<Portfolio> getEmpList() {
return tradeList;
}
boolean bdate = false;
boolean bfirm = false;
boolean bacctId = false;
boolean bUserId = false;
boolean bseg = false;
boolean btradedate = false;
boolean btradetime = false;
boolean bec = false;
boolean bexch = false;
boolean bpfcode = false;
boolean bpftype = false;
boolean bpe = false;
boolean btradeqty = false;
boolean btradeprice = false;
boolean bmore = false;
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("portfolio")) {
trd = new Portfolio();
//initialize list
if (tradeList == null)
tradeList = new ArrayList<>();
} else if (qName.equalsIgnoreCase("firm")) {
bfirm = true;
} else if (qName.equalsIgnoreCase("acctId")) {
bacctId = true;
} else if (qName.equalsIgnoreCase("UserId")) {
bUserId = true;
} else if (qName.equalsIgnoreCase("seg")) {
bseg = true;
} else if (qName.equalsIgnoreCase("trade")) {
} else if (qName.equalsIgnoreCase("tradedate")) {
btradedate = true;
} else if (qName.equalsIgnoreCase("tradetime")) {
btradetime = true;
} else if (qName.equalsIgnoreCase("ec")) {
bec = true;
} else if (qName.equalsIgnoreCase("exch")) {
bexch = true;
} else if (qName.equalsIgnoreCase("pfcode")) {
bpfcode = true;
} else if (qName.equalsIgnoreCase("pftype")) {
bpftype = true;
} else if (qName.equalsIgnoreCase("pe")) {
bpe = true;
} else if (qName.equalsIgnoreCase("tradeqty")) {
btradeqty = true;
} else if (qName.equalsIgnoreCase("tradeprice")) {
btradeprice = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("trade")) {
tradeList.add(trd);
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bfirm) {
//age element, set Employee age
trd.setFirm(new String(ch, start, length));
bfirm = false;
} else if (bacctId) {
trd.setAcctId(new String(ch, start, length));
bacctId = false;
} else if (bUserId) {
trd.setUserId(new String(ch, start, length));
bUserId = false;
} else if (bseg) {
trd.setSeg(new String(ch, start, length));
bseg = false;
} else if (btradedate) {
trd.setTradedate(new String(ch, start, length));
btradedate = false;
} else if (btradetime) {
trd.setTradetime(new String(ch, start, length));
btradetime = false;
} else if (bec) {
trd.setEC(new String(ch, start, length));
bec = false;
} else if (bexch) {
trd.setExch(new String(ch, start, length));
bexch = false;
} else if (bpfcode) {
trd.setPFCode(new String(ch, start, length));
bpfcode = false;
} else if (bpftype) {
trd.setPFType(new String(ch, start, length));
bpftype = false;
} else if (bpe) {
trd.setPE(new String(ch, start, length));
bpe = false;
} else if (btradeqty) {
trd.setTradeQty(new String(ch, start, length));
btradeqty = false;
} else if (btradeprice) {
trd.setTradePrice(new String(ch, start, length));
btradeprice = false;
// bmore = false;
}
}
}
Here is an example of my xml file
<?xml version="1.0"?>
<XMLFiletoparse>
<created>201311290419</created>
<pointInTime>
<date>20131129</date>
<portfolio>
<firm>999</firm>
<acctId>1234G5689</acctId>
<UserId>11AA</UserId>
<seg>ABC</seg>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:30:00</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>0</tradeQty>
<tradePrice>1.11111</tradePrice>
</trade>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:30:00</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>10</tradeQty>
<tradePrice>2.22222</tradePrice>
</trade>
</portfolio>
<portfolio>
<firm>888</firm>
<acctId>454588784KI</acctId>
<UserId>LMNO3</UserId>
<seg>ABC</seg>
<trade>
<tradeDate>20131129</tradeDate>
<tradeTime>08:31:08</tradeTime>
<ec>ABC</ec>
<exch>ABC</exch>
<pfCode>AB</pfCode>
<pfType>XYZ</pfType>
<pe>201403</pe>
<tradeQty>6</tradeQty>
<tradePrice>3.58965</tradePrice>
</trade>
</portfolio>
</pointInTime>
</XMLFiletoparse>
Here is portfolio class
import java.io.Serializable;
public class Portfolio implements Serializable {
private String date = null;
private String firm = null;
private String acctId = null;
private String UserId = null;
private String seg = null;
private String tradedate = null;
private String tradetime = null;
private String ec = null;
private String exch = null;
private String pfcode = null;
private String pftype = null;
private String pe = null;
private String tradeqty = null;
private String tradeprice = null;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFirm() {
return firm;
}
public void setFirm(String firm) {
this.firm = firm;
}
public String getAcctId() {
return acctId;
}
public void setAcctId(String acctId) {
this.acctId = acctId;
}
public String getUserId() {
return UserId;
}
public void setUserId(String UserId) {
this.UserId = UserId;
}
public String getSeg() {
return seg;
}
public void setSeg(String seg) {
this.seg = seg;
}
public String getTradedate() {
return tradedate;
}
public void setTradedate(String tradedate) {
this.tradedate = tradedate;
}
public String getTradetime() {
return tradetime;
}
public void setTradetime(String tradetime) {
this.tradetime = tradetime;
}
public String getEC() {
return ec;
}
public void setEC(String ec) {
this.ec = ec;
}
public String getExch() {
return exch;
}
public void setExch(String exch) {
this.exch = exch;
}
public String getPFCode() {
return pfcode;
}
public void setPFCode(String pfcode) {
this.pfcode = pfcode;
}
public String getPFType() {
return pftype;
}
public void setPFType(String pftype) {
this.pftype = pftype;
}
public String getPE() {
return pe;
}
public void setPE(String pe) {
this.pe = pe;
}
public String getTradeQty() {
return tradeqty;
}
public void setTradeQty(String tradeqty) {
this.tradeqty = tradeqty;
}
public String getTradePrice() {
return tradeprice;
}
public void setTradePrice(String tradeprice) {
this.tradeprice = tradeprice;
}
#Override
public String toString() {
return "Date: " + this.date + " Firm: " + this.firm + " Acct ID: " + this.acctId + " User ID: " + this.UserId +
" Seg: " + this.seg + " tradedate: " + this.tradedate + " tradetime: " + this.tradetime +
" EC: " +this.ec+ " Exch: " +this.exch+ " PFCode: " +this.pfcode+ " PFType: " +this.pftype+
" PE: " + this.pe + " Trade Qty: " + tradeqty + " Trade Price: " + tradeprice;
}

You are seeing last child node result only, in case of multiple trade node in portfolio, because you are initializing trd after encountering portfolio tag, and it appears it can only store info about 1 trade. So, when there are 2 or more trade tags, same portfolio object gets modified. Now since Java works with call by reference at the background, the object you added in the list also gets updated as trd and object in list points to same memory area.
There could be two solutions to your problem:
1. Modify Portfolio class to store more than 1 trade data. (This should be the implementation based on your XML structure)
2. Move line trd = new Portfolio() inside else if (qName.equalsIgnoreCase("trade"))

I am posting an updated portfolio class. I had to essentially save the parent node values to a variable and pass them with the children node variables to be inserted into a database with all fields populated with the proper data. The variables for the parent node only update with a new value when the next parent node is reached. This kept the integrity of the data correct row to row.
package risk_mgnt_manager;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
public class Portfolio implements Serializable {
final private static String JDBC_CONNECTION_URL = "com.mysql.jdbc.Driver";
final private static String DB_URL = "jdbc:mysql://123.456.789.123/DB_Name";
final private static String USER = "user";
final private static String PASS = "pass";
private Connection connection;
private String firm = null;
private String acctId = null;
private String UserId = null;
private String seg = null;
private String tradedate = null;
private String tradetime = null;
private String ec = null;
private String exch = null;
private String pfcode = null;
private String pftype = null;
private String pe = null;
private String tradeqty = null;
private String tradeprice = null;
private String ffirm = null;
private String facctId = null;
private String fUserId = null;
private String fseg = null;
private String ftradedate = null;
private String ftradetime = null;
private String fec = null;
private String fexch = null;
private String fpfcode = null;
private String fpftype = null;
private String fpe = null;
private String ftradeqty = null;
private String ftradeprice = null;
private List results;
//parent nodes with if else statements check if there is new value for variable
public String getFirm() {
return firm;
}
public void setFirm(String firm) {
this.firm = firm;
if(firm == null){
ffirm = ffirm;
} else {
ffirm = firm;
}
}
public String getAcctId() {
return acctId;
}
public void setAcctId(String acctId) {
this.acctId = acctId;
if(acctId == null){
facctId = facctId;
} else {
facctId = acctId;
}
}
public String getUserId() {
return UserId;
}
public void setUserId(String UserId) {
this.UserId = UserId;
if(UserId == null){
fUserId = fUserId;
} else {
fUserId = UserId;
}
}
public String getSeg() {
return seg;
}
public void setSeg(String seg) {
this.seg = seg;
if(seg == null){
fseg = fseg;
} else {
fseg = seg;
}
}
// no if else statement from here on out. this is the child node data and
// it is always present
public String getTradedate() {
return tradedate;
}
public void setTradedate(String tradedate) {
this.tradedate = tradedate;
ftradedate = tradedate;
}
public String getTradetime() {
return tradetime;
}
public void setTradetime(String tradetime) {
this.tradetime = tradetime;
ftradetime = tradetime;
}
public String getEC() {
return ec;
}
public void setEC(String ec) {
this.ec = ec;
fec = ec;
}
public String getExch() {
return exch;
}
public void setExch(String exch) {
this.exch = exch;
fexch = exch;
}
public String getPFCode() {
return pfcode;
}
public void setPFCode(String pfcode) {
this.pfcode = pfcode;
fpfcode = pfcode;
}
public String getPFType() {
return pftype;
}
public void setPFType(String pftype) {
this.pftype = pftype;
fpftype = pftype;
}
public String getPE() {
return pe;
}
public void setPE(String pe) {
this.pe = pe;
fpe = pe;
}
public String getTradeQty() {
return tradeqty;
}
public void setTradeQty(String tradeqty) {
this.tradeqty = tradeqty;
ftradeqty = tradeqty;
}
public String getTradePrice() {
return tradeprice;
}
public void setTradePrice(String tradeprice) {
this.tradeprice = tradeprice;
ftradeprice = tradeprice;
// data from parser is sent to list
toList(ffirm,facctId,fUserId,fseg,ftradedate,tradetime,fec,fexch,
fpfcode,fpftype,fpe,ftradeqty,ftradeprice);
}
/*
This will ultimately be the setup to import the list into my database
I only printed the results to make sure I am getting the correct output
*/
public void toList(String a,String b,String c,String d,String e,String f,
String g,String h,String i,String j,String k,String l,String m){
importData(ffirm,facctId,fUserId,fseg,ftradedate,tradetime,fec,fexch,
fpfcode,fpftype,fpe,ftradeqty,ftradeprice);
}
// public void importData(final List<String> results){
public void importData(String firm,String acctid,String userid,String seg,String trdDate,String trdTime,
String ec,String exch,String pfcode,String pftype,String pe,String trdQty,String trdPrice){
connection = null;
try {
Class.forName(JDBC_CONNECTION_URL);
connection = DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
String query = "INSERT INTO t_datarlt_trades_wrk (Firm, AcctId, UserID"
+ ", seg, tradedate, tradetime, ec, exch, pfcode, pftype, pe"
+ ", tradeqty, tradeprice) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
connection.setAutoCommit(false);
PreparedStatement stmt = connection.prepareStatement(query);
// for(String result : results){
stmt.setString(1, firm);
stmt.setString(2, acctid);
stmt.setString(3, userid);
stmt.setString(4, seg);
stmt.setString(5, trdDate);
stmt.setString(6, trdTime);
stmt.setString(7, ec);
stmt.setString(8, exch);
stmt.setString(9, pfcode);
stmt.setString(10, pftype);
stmt.setString(11, pe);
stmt.setString(12, trdQty);
stmt.setString(13, trdPrice);
stmt.addBatch();
// }
stmt.executeBatch();
connection.commit();
//STEP 6: Clean-up environment
stmt.close();
connection.close();
} catch(SQLException sqle) {
System.out.println("SQLException : " + sqle);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Related

Initialize an object on the arraylist.get.set method?

I'm new at this.
I have something like this:
{
libri.get(i).setUtenteAssegnato(**Utente**); How do i create an Utente instance with user inputs?
}
Utente class:
package Biblioteca;
public class Utente
{
private String nome;
private String cognome;
public Utente (String unNome, String unCognome)
{
this.nome=unNome;
this.cognome=unCognome;
}
public String getNome()
{
return nome;
}
public String getCognome()
{
return cognome;
}
public String toString()
{
return (this.nome + this.cognome);
}
}
This is the Libro class, with setUtenteAssegnato method:
package Biblioteca;
public class Libro
{
private int codice;
private String titolo;
private Utente utenteAssegnato;
public Libro (int unCodice, String unTitolo)
{
this.codice = unCodice;
this.titolo = unTitolo;
this.utenteAssegnato = null;
}
public Utente getUtenteAssegnato()
{
return this.utenteAssegnato;
}
public void setUtenteAssegnato(Utente utenteAssegnato)
{
this.utenteAssegnato = utenteAssegnato;
}
public int getCodice()
{
return codice;
}
public String getTitolo()
{
return titolo;
}
public String toString()
{
return (this.codice + this.titolo + this.utenteAssegnato);
}
}
This is the class i'm having problem with:
package Biblioteca;
import java.util.ArrayList;
import java.util.List;
public class Biblioteca
{
List<Libro> libri = new ArrayList<Libro>();
List<Utente> utenti = new ArrayList<Utente>();
public Biblioteca ()
{
}
public void aggiungiUtente (String unNome, String unCognome)
{
Utente u1 = new Utente (unNome, unCognome);
utenti.add(u1);
}
public void aggiungiLibro(int unCodice, String unTitolo)
{
Libro l1 = new Libro (unCodice, unTitolo);
libri.add(l1);
}
public void creaPrestito (int unCodice, String unCognome)
{
boolean codiceTrovato = false;
boolean cognomeTrovato = false;
int i;
int j;
for (i=0; i<libri.size(); i++)
{
if (libri.get(i).getCodice() == (unCodice))
{
System.out.println("Codice trovato. ");
codiceTrovato = true;
}
else
{
System.out.println("Codice non trovato. ");
}
}
for (j=0; j<utenti.size(); j++)
{
if (utenti.get(j).getCognome().equals(unCognome))
{
System.out.println("Utente trovato. ");
cognomeTrovato = true;
}
else
{
System.out.println("Utente non trovato. ");
}
}
if (codiceTrovato && cognomeTrovato)
{
**libri.get(i).setUtenteAssegnato(Utente);**
}
}
public String toString()
{
String stampa = ", ";
for(Libro d : libri)
{
stampa += d.toString();
}
return stampa;
}
}
Basically, i don't know how to set the object in the arraylist (i) position from input (it should be 2 strings, right?)
Do i have to create another instance of Utente?

String not returned [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have create function to return string, that string is appending lot of other string from model class. Please see my code below
public static String getDefaultParameters(Context context){
System.out.println("Default Params");
PreDefinedAttributes preDefinedAttributes = new PreDefinedAttributes(context);
StringBuffer sb = new StringBuffer();
sb.append("&_vpw="+preDefinedAttributes.getWidth());
sb.append("&_vph="+preDefinedAttributes.getHeight());
sb.append("&sdk_version="+preDefinedAttributes.getSdk_version());
sb.append("&_src=android-sdk"
+"&_os="+preDefinedAttributes.getMobile_os());
sb.append("&os_version="+preDefinedAttributes.getMobile_version());
sb.append("&manufacturer="+preDefinedAttributes.getMobile_manufacturer());
System.out.println("Builder Params "+sb.toString());
return sb.toString();
}
But am not getting Builder Params value in the log. I have used StringBuilder and normal String with + sign as well, nothing works.
Code ForPredefined Attributes Class, where i have populate the param data and returns the values.
public class PreDefinedAttributes {
private Context mContext;
private String mobile_os,mobile_model,mobile_brand,mobile_version,mobile_manufacturer;
private String sdk_version,src,appname,appversion;
private String lat="",lng="",device_id;
private static final int REQUEST_FINE_LOCATION=0;
private int height,width;
public PreDefinedAttributes(Context context) {
mContext = context;
this.mobile_model = android.os.Build.MODEL;
this.mobile_os = "Android";
this.mobile_brand = Build.BRAND + " "+Build.PRODUCT;
this.mobile_version = Build.VERSION.RELEASE;
this.mobile_manufacturer = Build.MANUFACTURER;
this.sdk_version = Utils.SDK_VERSION;
this.src = Utils.SDK_SRC;
this.device_id = Utils.getDeviceId(mContext);
try {
this.appversion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
}catch (Exception e){
this.appversion = "";
}
final PackageManager pm = mContext.getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo( mContext.getPackageName(), 0);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
this.appname = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
height = Resources.getSystem().getDisplayMetrics().heightPixels;
width = Resources.getSystem().getDisplayMetrics().widthPixels;
//loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION,REQUEST_FINE_LOCATION);
try {
SingleShotLocationProvider.requestSingleUpdate(mContext,
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
Log.d("Location", "my location is " + location.toString());
lat = ""+location.latitude;
lng = ""+location.longitude;
}
});
}catch (SecurityException e){
e.printStackTrace();
}finally {
}
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public String getDevice_id() {
return device_id;
}
public String getMobile_brand() {
return mobile_brand;
}
public String getMobile_model() {
return mobile_model;
}
public String getMobile_os() {
return mobile_os;
}
public String getMobile_version() {
return mobile_version;
}
public String getMobile_manufacturer() {
return mobile_manufacturer;
}
public String getSdk_version() {
return sdk_version;
}
public String getSrc() {
return src;
}
public String getAppname() {
return appname;
}
public String getAppversion() {
return appversion;
}
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
Your String result = ""; is null check it Your are returning null string change it
You should
return sb.toString();
instead of
return result;
EDIT
public class PreDefinedAttributes {
private Context mContext;
private String mobile_os, mobile_model, mobile_brand, mobile_version, mobile_manufacturer;
private String sdk_version, src, appname, appversion;
private String lat = "", lng = "", device_id;
private static final int REQUEST_FINE_LOCATION = 0;
private int height, width;
public PreDefinedAttributes(Context context) {
mContext = context;
this.mobile_model = android.os.Build.MODEL;
this.mobile_os = "Android";
this.mobile_brand = Build.BRAND + " " + Build.PRODUCT;
this.mobile_version = Build.VERSION.RELEASE;
this.mobile_manufacturer = Build.MANUFACTURER;
this.sdk_version = 16 + "";
this.src = 16 + "";
this.device_id = 16 + "";
try {
this.appversion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
} catch (Exception e) {
this.appversion = "";
}
final PackageManager pm = mContext.getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(mContext.getPackageName(), 0);
} catch (final PackageManager.NameNotFoundException e) {
ai = null;
}
this.appname = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
height = Resources.getSystem().getDisplayMetrics().heightPixels;
width = Resources.getSystem().getDisplayMetrics().widthPixels;
//loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION,REQUEST_FINE_LOCATION);
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public String getDevice_id() {
return device_id;
}
public String getMobile_brand() {
return mobile_brand;
}
public String getMobile_model() {
return mobile_model;
}
public String getMobile_os() {
return mobile_os;
}
public String getMobile_version() {
return mobile_version;
}
public String getMobile_manufacturer() {
return mobile_manufacturer;
}
public String getSdk_version() {
return sdk_version;
}
public String getSrc() {
return src;
}
public String getAppname() {
return appname;
}
public String getAppversion() {
return appversion;
}
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
get values like this
PreDefinedAttributes preDefinedAttributes = new PreDefinedAttributes(this);
StringBuffer sb = new StringBuffer();
sb.append("&_vpw=" + preDefinedAttributes.getWidth());
sb.append("&_vph=" + preDefinedAttributes.getHeight());
sb.append("&sdk_version=" + preDefinedAttributes.getSdk_version());
sb.append("&_src=android-sdk"
+ "&_os=" + preDefinedAttributes.getMobile_os());
sb.append("&os_version=" + preDefinedAttributes.getMobile_version());
sb.append("&manufacturer=" + preDefinedAttributes.getMobile_manufacturer());
Log.e("Builder Params " , sb.toString());
OUtput
You have to replace your return statement like this
return sb.toString();

How can I split a line and assign index number for a graph's links connection in java?

I need help to generate a graph's link connection in json format which are index numbers. I can manage to generate the 1st part of nodes index numbers but can't do the 2nd part of links index numbers. Nodes index number should be plotted links index no. Anyone please help.
Input file:
Abdelaziz Bouteflika,Bush,1
Albert II of Belgium,Bush,1
Albert Wehrer,Bush,1
Berlusconi,Bush,1
Bernard-Montgomery,Bush,1
Bush,Fidel-Castro,1
Bernard-Montgomery,Albert Wehrer,5
Expected Output file:
{
"nodes":[
{"name":"Bush","Id":0},
{"name":"Abdelaziz Bouteflika","Id":1},
{"name":"Albert II of Belgium","Id":2},
{"name":"Albert Wehrer","Id":3},
{"name":"Berlusconi","Id":4},
{"name":"Bernard-Montgomery","Id":5},
{"name":"Fidel-Castro","Id":6}
],
"links":[
{"source":1,"target":0},
{"source":2,"target":0},
{"source":3,"target":0},
{"source":4,"target":0},
{"source":5,"target":0},
{"source":6,"target":0},
{"source":5,"target":3}
]
}
My code:
public class Link_Of_Index {
List<String> linklist1 = new ArrayList<String>();
List<String> finalList = new ArrayList<String>();
public void getIndexNo() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("E:/Workspace/Entity_Graph_Creation/WebContent/Graph_nodes_1.csv"));
FileWriter fw = new FileWriter(new File("E:/workspace/Entity_Graph_Creation/Input/links.json"));
try{
String line = null;
int index=0;
while (( line = reader.readLine()) != null)
{
String[] splits = line.split(",");
linklist1.add(splits[0]);
linklist1.add(splits[1]);
linklist1.add(splits[2]);
}
for (String s: linklist1) {
if (!finalList.contains(s)) {
finalList.add(s);
JSONObject obj = new JSONObject();
obj.put("Id", index);
obj.put("name", s);
fw.write(obj.toString()+ ","+ "\n");
index ++;
}
fw.flush();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Link_Of_Index inx = new Link_Of_Index();
inx.getIndexNo();
}
}
EDIT: I rewrote the entire answer to reflect your new requirements. For the next time, you should mention that in first place, or make 2 seperate questions of it.
public class GraphFileIO {
private static final Comparator<Node> NODE_COMPARATOR = new Comparator<Node>() {
#Override
public int compare(Node node1, Node node2) {
return node1.compareTo(node2);
}
};
private Map<Node, List<Edge>> graph;
private final File sourceFile;
public GraphFileIO(final File pSource) throws IOException {
if (pSource.exists()) {
sourceFile = pSource;
} else {
throw new IOException();
}
}
public void readGraph() throws IOException {
int index = 1;
graph = new TreeMap<>(NODE_COMPARATOR);
for (String line : Files.readAllLines(sourceFile.toPath(), Charset.defaultCharset())) {
if (line.trim().isEmpty()) {
continue; // skip blank lines
}
// csv columns:
// node 1, node 2, weight, event
String[] splits = line.split(",");
Node n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
Edge edge = new Edge(splits[3]);
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
Node node = entry.getKey();
if (node.getName().equals(splits[0])) {
edge.setSource(node.getId());
entry.getValue().add(edge);
} else if (node.getName().equals(splits[1])) {
edge.setTarget(node.getId());
// if edges are bi-directional, uncomment the next line of
// code
/* entry.getValue().add(edge); */
}
}
}
}
public void writeGraphToFile(final File targetFile) throws IOException {
JSONObject obj = new JSONObject();
JSONArray nodeList = new JSONArray();
JSONArray edgeList = new JSONArray();
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
JSONObject jsonNode = new JSONObject();
jsonNode.put("name", entry.getKey().getName());
jsonNode.put("Id", entry.getKey().getId());
jsonNode.put("event", entry.getValue());
nodeList.add(jsonNode);
for (Edge link : entry.getValue()) {
JSONObject link = new JSONObject();
link.put("source", link.getSourceID());
link.put("target", link.getTargetID());
edgeList.add(link);
}
}
obj.put("nodes", nodeList);
obj.put("links", edgeList);
FileWriter fw = new FileWriter(targetFile);
fw.write(obj.toJSONString());
fw.flush();
fw.close();
}
public static void main(final String[] args) {
File source = new File("C:\\Sandbox\\src\\foo\\test.csv");
File target = new File("C:\\Sandbox\\src\\foo\\testresult.csv");
GraphFileIO g;
try {
g = new GraphFileIO(source);
g.readGraph();
g.writeGraphToFile(target);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Node implements Comparable<Node> {
private final Integer id;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
private final String name;
private final Collection<String> events;
public Node(Integer id, String name) {
super();
this.id = id;
this.name = name;
this.events = new HashSet<>();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public Collection<String> getEvents() {
return events;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Node other = (Node) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
#Override
public int compareTo(Node o) {
return id.compareTo(o.id);
}
}
public class Edge {
private final String event;
private Integer sourceID;
private Integer targetID;
public Edge(String string) {
event = string;
}
public void setSource(Integer id) {
sourceID = id;
}
public void setTarget(Integer id) {
targetID = id;
}
#Override
public String toString() {
return event;
}
public Integer getSourceID() {
return sourceID;
}
public Integer getTargetID() {
return targetID;
}
public String getEvent() {
return event;
}
}

Inheritance + RPC GWT

It seems that I don't understand inheritance.
I have these classes : PicaAsset, VideoAsset that inherit from a class names Assets.
This is the Assets class declaration :
public class Assets {
protected int book=0;
protected int fromChapter=0;
protected int toChapter=0;
protected int fromVerse=0;
protected int toVerse=0;
protected String creator=null;
protected String discription=null;
protected String source=null;
protected String title=null;
protected String duration=null;
protected String url=null;
public Assets(int book, int fromChapter, int toChapter, int fromVerse,
int toVerse, String creator, String discription, String source,
String title, String duration, String url) {
this.book = book;
this.fromChapter = fromChapter;
this.toChapter = toChapter;
this.fromVerse = fromVerse;
this.toVerse = toVerse;
this.creator = creator;
this.discription = discription;
this.source = source;
this.title = title;
this.duration = duration;
this.url = url;
}
public Assets() {
}
public int getBook() {
return book;
}
public void setBook(int book) {
this.book = book;
}
public int getFromChapter() {
return fromChapter;
}
public void setFromChapter(int fromChapter) {
this.fromChapter = fromChapter;
}
public int getToChapter() {
return toChapter;
}
public void setToChapter(int toChapter) {
this.toChapter = toChapter;
}
public int getFromVerse() {
return fromVerse;
}
public void setFromVerse(int fromVerse) {
this.fromVerse = fromVerse;
}
public int getToVerse() {
return toVerse;
}
public void setToVerse(int toVerse) {
this.toVerse = toVerse;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
PicAsset :
public class PicAsset extends Assets implements IsSerializable {
private int picId=0;
public PicAsset(){
}
public PicAsset(int picId, int book, int fromChapter, int toChapter,
int fromVerse, int toVerse, String creator, String discription,
String source, String title, String duration, String url) {
super( book, fromChapter, toChapter,
fromVerse, toVerse, creator, discription,
source, title, duration, url);
this.picId = picId;
}
public int getIdpic() {
return picId;
}
public void setIdpic(int idpic) {
this.picId = idpic;
}
}
Now I use an RPC call to use methods declared in the server side to get info from my datbase, as you can see the method return a List of PicAsset , List.
rpcService.getPicture((books.getSelectedIndex()+1), (chapters.getSelectedIndex()+1), new AsyncCallback<List<PicAsset>>(){
public void onFailure(Throwable caught) {
Window.alert("Can't connect to database" + books.getSelectedIndex() + chapters.getSelectedIndex());
}
public void onSuccess(List<PicAsset> result) {
int listSize = result.size();
int i;
int flag = 0;
assetPicPanel.clear();
Label frameTitle = new Label("Pictures");
for(i=0;i<listSize;i++)
{
if(flag == 0)
{
assetPicPanel.add(frameTitle);
flag = 1;
}
HorizontalPanel vPanelPic = new HorizontalPanel();
System.out.print("heeeeey" +" " + result.get(i).getFromChapter());
Grid g = result.get(i).AssetGrid(result.get(i));
vPanelPic.add(g);
assetPicPanel.add(vPanelPic);
}
}
});
Now when I print the ..get().getFromChapter() on the server side it brings the right values.
But when I print the values that have been returned to the RPC call I get the default constructor values... and not what have to be sent back.
Here also the getPicture implementation on the server side :
public List<PicAsset> getPicture(int book, int chapter) throws Exception
{
System.out.print("getPicture ok " + book +"," + chapter);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet result = null;
List<PicAsset> relevantAssets = new ArrayList<PicAsset>();
PicAsset relAsset;
try {
conn = getConnection();
pstmt = conn.prepareStatement("SELECT * FROM picasset WHERE book = ? AND fromChapter <= ? AND toChapter >= ?");
//System.out.print("connection" + conn);
pstmt.setInt(1, book);
pstmt.setInt(2, chapter);
pstmt.setInt(3, chapter);
result = pstmt.executeQuery();
// System.out.print(result);
while (result.next()) {
//System.out.print("in while");
relAsset = new PicAsset(result.getInt("picId"),result.getInt("book"), result.getInt("fromChapter"), result.getInt("toChapter"),result.getInt("fromVerse"),result.getInt("toVerse"),result.getString("creator"),result.getString("discription"),result.getString("source"),result.getString("title"),result.getString("duration"),result.getString("url"));
relevantAssets.add(relAsset);
}
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
finally
{
// Cleanup
result.close();
pstmt.close();
conn.close();
}
System.out.print("In MySql get Chapter " + relevantAssets.get(0).getFromChapter() + " " + relevantAssets.get(0).getIdpic());
return relevantAssets;
}
Within GWT RPC it would be much better to use raw arrays rather than collection interfaces - return from your method PicAsset[] instead of List. This will allow you (a) solve your problem and (b) escape unnecessary classes to be compiled into client code.
See "Raw Types" section at gwtproject.org

How to read an ArrayList from a File into another ArrayList?

I trying to read an arraylist from a file into another arraylist but I keep getting errors. The file is called eventos.dat and the arraylist is from the type Evento. I want to create a new ArrayList<Evento> with the objects from the array on the file. Here is the method i'm using:
public class ListaEventos implements Serializable{
private ArrayList<Evento> eventos = new ArrayList();
public String adicionarEvento(Evento novo){
for (Evento evento : eventos) {
if(novo.equals(evento)){
return "Evento já existe";
}
}
eventos.add(novo);
return "ADICIONEI";
}
public ArrayList<Evento> getEventos() {
return eventos;
}
public Evento procuraEvento(String tituloEvento){
for (Evento evento : eventos){
if(tituloEvento.equals(evento.getTitulo())){
return evento;
}
}
return null;
}
public String editaEvento(Evento antigo, Evento novo){
for (int i=0;i<eventos.size();i++){
if(antigo.equals(eventos.get(i))){
eventos.get(i).setTitulo(novo.getTitulo());
eventos.get(i).setData(novo.getData());
eventos.get(i).setDescricao(novo.getDescricao());
eventos.get(i).setLocal(novo.getLocal());
eventos.get(i).setPrivado(novo.getPrivado());
return "Editei evento";
}
}
return "Evento não existe";
}
public String removeEvento(String removeTitulo){
Evento aux= procuraEvento(removeTitulo);
if(aux != null){
eventos.remove(aux);
return "Evento removido!";
}
return "Evento não existe";
}
public void gravaFicheiro(){
try{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Eventos.dat"));
out.writeObject(eventos);
out.close();
}
catch(IOException ex){
System.out.println("Não conseguiu gravar");
}
}
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException{
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
}
here is the Evento class:
public class Evento implements Serializable {
private String titulo = "Nao preenchido";
private String data = "Nao preenchido";
private String local = "Nao preenchido";
private String descricao = "Nao preenchido";
private String privado = "Nao preenchido";
private ArrayList<Contacto> convidados = new ArrayList();
public Evento() {
}
public Evento(String titulo, String data, String local, String descricao, String privado) {
this.titulo = titulo;
this.data = data;
this.local = local;
this.descricao = descricao;
this.privado = privado;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setData(String data) {
this.data = data;
}
public void setLocal(String local) {
this.local = local;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setPrivado(String privado) {
this.privado = privado;
}
public String getTitulo() {
return titulo;
}
public String getData() {
return data;
}
public String getLocal() {
return local;
}
public String getDescricao() {
return descricao;
}
public String getPrivado() {
return privado;
}
public ArrayList<Contacto> getConvidados() {
return convidados;
}
public void setConvidados(ArrayList<Contacto> convidados) {
this.convidados = convidados;
}
public String adicionaConvidado(String nomeConvidado){
Contacto novo = new Contacto();
for (Contacto contacto : this.convidados) {
if(nomeConvidado.equals(contacto.getNome())){
return "Contacto já foi convidado";
}
}
novo.setNome(nomeConvidado);
novo.setEmail("");
novo.setTelefone("");
convidados.add(novo);
return "ADICIONEI CONVIDADO";
}
public Evento(String titulo, String local) {
this.titulo = titulo;
this.local = local;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Evento other = (Evento) obj;
if (!Objects.equals(this.titulo, other.titulo)) {
return false;
}
if (!Objects.equals(this.data, other.data)) {
return false;
}
if (!Objects.equals(this.local, other.local)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Evento{" + "titulo=" + titulo + ", data=" + data + ", local=" + local + ", descricao=" + descricao + ", privado=" + privado + ", convidados=" + convidados + '}';
}
#Override
public int hashCode() {
int hash = 7;
return hash;
}
Changed the method CarregaEvento to:
public ArrayList<Evento> carregaEventos() throws ClassNotFoundException {
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream ("Eventos.dat"));
eventos=(ArrayList<Evento>) in.readObject();
in.close();
return eventos;
}catch(IOException ex){
System.out.println("Ficheiro não existe");
return null;
}
}
No errors but still doesn't work.
eventos=(ArrayList<Evento>) in.readObject();
This will not create a new type of an ArrayList<Evento>.
although you can create a new instance of an Evento with the String that is provided when you read the text file. you can use the split(String par1) method in the String class to create a new instance of Evento and add it to an arraylist.
refer to the JavaDocs for more info on splitting.

Categories