There's a fair bit of code involved and I'm not sure how much detail to go into, but I'm populating a treemap with data from a mysql table and I'm having trouble iterating through it.
Here's the code for the class containing the treemap
public class SeasonResults{
private static Map<String,SeasonResults> allResults = new TreeMap<String,SeasonResults>();
private String hometeam;
private String awayteam;
private String result;
private static SeasonResults result6;
public static SeasonResults add(String hometeam, String awayteam, String result)
{
result6 = new SeasonResults(hometeam, awayteam, result);
allResults.put(hometeam,result6);
return result6;
}
private SeasonResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;
}
public static Collection<SeasonResults> getCollection()
{
return allResults.values();
}
#Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}
And here's the code where I populate the array and then try and iterate through it.
public void HeadToHead(){
try
{
//Sets up the connedtion to the database and installs drivers which are required.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");
String SQL = "SELECT * FROM PreviousSeasons WHERE HomeTeam=? and AwayTeam=?";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
prepst.setString(2,box2.getSelectedItem().toString());
rs = prepst.executeQuery();
while (rs.next())
{
//This retrieves each row of League table and adds it to an array in the League Results class.
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
custs = (hometeam + "," + awayteam + "," + result); // Takes all the variables containging a single customers information and puts it into a string, seperated by commas.
SeasonResults.add(hometeam, awayteam, result);
}
}
catch (Exception e)
{
System.out.println("Error " +e);
}
Seasonrecord = SeasonResults.getCollection();
seasons = new SeasonResults[Seasonrecord.size()];
Iterator iterateSeason = Seasonrecord.iterator();
int i = 0;
while(iterateSeason.hasNext()){
seasons[i] = (SeasonResults)iterateSeason.next();
i++;
if(result.equals("HW")){
hometeamvalue = hometeamvalue + 50;
}
else if(result.equals("D")){
hometeamvalue = hometeamvalue + 10;
awayteamvalue = awayteamvalue + 10;
}
else{
if(result.equals("AW")){
awayteamvalue = awayteamvalue + 50;
}
}
}
}
There are 5 'result' fields in the database. 2 are 'HW', 2 are 'AW', and 1 is 'D'. What I'm trying to do is print out 'hometeamvalue' and 'awayteamvalue' but when I do the value is printed as only 10. Only the first field's value is used.
I use the same code to iterate through the array when I want to display the results in a GUI, and all the fields are shown. But when I try and do some calculations with them, it doesn't work.
Any ideas what the problem is?
You have to do like this
SeasonResults.java
public class SeasonResults{
private String hometeam;
private String awayteam;
private String result;
public String getHometeam() {
return hometeam;
}
public void setHometeam(String hometeam) {
this.hometeam = hometeam;
}
public String getAwayteam() {
return awayteam;
}
public void setAwayteam(String awayteam) {
this.awayteam = awayteam;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public SeasonResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;
}
#Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}
HeadToHaed method
public void HeadToHead(){
String hometeam,awayteam,result;
int hometeamvalue,awayteamvalue;
List<SeasonResults> allResults = new ArrayList<SeasonResults>();
try
{
//Sets up the connedtion to the database and installs drivers which are required.
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");
String SQL = "SELECT * FROM PreviousSeasons WHERE HomeTeam=? and AwayTeam=?";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
prepst.setString(2,box2.getSelectedItem().toString());
ResultSet rs = prepst.executeQuery();
SeasonResults seasonResults=null;
while (rs.next())
{
//This retrieves each row of League table and adds it to an array in the League Results class.
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
seasonResults=new SeasonResults( hometeam, awayteam, result) ;
custs = (hometeam + "," + awayteam + "," + result); // Takes all the variables containging a single customers information and puts it into a string, seperated by commas.
allResults.add(seasonResults);
}
}
catch (Exception e)
{
System.out.println("Error " +e);
}
System.out.println("SIze of ArrayList::"+allResults.size());
for(SeasonResults temp:allResults)
{
if(temp.getResult().equals("HW")){
hometeamvalue = hometeamvalue + 50;
}
else if(temp.getResult().equals("D")){
hometeamvalue = hometeamvalue + 10;
awayteamvalue = awayteamvalue + 10;
}
else{
if(temp.getResult().equals("AW")){
awayteamvalue = awayteamvalue + 50;
}
}
}
}
Let Me Know If U Face Any Issues
Related
I'm trying to write a small java application that returns the details for an employee. Here's my Employee class.
public class Employees {
private int id;
private Date dateofBirth;
private String firstName;
private String lastName;
private enum gender{
M, F;
}
private gender employeeGender;
private Date dateHired;
public String getEmployeeGender() {
return this.employeeGender.name();
}
public void setEmployeeGender(String employeeGender) {
this.employeeGender = gender.valueOf(employeeGender);
}
/*Getters, setters omitted*/
Here's my DAO class
public class EmployeeDao {
final String TABLE_EMPLOYEES = "employees";
final String COLUMN_EMPLOYEES_ID = "emp_no";
final String COLUMN_EMPLOYEES_DOB = "birth_date";
final String COLUMN_EMPLOYEES_FIRST_NAME = "first_name";
final String COLUMN_EMPLOYEES_LAST_NAME = "last_name";
final String COLUMN_EMPLOYEES_GENDER = "gender";
final String COLUMN_EMPLOYEES_HIRE_DATE = "hire_date";
final String QUERY_EMPLOYEES = "SELECT * FROM " + TABLE_EMPLOYEES + " WHERE " + COLUMN_EMPLOYEES_ID + " = ?";
public Employees getEmployeeDetails(int employeeId) {
Employees employee = new Employees();
try (DbConnection dbConnection = new DbConnection();
Connection databaseConnection = dbConnection.getConn();
PreparedStatement selectFromEmployees = databaseConnection.prepareStatement(QUERY_EMPLOYEES)) {
selectFromEmployees.setInt(1, employeeId);
try (ResultSet result = selectFromEmployees.executeQuery()) {
if (result.next() == false) {
System.out.println("Empty Resultset");
}
while (result.next()) {
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return employee;
}
}
But when I try to run the app in main method like this, I get an output with null values.
public static void main(String[] args) {
EmployeeDao employeeDao = new EmployeeDao();
Employees employees = employeeDao.getEmployeeDetails(39256);
System.out.println(employees.getId() + " \n" + employees.getFirstName() + " \n" + employees.getLastName() + " \n" + employees.getDateofBirth() + " \n" + employees.getDateHired());
}
This is the output.
This is how the corresponding row looks like in the database
You should not call next twice, since it will move the cursor forward again. Try this:
if (result.next() == false) {
System.out.println("Empty Resultset");
} else {
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
Calling ResultSet#next moves the cursor forward a row, so your if condition loses the first row. Since you know your query can return at most one row, you don't need the while loop at all, however:
public Employees getEmployeeDetails(int employeeId) throws SQLException {
Employees employee = null;
try (DbConnection dbConnection = new DbConnection();
Connection databaseConnection = dbConnection.getConn();
PreparedStatement selectFromEmployees =
databaseConnection.prepareStatement(QUERY_EMPLOYEES)) {
selectFromEmployees.setInt(1, employeeId);
try (ResultSet result = selectFromEmployees.executeQuery()) {
if (result.next()) {
employee = new Employees();
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
}
}
return employee;
}
No need to add extra result.next() comparison.
if (result.next() == false) {
System.out.println("Empty Resultset");
}
while (result.next()){
}
while will execute only if there are any rows.
Check the size of list generated before using to check if it contains value or not.
i am trying to get a string out of a random number and it is returning this
Nome1: com.example.OtherActivity#3c9413b0 x com.example.OtherActivity#132c3229 :Nome2
Nome1 and Nome2 are converting good but the rest is not
My OtherActivity class is this
public class OtherActivity{
private String teamOne;
public Team(String teamOne) {
this.teamOne = teamOne;
}
public String getTeamOne() {
return teamOne;
}
public void setTeamOne(String teamOne) {
this.teamOne = teamOne;
}
}
My TeamMixer class
public class TeamMixer extends PlayerNames {
public ArrayList<Team> times = null;
public TeamMixer(ArrayList<Team> times) {
this.times = times;
}
protected String tellJoke(){
Double randomNumber = new Double(Math.random() * times.size());
Double randomNumber1 = new Double(Math.random() * times.size());
int randomNum1 = randomNumber1.intValue();
int randomNum = randomNumber.intValue();
Team time2 = times.get(randomNum);
Team time3 = times.get(randomNum1);
String timeString = String.valueOf(time3);
String timeString2 = time2.toString();
if(time2 == time3){
Double randomNumber2 = new Double(Math.random() * times.size());
int randomNum2 = randomNumber2.intValue();
Team time4 = times.get(randomNum2);
String timeString3 = String.valueOf(time4);
String tentativa = sayTeam(timeString2, timeString3);
return tentativa;
} else{
String tentativa2 = sayTeam(timeString, timeString2);
return tentativa2;
}
}
protected String sayTeam(String teams, String teams2){
String message = (getNamePlayerOne()+": " + teams + " x " + teams2 + " :" + getNamePlayerTwo());
return message;
}
}
Appreciate the help!
Override your Team class toString method, so it returns the string not the Team object:
private class Team {
String str;
public Team(String str) {
this.str = str;
}
#Override
public String toString() {
return str;
}
}
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
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();
}
}
}
I'm making a Timetable scheduler as a final year project. For the last two days, I'm getting an OutOfMemoryException. I have read a lot about the exception, and tried to increase the memory alloted through the -Xms and -Xmx options. None of these seem to work for me.
I profiled the project, and found that the maximum space was consumed by hashmap objects, and also by the MySQL connection. I have used a static connection as follows
public final class Connector
{
private static Connector connector;
Connection con;
String driverName;
String dbname;
String username;
String password;
String connString;
private Connector(){
driverName = "com.mysql.jdbc.Driver";
dbname = "timegen";
username = "root";
password = "root";
connString = "jdbc:mysql://localhost:3306/" + dbname;
openConnection();
}
public void openConnection(){
try{
Class.forName(driverName);
con = DriverManager.getConnection(connString, username, password);
} catch(Exception e){
System.out.println(e);
}
}
public void terminateConnection(){
try{
con.close();
} catch(Exception e){
System.out.println(e);
}
}
public static Connector createConnection() {
if (connector == null){
connector = new Connector();
}
return connector;
}
public Connection getCon() {
return con;
}
public String getConnString() {
return connString;
}
public void setConnString(String connString) {
this.connString = connString;
}
}
This is the code for a class named MasterData, which is extended by all other classes that access the database
public class MasterData{
static Connector con;
static Statement st;
MasterData(){
try {
con = Connector.createConnection();
st = con.getCon().createStatement();
} catch (SQLException ex) {
Logger.getLogger(MasterData.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Statement createStatement() throws SQLException{
Statement st = con.getCon().createStatement();
return st;
}
public void closeConnection(){
con.terminateConnection();
}
}
An example of a class that uses this
public class Teacher extends MasterData{
int teacherid;
String teachername;
String subject;
String post;
#Override
public String toString() {
return "Teacher{" + "teacherid=" + teacherid + ", teachername=" + teachername + ",
post=" + post + ", subject=" + subject + '}';
}
public Teacher(int teacherid, String teachername,String subject, String post) {
this.teacherid = teacherid;
this.teachername = teachername;
this.subject = subject;
this.post = post;
}
public Teacher(String teachername) {
this.teachername = teachername;
}
public Teacher(){}
public String display(){
String s ="\nTeacher name = " + teachername
+ "\nSubject = " + subject
+ "\nPost = "+post;
return s;
}
public ArrayList<String> getSubjectTeachers(String s){
ArrayList<String> teachers = new ArrayList<String>();
try{
ResultSet rs = st.executeQuery("select teachername from teacher where
subject='"+s+"';");
while(rs.next()){
teachers.add(rs.getString(1));
}
}catch(Exception e){e.printStackTrace();}
return teachers;
}
public List<Teacher> getFree()
{
List<Teacher> lst = new ArrayList<Teacher>();
try{
ResultSet rs = st.executeQuery("select * from teacher where teacherid not
in(select classteacher from division where classteacher!=null)");
while(rs.next())
{
lst.add(new
Teacher(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4)));
}
}catch(Exception e ){e.printStackTrace();}
return lst;
}
public int getTeacherid() {
return teacherid;
}
public void setTeacherid(int teacherid) {
this.teacherid = teacherid;
}
public String getTeachername() {
return teachername;
}
public void setTeachername(String teachername) {
this.teachername = teachername;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public boolean checkDuplicate(){
try{
ResultSet rs = st.executeQuery("select * from teacher where
teachername='"+teachername+"';");
if(rs.next())
return true;
}catch(Exception e){e.printStackTrace();}
return false;
}
public boolean insert(){
int t;
try{
t = st.executeUpdate("insert into teacher(teachername,subject,post)
values('"+teachername+"','"+subject+"','"+post+"');");
if(t!=0) return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
return false;
}
public boolean delete(){
int t;
try{
new AssignedTeacher().deleteTeacher(teacherid);
t = st.executeUpdate("delete from teacher where teacherid="+teacherid+";");
if(t!=0) return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
return false;
}
public boolean update(){
int t;
try{
t = st.executeUpdate("update teacher set teachername = '"+teachername+"',
subject='"+subject+"', post='"+post+"' where teacherid="+teacherid+";");
if(t!=0) return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
return false;
}
}
My intention was to create a single static connection for the entire program. It seems to work well. But is this the possible cause of the problem?
Try to set these parameters as well:
-XX:PermSize
-XX:MaxPermSize
It looks like you are creating too many Connections.
You may verify whether or not your connection is valid in your openConnection method You also may use some Connection Pool.
EDIT:
It seems to me that you've tried to implement Active record pattern because there are insert, delete, update and getSubjectTeachers methods. Anyway, its is not always a good idea to extend Teacher from MasterData. As a side effect, new connections will be created for each instance of MasterData. static Connection con would be reassigned to new object but previous Connection will not be ever closed. Same holds with MasterData#createStatement.
Also, as greedybuddha pointed out, make sure that your HashMap are not reassigned in the same manner.