Sie sind auf Seite 1von 31

Fundamentals of

Enterprise
JavaBeans
with J2EE

Solutions to
Workshops
Fundamentals of EJB with J2EE: Page i
Solutions to Workshops

Table of Contents

Workshop 2: Writing a Session Bean.............................................................................................1


Workshop 4: Deploying the Session Bean......................................................................................5
Workshop 5: Writing a Client Application........................................................................................ 7
Workshop 6: Writing a Container-Managed Entity Bean...............................................................13
Workshop 8: Deploying the Entity Bean........................................................................................ 21
Workshop 10: Using Exceptions................................................................................................... 25
Workshop 11: Using Transactions................................................................................................ 29
Workshop 13: Setting an Environment.......................................................................................... 31

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 1
Solutions to Workshops

Workshop 2:
Writing a Session Bean

Bank.java
package bank;

import account.*;

import java.rmi.RemoteException;
import javax.ejb.*;

public interface Bank extends EJBObject {

// ===========================================
// Methods for Bank attributes
// ===========================================

// Gets the bank's name.


public String getName() throws RemoteException;

// ===========================================
// Methods to get accounts
// ===========================================

// Creates account, returns new account #


public String createAccount(float openingBalance,
String description) throws RemoteException;

// Assigns a specific account as the current one


// for transactions, returns account balance.
public float setCurrentAccount(String acctNum)
throws RemoteException;

// ===========================================
// Methods to operate on current account
// ===========================================

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 2
Solutions to Workshops
// Gets the current balance of the currently selected account
public float getCurrentAcctBalance() throws RemoteException;

// Gets the current number of the currently selected account


public String getCurrentAcctNumber() throws RemoteException;

// Gets the current description of the currently selected account


public String getCurrentAcctDescription()
throws RemoteException;

// Sets the description of the currently selected account


public void setCurrentAcctDescription(String value)
throws RemoteException;

// Closes the current account


public void closeCurrentAccount() throws RemoteException;

// Credits the current account, returns new balance


public float credit(float amount) throws RemoteException;

// Debits the current account, returns new balance


public float debit(float amount) throws RemoteException;

// ===========================================
// Methods to do complex transactions
// ===========================================

// Moves money between accounts


public void transferFunds(String sourceAcctNum, String TargetAcctNum,
float amount) throws RemoteException;

} // End of Bank interface

BankHome.java
package bank;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface BankHome extends EJBHome {

// Creates a new Bank object.


public Bank create() throws CreateException, RemoteException;

} // End of BankHome interface

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 3
Solutions to Workshops

BankBean.java
package bank;

import course.account.Account;

import javax.ejb.*;

public class BankBean implements SessionBean {

//================================================
// Instance Variables
//================================================

private String _strName = ""; // For bank name


private Account _acctCurrent; // Current account

private SessionContext _ctxt; // For session context

//================================================
// Methods for remote interface
//================================================

// No changes to business methods...

//================================================
// Method for create(*) in home interface
//================================================

public void ejbCreate() {


System.out.println("Creating bank");
}

//================================================
// Methods required by SessionBean interface
//================================================

public void ejbActivate() { // Not needed


System.out.println("Activating bank");
}

public void ejbPassivate() { // Not needed


System.out.println("Passivating bank");
}

public void ejbRemove() { // Not needed


System.out.println("Removing bank");
}

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 4
Solutions to Workshops
public void setSessionContext(SessionContext ctxt) {
_ctxt = ctxt;
_strName = "Barney's Bank & Beanery";
}

} // End of BankBean class

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 5
Solutions to Workshops

Workshop 4:
Deploying the Session Bean

ejb-jar.xml (Generated)
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise


JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
<description>My bank bean</description>
<display-name>BankJar</display-name>
<enterprise-beans>
<session>
<display-name>Bank</display-name>
<ejb-name>Bank</ejb-name>
<home>bank.BankHome</home>
<remote>bank.Bank</remote>
<ejb-class>bank.BankBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Bean</transaction-type>
<security-identity>
<description></description>
<use-caller-identity></use-caller-identity>
</security-identity>
</session>
</enterprise-beans>
</ejb-jar>

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 6
Solutions to Workshops

