public void endTag(String tagName) {
if (tagName.equalsIgnoreCase("STMTTRN")) {
System.out.println(name + " " + amount + " " + dateFormat.format(datePosted.getTime()));
Transaction trans = null;
DAOFactory factory = new DAOFactory();
try {
factory.beginTransaction();
// Look for fitID
if (this.fitID != null) {
RegisterDAO registerDAO = (RegisterDAO)factory.getDAO("register");
trans = registerDAO.loadTransactionByFitID(this.fitID);
System.out.println("Transaction found!");
}
if (trans == null) {
trans = new Transaction();
Payee payee = PayeeUtils.findPayee(this.name, true);
trans.setPayee(payee);
trans.setDatePosted(datePosted);
trans.setFitID(fitID);
Transaction payeeTrans = PayeeUtils.findLastTransactionForPayee(payee, this.accountID);
if (payeeTrans != null) {
List transSplitList = payeeTrans.getTransSplitList();
TransSplit transSplit = null;
TransSplit newSplit = null;
double oldTotal = 0;
for (int i=0; i<transSplitList.size(); i++) {
transSplit = (TransSplit)transSplitList.get(i);
if (transSplit.getAmount().doubleValue() >= 0)
oldTotal += transSplit.getAmount().doubleValue();
}
for (int i=0; i<transSplitList.size(); i++) {
transSplit = (TransSplit)transSplitList.get(i);
newSplit = new TransSplit();
newSplit.setParentTransaction(trans);
newSplit.setAccount(transSplit.getAccount());
double splitAmount = Math.abs((transSplit.getAmount().doubleValue()/oldTotal)*amount);
if (newSplit.getAccountAccountID().equals(accountID)) {
if (amount >= 0) {
newSplit.setAmount(new Double(splitAmount));
}
else {
newSplit.setAmount(new Double(-splitAmount));
}
}
else {
if (amount >= 0) {
newSplit.setAmount(new Double(-splitAmount));
}
else {
newSplit.setAmount(new Double(splitAmount));
}
}
trans.appendTransSplit(newSplit);
}
}
else {
AccountDAO accountDAO = (AccountDAO)factory.getDAO("account");
Account newAccount = (Account)accountDAO.load("WHERE TITLE = 'Imbalance-USD'", null, true).get(0);
TransSplit transSplit = new TransSplit();
transSplit.setParentTransaction(trans);
Account account = new Account();
account.setAccountID(accountID);
transSplit.setAccount(account);
transSplit.setAmount(new Double(amount));
trans.appendTransSplit(transSplit);
TransSplit newSplit = new TransSplit();
newSplit.setParentTransaction(trans);
newSplit.setAccount(newAccount);
newSplit.setAmount(new Double(-amount));
trans.appendTransSplit(newSplit);
}
}
TransactionDAO transDAO = (TransactionDAO)factory.getDAO("transaction");
transDAO.store(trans, true);
factory.commit();
factory.close();
}
catch (Exception ex) {
System.out.println("Error with transaction: Payee" + trans.getPayee().getName() + "\n" +
"Fit ID: " + trans.getFitID());
throw new RuntimeException(ex);