/**
* A checking account represents a type of account against which
* people may make overdrafts covered by other savings accounts they
* hold. If they cannot cover an overdraft, then a withdrawal will fail.
*/
package bank.server;
import imaginary.persist.LockException;
import imaginary.persist.RemoteLockHolder;
import java.rmi.RemoteException;
import java.util.Vector;
public class CheckingAccount extends Account implements RemoteCheckingAccount {
/**
* Constructs a new checking account.
*/
public CheckingAccount() throws RemoteException {
super();
}
/**
* Extends the Account withdraw method. Here, it checks to
* see if the customer has enough money in the account. If they
* do not have enough money to make the withdrawal, then it checks
* the customers savings accounts in an attempt to cover. If the
* savings accounts will cover the withdrawal, then the proper
* amount is transfered to this account from those accounts
* and the withdrawal succeeds. If not enough money can be
* transfered to cover the withdrawal, it fails.
* @param trans the Transaction used for modifying the account
* @param amount the (non-zero) amount of money being withdrawn
* @exception AccountException Insufficient functions for withdrawal
* @exception imaginary.persist.LockException Another Transaction holds
* a lock on one or more of the affected accounts.
*/
public synchronized void withdraw(RemoteLockHolder h, float amount)
throws AccountException, LockException, RemoteException {
modify(h);
if( amount > getBalance() ) { // Not enough money in this account!
RemoteAccount[] accts = getCustomer().getAccounts();
Vector savings = new Vector(accts.length);
float total = 0;
// First check to see if covering is possible
// Foreach account the customer has
for(int i=0; i<accts.length; i++) {
// Ignore this account
if( accts[i] == this ) {
continue;
}
// Account must be a savings account
if( !accts[i].getAccountType().equals("S") ) {
continue;
}
// add balance to the total
total += accts[i].getBalance();
// store the account for later reference
savings.addElement(accts[i]);
// Check to see if we already have enough to cover
if( total + getBalance() > amount ) {
break;
}
}
if( total + getBalance() < amount ) { // Not enough money
throw new AccountException("Insufficient funds.");
}
// Foreach savings account, transfer the funds
for(int i=0; i<savings.size(); i++) {
SavingsAccount s = (SavingsAccount)savings.elementAt(i);
float b = s.getBalance();
// Only transfer what is needed
if( b + getBalance() > amount ) {
b = amount - getBalance();
}
// do the transfer
s.transfer(h, b, this);
// Check if we have enough
if( getBalance() >= amount ) {
break;
}
}
}
// Do the actual withdrawal
super.withdraw(h, amount);
}
}
|