Workshop 5:
Writing a Client Application

BankClient.java
package client;

import bank.*;
import course.client.BankClientBase;

import java.util.Hashtable;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;

public class BankClient extends BankClientBase {

//================================================
// Instance Variables
//================================================

private Bank _bank;


private BankHome _bankhome;
private String _strCurrAcctNum;

// Called after GUI is created.


public void init() {
try {
Context ctx = getInitialContext();
String strName = getBankHomeName();
Object obj = ctx.lookup(strName);

obj = PortableRemoteObject.narrow(obj, BankHome.class);


_bankhome = (BankHome) obj;
}

// Catch any exception not caught by subsidiary methods.


catch( Exception ex ) {
printException(ex, "Can't connect to bank home:");
}

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 7
Solutions to Workshops
}

//================================================
// Methods called by Bank menu
//================================================

// Connect to bank
public boolean bankConnect( String textEntry ) {
String strName = null;
try {
_bank = _bankhome.create();
strName = _bank.getName();
showBankInfo( strName );
return true;
}

catch( Exception ex ) {
printException(ex, "Can't connect to bank:");
return false;
}
}

// Disconnect from bank


public boolean bankDisconnect( ) {
try {
_bank.remove();
showBankInfo( "" );
showAccountInfo( null, 0, "" );
return true;
}
catch( Exception ex ) {
printException(ex, "Can't disconnect from bank:");
return false;
}
}

//================================================
// Methods called by Account menu
//================================================

// Create a new account


public boolean accountCreate( int type, float openingBalance,
String description ) {
String strNewAcct = null;
try {
strNewAcct = _bank.createAccount(openingBalance, description);
_strCurrAcctNum = strNewAcct;
showAccountInfo();
println( "Opened new account #" + _strCurrAcctNum +
". Balance: " + dollarFormat(_bank.getCurrentAcctBalance()));
return true;

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 8
Solutions to Workshops
}
catch( Exception ex ) {
printException( ex, "Could not create account:");
return false;
}
}

// Deposit money in current account


public boolean accountDeposit( float amount ) {
try {
float fBalance = _bank.credit( amount );
println( "Deposited " + dollarFormat(amount) +
". New balance: " + dollarFormat(fBalance));
return true;
}
catch( Exception ex ) {
printException(ex, "Couldn't complete deposit:");
return false;
}
}

// Get an existing account and make it the current one


public boolean accountGet( String number ) {
try {
float fBalance = _bank.setCurrentAccount( number );

// -1 indicates account was not found:


if(fBalance == -1) {
println( "Could not get account " + number);
return false;
}

// Success
_strCurrAcctNum = number;
showAccountInfo();
println( "Opened account #" + number +
". Balance = " + dollarFormat(fBalance)) ;
return true;
}
catch( Exception ex ) {
printException(ex, "Could not get account " + number + ":");
return false;
}
}

// Assign description to current account


public boolean accountSetDescription( String value ) {
println( "Setting description to " + value );
try {
_bank.setCurrentAcctDescription( value );
showAccountInfo();
return true;
}
catch( Exception ex ) {

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 9
Solutions to Workshops
printException(ex, "Can't set description:");
return false;
}
}

// Withdraw money from current account


public boolean accountWithdraw( float amount ) {
try {
float fBalance = bank.debit( amount );
println( "Withdrew " + dollarFormat(amount) +
". New balance: " + dollarFormat(fBalance));
return true;
}
catch( Exception ex ) {
printException(ex, "Couldn't complete withdrawal:");
return false;
}
}

// Close current account


public boolean accountClose() {
try {
_bank.closeCurrentAccount();
showAccountInfo( null, 0, "" );
return true;
}
catch( Exception ex ) {
printException(ex, "Couldn't close account:");
return false;
}
}

//================================================
// Helper Methods
//================================================

// Show information for current account.


protected void showAccountInfo() {
try {
showAccountInfo( _bank.getCurrentAcctNumber(), 0,
_bank.getCurrentAcctDescription() );
}
catch( Exception ex ) {
printException(ex, "Couldn't display account information:");
}
}

// Create, return an initial context


protected Context getInitialContext() throws NamingException {
String[] strServerInfo = getServerInfo();
String[] strPropNames = {
Context.PROVIDER_URL,
Context.SECURITY_PRINCIPAL,

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 10
Solutions to Workshops
Context.SECURITY_CREDENTIALS
};

// Create a hashtable for the environment


Hashtable ht = new Hashtable();

// For each item in array, if item is not null


// add it to the environment
for(int i = 0; i < strServerInfo.length; i++ )
if(strServerInfo[i] != null)
ht.put(strPropNames[i], strServerInfo[i]);

return new InitialContext(ht);


}

// Main method
public static void main( String[] args ) {
BankClientBase.main(args, new BankClient());
}

} // End of BankClient class

