www.pudn.com > EJB3eCode.zip > AccountClient.java
package examples.bmp; import javax.ejb.*; import javax.naming.*; import java.rmi.*; import javax.rmi.*; import java.util.*; /** * Sample client code which manipulates a Bank Account Entity Bean. */ public class AccountClient { public static void main(String[] args) throws Exception { Account account = null; try { /* * Get a reference to the Account Home Object - the * factory for Account EJB Objects */ Context ctx = new InitialContext(System.getProperties()); Object obj = ctx.lookup("AccountHome"); AccountHome home = (AccountHome) javax.rmi.PortableRemoteObject.narrow(obj, AccountHome.class); System.err.println("Total of all accounts in bank initially = " + home.getTotalBankValue()); /* * Use the factory to create the Account EJB Object */ home.create("123-456-7890", "John Smith"); /* * Find an account */ Iterator i = home.findByOwnerName("John Smith").iterator(); if (i.hasNext()) { account = (Account) javax.rmi.PortableRemoteObject.narrow(i.next(), Account.class); } else { throw new Exception("Could not find account"); } /* * Call the balance() method, and print it */ System.out.println("Initial Balance = " + account.getBalance()); /* * Deposit $100 into the account */ account.deposit(100); /* * Retrieve the resulting balance. */ System.out.println("After depositing 100, account balance = " + account.getBalance()); System.out.println("Total of all accounts in bank now = " + home.getTotalBankValue()); /* * Retrieve the Primary Key from the EJB Object */ AccountPK pk = (AccountPK) account.getPrimaryKey(); /* * Release our old EJB Object reference. Now call * find() again, this time querying on Account ID * (i.e. the Primary Key). */ account = null; account = home.findByPrimaryKey(pk); /* * Print out current balance */ System.out.println("Found account with ID " + pk + ". Balance = " + account.getBalance()); /* * Try to withdraw $150 */ System.out.println("Now trying to withdraw $150, which is more than is currently available. This should generate an exception.."); account.withdraw(150); } catch (Exception e) { System.out.println("Caught the exception!"); System.out.println("Message: " + e.getMessage()); } finally { /* * Destroy the Entity permanently */ try { System.out.println("Destroying account.."); if (account != null) { account.remove(); } } catch (Exception e) { e.printStackTrace(); } } } }