1 package org.prevayler.demos.demo2.business; 2 3 import java.util.*; 4 5 public class Bank implements java.io.Serializable { 6 7 private long nextAccountNumber = 1; 8 private Map accountsByNumber = new HashMap(); 9 private transient BankListener bankListener; 10 11 public Account createAccount(String holder) throws Account.InvalidHolder { 12 Account account = new Account(nextAccountNumber, holder); 13 accountsByNumber.put(new Long (nextAccountNumber++), account); 14 15 if (bankListener != null) bankListener.accountCreated(account); 16 return account; 17 } 18 19 public void deleteAccount(long number) throws AccountNotFound { 20 Account account = findAccount(number); 21 accountsByNumber.remove(new Long (number)); 22 if (bankListener != null) bankListener.accountDeleted(account); 23 } 24 25 public List accounts() { 26 List accounts = new ArrayList(accountsByNumber.values()); 27 28 Collections.sort(accounts, new Comparator() { 29 public int compare(Object acc1, Object acc2) { 30 return ((Account)acc1).number() < ((Account)acc2).number() ? -1 : 1; 31 } 32 }); 33 34 return accounts; 35 } 36 37 public void setBankListener(BankListener bankListener) { 38 this.bankListener = bankListener; 39 } 40 41 public Account findAccount(long number) throws AccountNotFound { 42 Account account = searchAccount(number); 43 if (account == null) throw new AccountNotFound(number); 44 return account; 45 } 46 47 public void transfer(long sourceNumber, long destinationNumber, long amount, Date timestamp) throws AccountNotFound, Account.InvalidAmount { 48 Account source = findAccount(sourceNumber); 49 Account destination = findAccount(destinationNumber); 50 51 source.withdraw(amount, timestamp); 52 if (amount == 666) throw new RuntimeException ("Runtime Exception simulated for rollback demonstration purposes."); 53 destination.deposit(amount, timestamp); 54 } 55 56 private Account searchAccount(long number) { 57 return (Account)accountsByNumber.get(new Long (number)); 58 } 59 60 public class AccountNotFound extends Exception { 61 AccountNotFound(long number) { 62 super("Account not found: " + Account.numberString(number) + ".\nMight have been deleted."); 63 } 64 } 65 66 } | Popular Tags |