jndi.properties
java.naming.factory.initial=
com.sun.enterprise.naming.SerialInitContextFactory

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 11
Solutions to Workshops

Workshop 6:
Writing a Container-Managed
Entity Bean

Account.java
package account;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface Account extends EJBObject {

//================================================
// Instance Methods for properties
//================================================

public String getNumber() throws RemoteException;

public float getBalance() throws RemoteException;

public String getDescription() throws RemoteException;

public void setDescription(String value)


throws RemoteException;

//================================================
// Instance Methods for moving money
//================================================

public float credit(float amount) throws RemoteException;

public float debit(float amount) throws RemoteException;


}

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 12
Solutions to Workshops

AccountHome.java
package account;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface AccountHome extends EJBHome {

public Account create(float openingBalance, String description)


throws CreateException, RemoteException;

public Account findByPrimaryKey(String key)


throws FinderException, RemoteException;

AccountBean.java
package account;

import course.util.IdGenerator;

import java.rmi.*;
import javax.ejb.*;

public abstract class AccountBean implements EntityBean {

//================================================
// Instance Variables
//================================================

private EntityContext _ctxt; // For entity context


private IdGenerator _igAcctNum; // For Account #'s

//================================================
// Methods for CMP fields
//================================================

public abstract String getNumber(); // Remote method


public abstract void setNumber(String value);

public abstract float getBalance(); // Remote method


public abstract void setBalance(float value);

// Remote methods
public abstract String getDescription();
public abstract void setDescription(String value);

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 13
Solutions to Workshops

//================================================
// Methods for remote interface
//================================================

public float credit(float amount) {


float fNewBal = getBalance() + amount;
setBalance(fNewBal);
return fNewBal;
}

public float debit(float amount) {


float fNewBal = getBalance() - amount;
setBalance(fNewBal);
return fNewBal;
}

//================================================
// Methods for create(*) in home interface
//================================================

public String ejbCreate(float openingBalance,


String description) throws CreateException {

// Assign initial values


int iAcctNum = (int) _igAcctNum.getNextId();
setNumber(iAcctNum + "");
setBalance(openingBalance);
setDescription(description);

return null;
}

public void ejbPostCreate(float openingBalance,


String description) {
}

//================================================
// Methods required by EntityBean interface
//================================================

public void ejbActivate() { } // Not needed


public void ejbPassivate() { } // Not needed
public void ejbLoad() { } // Not needed
public void ejbStore() { } // Not needed
public void ejbRemove() { } // Not needed

public void setEntityContext(EntityContext ctxt) {


_ctxt = ctxt;

// Create generator for Account #'s


_igAcctNum = IdGenerator.getGenerator("AccountBean",

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 14
Solutions to Workshops
1000, 100, false);
}

public void unsetEntityContext() {


_ctxt = null;
}
}

BankBean.java
package bank;

// import course.account.Account;

import account.*;

import java.rmi.RemoteException;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;

public class BankBean implements SessionBean {

//================================================
// Instance Variables
//================================================

private String _strName = ""; // For bank name


private Account _acctCurrent; // Current account
private AccountHome _accthome;

private SessionContext _ctxt; // For session context

//================================================
// Methods for remote interface
//================================================

// Gets name of this bank


public String getName() {
return _strName;
}

// Creates a new account


public String createAccount(float openingBalance,
String description)
throws CreateException {

try {
Account acct =
_accthome.create(openingBalance, description);

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 15
Solutions to Workshops
_acctCurrent = acct;
return acct.getNumber();
}
catch(RemoteException e) {
throw new CreateException("Can't create account:\n" + e);
}
}

// Chooses an account to work with. Returns -1 if


// number is invalid.
public float setCurrentAccount(String acctNum)
throws FinderException {

Account acct = null;

try {
acct = _accthome.findByPrimaryKey(acctNum);
_acctCurrent = acct;
return getCurrentAcctBalance();
}
catch(RemoteException e) {
throw new FinderException("Can't find account " +
acctNum + ":\n" + e);
}
}

// Gets balance of current account


public float getCurrentAcctBalance() throws RemoteException {
return _acctCurrent.getBalance();
}

// Gets number of current account


public String getCurrentAcctNumber() throws RemoteException {
return _acctCurrent.getNumber();
}

// Gets description of current account


public String getCurrentAcctDescription() throws RemoteException {
return _acctCurrent.getDescription();
}

// Sets description of current account


public void setCurrentAcctDescription(String value)
throws RemoteException {
_acctCurrent.setDescription(value);
}

// Closes current account


public void closeCurrentAccount()
throws RemoteException, RemoveException {
_acctCurrent.remove();
}

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 16
Solutions to Workshops
// Credits the current account, returns new balance
public float credit(float amount) throws RemoteException {
return _acctCurrent.credit(amount);
}

// Debits the current account, returns new balance


public float debit(float amount) throws RemoteException {
return _acctCurrent.debit(amount);
}

// Moves money between two accounts


public void transferFunds(String sourceAcctNum, String targetAcctNum,
float amount) {
}

//================================================
// Method for create(*) in home interface
//================================================

public void ejbCreate() throws CreateException {


System.out.println("Creating bank");

// Get Account Home


try {
String strAcctHomeName = "MyAccount";

Context ctx = new InitialContext();


Object obj = ctx.lookup(strAcctHomeName);
obj = PortableRemoteObject.narrow(obj, AccountHome.class);
_accthome = (AccountHome) obj;
}
catch(Exception e) {
throw new CreateException("Could not create bank;\n" +
"Could not look up Account Home:\n" + e);
}
}

//================================================
// Methods required by SessionBean interface
//================================================

public void ejbActivate() { // Not needed


System.out.println("Activating bank");
}

public void ejbPassivate() { // Not needed


System.out.println("Passivating bank");
}

public void ejbRemove() { // Not needed


System.out.println("Removing bank");
}

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 17
Solutions to Workshops

public void setSessionContext(SessionContext ctxt) {


_ctxt = ctxt;
_strName = "Barney's Bank & Beanery";
}

} // End of BankBean class

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 18
Solutions to Workshops

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 19
Solutions to Workshops

Workshop 8:
Deploying the Entity Bean

ejb-jar.xml (Generated)
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise


JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar>
<description>My bank teller bean</description>
<display-name>LabBeans</display-name>
<enterprise-beans>
<session>
<description>no description</description>
<display-name>MyBank</display-name>
<ejb-name>MyBank</ejb-name>
<home>bankteller.BankTellerHome</home>
<remote>bankteller.BankTeller</remote>
<ejb-class>bankteller.BankTellerBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
<security-identity>
<description></description>
<use-caller-identity></use-caller-identity>
</security-identity>
</session>
<entity>
<display-name>MyAccount</display-name>
<ejb-name>MyAccount</ejb-name>
<home>account.AccountHome</home>
<remote>account.Account</remote>
<ejb-class>account.AccountBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Account</abstract-schema-name>
<cmp-field>

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 20
Solutions to Workshops
<description>no description</description>
<field-name>number</field-name>
</cmp-field>
<cmp-field>
<description>no description</description>
<field-name>description</field-name>
</cmp-field>
<cmp-field>
<description>no description</description>
<field-name>balance</field-name>
</cmp-field>
<primkey-field>number</primkey-field>
<security-identity>
<description></description>
<use-caller-identity></use-caller-identity>
</security-identity>
</entity>
<!-- query element removed here -->
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Remote</method-intf>
<method-name>setDescription</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Home</method-intf>
<method-name>create</method-name>
<method-params>
<method-param>float</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Home</method-intf>
<method-name>remove</method-name>
<method-params>
<method-param>java.lang.Object</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 21
Solutions to Workshops
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Remote</method-intf>
<method-name>remove</method-name>
<method-params />
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Home</method-intf>
<method-name>findByPrimaryKey</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Remote</method-intf>
<method-name>deposit</method-name>
<method-params>
<method-param>float</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Remote</method-intf>
<method-name>getDescription</method-name>
<method-params />
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Remote</method-intf>
<method-name>withdraw</method-name>
<method-params>
<method-param>float</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Home</method-intf>

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 22
Solutions to Workshops
<method-name>remove</method-name>
<method-params>
<method-param>javax.ejb.Handle</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Remote</method-intf>
<method-name>getBalance</method-name>
<method-params />
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>MyAccount</ejb-name>
<method-intf>Remote</method-intf>
<method-name>getNumber</method-name>
<method-params />
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 23
Solutions to Workshops

Workshop 10:
Using Exceptions

Account.java
public interface Account extends EJBObject {

//================================================
// Instance Methods for properties
//================================================

// No change here...

//================================================
// Instance Methods for moving money
//================================================

public float credit(float amount)


throws RemoteException, IllegalTransactionException;

public float debit(float amount)


throws RemoteException, IllegalTransactionException;
}

AccountBean.java
public abstract class AccountBean implements EntityBean {

//--------------------------------------------------------

public float credit(float amount)


throws IllegalTransactionException {

// Throw exception if amount is negative


if(amount < 0)
throw new IllegalTransactionException(getNumber(),
"Negative amount for credit not allowed");

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 24
Solutions to Workshops
float fNewBal = getBalance() + amount;
setBalance(fNewBal);
return fNewBal;
}

public float debit(float amount) throws IllegalTransactionException {

// Throw exception if amount is negative


if(amount < 0)
throw new IllegalTransactionException(getNumber(),
"Negative amount for debit not allowed");

float fNewBal = getBalance() - amount;

// Throw exception if amount exceeds balance


if(fNewBal < 0)
throw new InsufficientFundsException(getNumber(), fNewBal);

setBalance(fNewBal);
return fNewBal;
}

//--------------------------------------------------------
}

Bank.java
public interface Bank extends EJBObject {

//--------------------------------------------------------

public float credit(float amount)


throws RemoteException, IllegalTransactionException;

public float debit(float amount)


throws RemoteException, IllegalTransactionException;

//--------------------------------------------------------
}

BankBean.java
public class BankBean implements SessionBean {

//--------------------------------------------------------

// All methods that threw RemoteException were changed


// along these lines:

public float getCurrentAcctBalance() {

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 25
Solutions to Workshops
try {
return _acctCurrent.getBalance();
}
catch(RemoteException re) {
throw remoteToEjbException(re);
}
}

//--------------------------------------------------------

public float credit(float amount)


throws IllegalTransactionException {

try {
return _acctCurrent.credit(amount);
}
catch(RemoteException re) {
throw remoteToEjbException(re);
}
}

public float debit(float amount) throws IllegalTransactionException {

try {
return _acctCurrent.debit(amount);
}
catch(RemoteException re) {
throw remoteToEjbException(re);
}
}

//--------------------------------------------------------

private EJBException remoteToEjbException(RemoteException re) {

Throwable thr = re.detail;

// If RemoteException contains an exception,


// wrap it in EJBException
if(thr instanceof Exception)
return new EJBException((Exception) thr);

// If some other throwable, pass its String version


else if(thr != null)
return new EJBException(thr.toString());

// Otherwise pass the RemoteException


else
return new EJBException(re.toString());
}
}

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 26
Solutions to Workshops

Workshop 11:
Using Transactions

BankBean.java
public void transferFunds(String sourceAcctNum, String targetAcctNum,
float amount)
throws FinderException, IllegalTransactionException {

try {
Account acctSource =
_accthome.findByPrimaryKey(sourceAcctNum);
Account acctTarget =
_accthome.findByPrimaryKey(targetAcctNum);
acctTarget.credit(amount);
acctSource.debit(amount);
}
catch(RemoteException re) {
throw remoteToEjbException(re);
}
catch(FinderException fe) {
_ctxt.setRollbackOnly();
throw fe; // Re-throw exception
}
catch(IllegalTransactionException ite) {
_ctxt.setRollbackOnly();
throw ite; // Re-throw exception
}
}

Bank.java
public void transferFunds(String sourceAcctNum, String targetAcctNum,
float amount) throws RemoteException, FinderException,
IllegalTransactionException;

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 27
Solutions to Workshops

BankClient.java
public boolean accountTransfer( float amount, String target ) {
try {
_bank.transferFunds(_strCurrAcctNum, target, amount);

float fNewBalance = _bank.getCurrentAcctBalance();


println( "Moved " + dollarFormat(amount) +
" from " + _strCurrAcctNum + " to " + target + ".");
println( "New balance on current account #" + _strCurrAcctNum +
": " + dollarFormat(fNewBalance));
return true;
}
catch( Exception ex ) {
printException(ex, "Couldn't complete transfer:");
return false;
}
}

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 28
Solutions to Workshops

Workshop 13:
Setting an Environment

BankBean.java
public class BankBean implements SessionBean {

//================================================
// Instance Variables
//================================================

private Context _jndiCtxt; // For lookup


private SessionContext _ctxt; // For session context

public void ejbCreate() throws CreateException {


System.out.println("Creating bank");

String strAcctHomeName = null;

// Get environment vars


try {
Object obj = _jndiCtxt.lookup("java:comp/env");
obj = PortableRemoteObject.narrow(obj, Context.class);
Context ctxtEnv = (Context) obj;

// AccountHome name
strAcctHomeName = (String) ctxtEnv.lookup("AccountHome.name");

// Bank name
_strName = (String) ctxtEnv.lookup("Bank.name");
}
catch(Exception e) {
throw new CreateException("Could not create bank;\n" +
"Could not get environment:\n" + e);
}

// Get Account Home


try {

© 2002 SkillBuilders, Inc. V 2.1.1


Fundamentals of EJB with J2EE: Page 29
Solutions to Workshops
Object obj = _jndiCtxt.lookup(strAcctHomeName);
obj = PortableRemoteObject.narrow(obj, AccountHome.class);
_accthome = (AccountHome) obj;
}
catch(Exception e) {
throw new CreateException("Could not create bank;\n" +
"Could not look up Account Home:\n" + e);
}
}

public void setSessionContext(SessionContext ctxt) {


_ctxt = ctxt;
// _strName = "Barney's Bank & Beanery";

try {
_jndiCtxt = new InitialContext();
}
catch(NamingException ne) {
throw new EJBException(ne);
}
}

© 2002 SkillBuilders, Inc. V 2.1.1

Das könnte Ihnen auch gefallen