Download presentation
Presentation is loading. Please wait.
Published byTyler Carson Modified over 6 years ago
1
Chapter 14: Session EJBs and Distributed Transactions
Outline Introduction EJB Overview Remote Interface Home Interface EJB Implementation EJB Container Session Beans Stateful Session EJBs Deploying Session EJBs Stateless Session EJBs EJB Transactions MoneyTransfer EJB Home and Remote Interfaces Bean-Managed Transaction Demarcation Container-Managed Transaction Demarcation MoneyTransfer EJB Client Deploying the MoneyTransfer EJB Internet and World Wide Web Resources
2
Enterprise JavaBeans (EJBs) Session EJBs Distributed Transactions
Introduction Enterprise JavaBeans (EJBs) Component model for enterprise application business logic Session EJBs Stateful and Stateless Distributed Transactions Ensure data integrity across databases and across application servers
3
14.2 EJB Overview Remote Interface Home Interface Implementation
Declares publicly available methods of EJB Home Interface Declares create methods for creating new EJB instances Declares remove methods for removing EJB instances Declares finder methods for locating EJB instances Implementation Provides implementations for EJB business methods declared in remote interface Provides implementations for create, remove and finder methods declared in home interface EJB Container Runtime environment for managing EJB lifecycle
4
Six roles for enterprise-system implementors
14.2 EJB Overview (cont.) Six roles for enterprise-system implementors Enterprise Bean Provider Implements business logic as EJBs Application Assembler Constructs application components from EJBs Deployer Deploys application components to a J2EE application server EJB Server Provider Implements a J2EE-compliant application server EJB Container Provider Implements the application server’s runtime environment for EJBs
5
Remote Interface Declares business methods that EJB clients can invoke to perform business-logic tasks Must extend interface javax.ejb.EJBObject Throw clause for each method must include RemoteException Throw clause for each method may include application-specific exceptions (e.g., IllegalArgumentException)
6
14.2.1 Remote Interface (cont.)
7
Home Interface Declares methods for creating, removing and finding EJB instances Must extend javax.ejb.EJBHome Finder methods enable clients to locate particular EJB instances
8
Home Interface (cont.)
9
EJB Implementation Defines business methods declared in the remote interface Defines create, remove and finder methods declared in the home interface Session EJBs must implement interface javax.ejb.SessionBean
10
Manages EJB interactions
EJB Container Manages EJB interactions Client interactions Method invocations Transactions Security Manages EJB lifecycle Pools EJB instances to enhance performance Creates new EJB instances Removes existing EJB instances
11
Perform business logic processing for a particular client
Session Beans Perform business logic processing for a particular client Not persistent Do not represent database-stored data Instances are lost if EJB container crashes Two types Stateful Stateless
12
Maintain state information between business method invocations
Stateful Session EJBs Maintain state information between business method invocations Shopping Cart Stateful Session EJB Would provide business methods for adding and removing items from the cart EJB would store state information Number of items in the cart Quantity of each item in the cart Total cost of items in the cart
13
Remote interface must extend interface EJBObject
1 // InterestCalculator.java 2 // InterestCalculator is the remote interface for the 3 // InterestCalculator EJB. 4 package com.deitel.advjhtp1.ejb.session.stateful.ejb; 5 6 // Java core libraries 7 import java.rmi.RemoteException; 8 9 // Java standard extensions 10 import javax.ejb.EJBObject; 11 12 public interface InterestCalculator extends EJBObject { 13 // set principal amount public void setPrincipal( double amount ) throws RemoteException; 17 // set interest rate public void setInterestRate( double rate ) throws RemoteException; 21 // set loan length in years public void setTerm( int years ) throws RemoteException; 25 // get loan balance public double getBalance() throws RemoteException; 28 // get amount of interest earned public double getInterestEarned() throws RemoteException; 31 } Fig InterestCalculator remote interface for calculating simple interest. Line 12 Lines 16, 20, 27 and 30 Remote interface must extend interface EJBObject throws clause for each business method must include RemoteException
14
Home interface must extend interface EJBHome
1 // InterestCalculatorHome.java 2 // InterestCalculatorHome is the home interface for the 3 // InterestCalculator EJB. 4 package com.deitel.advjhtp1.ejb.session.stateful.ejb; 5 6 // Java core libraries 7 import java.rmi.RemoteException; 8 9 // Java standard extensions 10 import javax.ejb.*; 11 12 public interface InterestCalculatorHome extends EJBHome { 13 // create InterestCalculator EJB public InterestCalculator create() throws RemoteException, CreateException; 17 } Fig InterestCalculatorHome interface for creating InterestCalculator EJBs. Line 12 Lines 15-16 Home interface must extend interface EJBHome create methods must return the remote interface type (e.g., InterestCalculator) create method enables clients to create InterestCalculator instances
15
Session EJB implementations must implement interface SessionBean
1 // InterestCalculatorEJB.java 2 // InterestCalculator is a stateful session EJB for calculating 3 // simple interest. 4 package com.deitel.advjhtp1.ejb.session.stateful.ejb; 5 6 // Java core libraries 7 import java.util.*; 8 9 // Java standard extensions 10 import javax.ejb.*; 11 12 public class InterestCalculatorEJB implements SessionBean { 13 private SessionContext sessionContext; 15 // state variables private double principal; private double interestRate; private int term; 20 // set principal amount public void setPrincipal( double amount ) { principal = amount; } 26 // set interest rate public void setInterestRate( double rate ) { interestRate = rate; } 32 Fig InterestCalculatorEJB implementation of InterestCalculator remote interface. Line 12 Line 14 Lines 17-19 Session EJB implementations must implement interface SessionBean SessionContext provides access to the EJB container Member variables maintain state information
16
EJB container invokes setSessionContext after creating the EJB
// set loan length in years public void setTerm( int years ) { term = years; } 38 // get loan balance public double getBalance() { // calculate simple interest return principal * Math.pow( interestRate, term ); } 45 // get amount of interest earned public double getInterestEarned() { return getBalance() - principal; } 51 // set SessionContext public void setSessionContext( SessionContext context ) { sessionContext = context; } 57 // create InterestCalculator instance public void ejbCreate() {} 60 // remove InterestCalculator instance public void ejbRemove() {} 63 // passivate InterestCalculator instance public void ejbPassivate() {} 66 Fig InterestCalculatorEJB implementation of InterestCalculator remote interface. Lines Line 59 Line 62 Line 65 EJB container invokes setSessionContext after creating the EJB EJB container invokes ejbCreate when a client invokes home interface method create to create a new EJB instance EJB container invokes ejbRemove when a client invokes home interface method remove to destroy an EJB instance EJB container invokes ejbPassivate to conserver resources when an EJB has been inactive
17
67 // activate InterestCalculator instance
public void ejbActivate() {} 69 } EJB container invokes ejbActivate to restore an EJB instance that the container passivated previously Fig InterestCalculatorEJB implementation of InterestCalculator remote interface. Line 68
18
Remote reference to InterestCalculator EJB instance
1 // InterestCalculatorClient.java 2 // InterestCalculatorClient is a GUI for interacting with the 3 // InterestCalculator EJB. 4 package com.deitel.advjhtp1.ejb.session.stateful.client; 5 6 // Java core libraries 7 import java.awt.*; 8 import java.awt.event.*; 9 import java.rmi.*; 10 import java.text.*; 11 import java.util.*; 12 13 // Java standard extensions 14 import javax.swing.*; 15 import javax.rmi.*; 16 import javax.naming.*; 17 import javax.ejb.*; 18 19 // Deitel libraries 20 import com.deitel.advjhtp1.ejb.session.stateful.ejb.*; 21 22 public class InterestCalculatorClient extends JFrame { 23 // InterestCalculator remote reference private InterestCalculator calculator; 26 private JTextField principalTextField; private JTextField rateTextField; private JTextField termTextField; private JTextField balanceTextField; private JTextField interestEarnedTextField; 32 Fig InterestCalculatorClient for interacting with InterestCalculator EJB. Line 25 Lines 27-31 Remote reference to InterestCalculator EJB instance JTextFields for obtaining input values from user
19
33 // InterestCalculatorClient constructor
public InterestCalculatorClient() { super( "Stateful Session EJB Example" ); 37 // create InterestCalculator for calculating interest createInterestCalculator(); 40 // create JTextField for entering principal amount createPrincipalTextField(); 43 // create JTextField for entering interest rate createRateTextField(); 46 // create JTextField for entering loan term createTermTextField(); 49 // create uneditable JTextFields for displaying balance // and interest earned balanceTextField = new JTextField( 10 ); balanceTextField.setEditable( false ); 54 interestEarnedTextField = new JTextField( 10 ); interestEarnedTextField.setEditable( false ); 57 // layout components for GUI layoutGUI(); 60 // add WindowListener to remove EJB instances when user // closes window addWindowListener( getWindowListener() ); 64 setSize( 425, 200 ); setVisible( true ); 67 Fig InterestCalculatorClient for interacting with InterestCalculator EJB.
20
Retrieve a reference to the InterestCalculator EJB home interface
} // end InterestCalculatorClient constructor 69 // create InterestCalculator EJB instance public void createInterestCalculator() { // lookup InterestCalculatorHome and create // InterestCalculator EJB try { 76 InitialContext initialContext = new InitialContext(); 78 // lookup InterestCalculator EJB Object homeObject = initialContext.lookup( "InterestCalculator" ); 82 // get InterestCalculatorHome interface InterestCalculatorHome calculatorHome = ( InterestCalculatorHome ) PortableRemoteObject.narrow( homeObject, InterestCalculatorHome.class ); 88 // create InterestCalculator EJB instance calculator = calculatorHome.create(); 91 } // end try 93 // handle exception if InterestCalculator EJB not found catch ( NamingException namingException ) { namingException.printStackTrace(); } 98 // handle exception when creating InterestCalculator EJB catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } InitialContext provides access to the JNDI directory for locating the EJB home interface Fig InterestCalculatorClient for interacting with InterestCalculator EJB. Line 77 Lines Lines Line 90 Lines Lines Retrieve a reference to the InterestCalculator EJB home interface Cast home interface reference using method PortableRemoteObject.narrow to ensure RMI-IIOP-compatible casting Invoke home interface create method to create InterestCalculator instance and store remote reference in calculator InitialContext method lookup throws a NamingException if there is an error locating the home interface InterestCalculatorHome method create throws a RemoteException if there is an error accessing the remote object
21
Set principal value in InterestCalculator EJB
103 // handle exception when creating InterestCalculator EJB catch ( CreateException createException ) { createException.printStackTrace(); } } // end method createInterestCalculator 109 // create JTextField for entering principal amount public void createPrincipalTextField() { principalTextField = new JTextField( 10 ); 114 principalTextField.addActionListener( new ActionListener() { 117 public void actionPerformed( ActionEvent event ) { // set principal amount in InterestCalculator try { double principal = Double.parseDouble( principalTextField.getText() ); 124 calculator.setPrincipal( principal ); } 127 // handle exception setting principal amount catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } 132 // handle wrong number format catch ( NumberFormatException numberFormatException ) { numberFormatException.printStackTrace(); } InterestCalculatorHome method create throws a CreateException if there is an error creating the EJB instance Fig InterestCalculatorClient for interacting with InterestCalculator EJB. Lines Lines Line 125 Set principal value in InterestCalculator EJB Parse user-entered principal value
22
Set interest rate in InterestCalculator EJB
} } ); // end addActionListener } // end method createPrincipalTextField 142 // create JTextField for entering interest rate public void createRateTextField() { rateTextField = new JTextField( 10 ); 147 rateTextField.addActionListener( new ActionListener() { 150 public void actionPerformed( ActionEvent event ) { // set interest rate in InterestCalculator try { double rate = Double.parseDouble( rateTextField.getText() ); 157 // convert from percentage calculator.setInterestRate( rate / ); } 161 // handle exception when setting interest rate catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } } } ); // end addActionListener } // end method createRateTextField 170 Fig InterestCalculatorClient for interacting with InterestCalculator EJB. Lines Line 159 Set interest rate in InterestCalculator EJB Parse user-entered interest rate
23
Parse user-entered term
// create JTextField for entering loan term public void createTermTextField() { termTextField = new JTextField( 10 ); 175 termTextField.addActionListener( new ActionListener() { 178 public void actionPerformed( ActionEvent event ) { // set loan term in InterestCalculator try { int term = Integer.parseInt( termTextField.getText() ); 185 calculator.setTerm( term ); } 188 // handle exception when setting loan term catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } } } ); // end addActionListener } // end method getTermTextField 197 // get JButton for starting calculation public JButton getCalculateButton() { JButton calculateButton = new JButton( "Calculate" ); 202 calculateButton.addActionListener( new ActionListener() { 205 Fig InterestCalculatorClient for interacting with InterestCalculator EJB. Lines Line 186 Parse user-entered term Set number of years interest will accrue in InterestCalculator EJB
24
Invoke getInterestEarned business method to calculate earned interest
public void actionPerformed( ActionEvent event ) { // use InterestCalculator to calculate interest try { 210 // get balance and interest earned double balance = calculator.getBalance(); double interest = calculator.getInterestEarned(); 215 NumberFormat dollarFormatter = NumberFormat.getCurrencyInstance( Locale.US ); 219 balanceTextField.setText( dollarFormatter.format( balance ) ); 222 interestEarnedTextField.setText( dollarFormatter.format( interest ) ); } 226 // handle exception when calculating interest catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } } // end method actionPerformed } ); // end addActionListener 234 return calculateButton; 236 } // end method getCalculateButton 238 Invoke getInterestEarned business method to calculate earned interest Fig InterestCalculatorClient for interacting with InterestCalculator EJB. Line 212 Lines Invoke getBalance business method to calculate balance plus interest
25
239 // lay out GUI components in JFrame
public void layoutGUI() { Container contentPane = getContentPane(); 243 // layout user interface components JPanel inputPanel = new JPanel( new GridLayout( 5, 2 ) ); 246 inputPanel.add( new JLabel( "Principal" ) ); inputPanel.add( principalTextField ); 249 inputPanel.add( new JLabel( "Interest Rate (%)" ) ); inputPanel.add( rateTextField ); 252 inputPanel.add( new JLabel( "Term (years)" ) ); inputPanel.add( termTextField ); 255 inputPanel.add( new JLabel( "Balance" ) ); inputPanel.add( balanceTextField ); 258 inputPanel.add( new JLabel( "Interest Earned" ) ); inputPanel.add( interestEarnedTextField ); 261 // add inputPanel to contentPane contentPane.add( inputPanel, BorderLayout.CENTER ); 264 // create JPanel for calculateButton JPanel controlPanel = new JPanel( new FlowLayout() ); controlPanel.add( getCalculateButton() ); contentPane.add( controlPanel, BorderLayout.SOUTH ); } 270 Fig InterestCalculatorClient for interacting with InterestCalculator EJB.
26
Remove InterestCalculator EJB instance when user closes window
// get WindowListener for exiting application public WindowListener getWindowListener() { return new WindowAdapter() { 275 public void windowClosing( WindowEvent event ) { // check to see if calculator is null if ( calculator.equals( null ) ) { System.exit( -1 ); } 282 else { // remove InterestCalculator instance try { calculator.remove(); } 288 // handle exception removing InterestCalculator catch ( RemoveException removeException ) { removeException.printStackTrace(); System.exit( -1 ); } 294 // handle exception removing InterestCalculator catch ( RemoteException remoteException ) { remoteException.printStackTrace(); System.exit( -1 ); } 300 System.exit( 0 ); } } }; } // end method getWindowListener Fig InterestCalculatorClient for interacting with InterestCalculator EJB. Line 286 Remove InterestCalculator EJB instance when user closes window
27
306 // execute the application public static void main( String[] args ) { new InterestCalculatorClient(); } 312 } Fig InterestCalculatorClient for interacting with InterestCalculator EJB.
28
14.3.2 Deploying Session EJBs
Fig Creating New Application in Application Deployment Tool.
29
14.3.2 Deploying Session EJBs (Cont.)
Fig Specifying EAR file for New Application.
30
14.3.2 Deploying Session EJBs (Cont.)
Fig Creating a New Enterprise Bean.
31
14.3.2 Deploying Session EJBs (Cont.)
Fig Adding InterestCalculator EJB classes.
32
14.3.2 Deploying Session EJBs (Cont.)
Fig Selecting InterestCalculator EJB classes to add.
33
14.3.2 Deploying Session EJBs (Cont.)
Fig Result of adding InterestCalculator EJB classes.
34
14.3.2 Deploying Session EJBs (Cont.)
Fig Specifying Enterprise Bean Class for InterestCalculator EJB.
35
14.3.2 Deploying Session EJBs (Cont.)
Fig Specifying InterestCalculator EJB classes and Stateful Session Bean Type.
36
14.3.2 Deploying Session EJBs (Cont.)
Fig Specifying Container Managed Transactions for InterestCalculator EJB.
37
14.3.2 Deploying Session EJBs (Cont.)
Fig XML deployment descriptor for InterestCalculator EJB.
38
14.3.2 Deploying Session EJBs (Cont.)
Fig Specifying JNDI Name for InterestCalculator EJB.
39
14.3.2 Deploying Session EJBs (Cont.)
Fig Deploying enterprise application to localhost.
40
14.3.2 Deploying Session EJBs (Cont.)
Fig Specifying the Application Deployment Tool should Return Client Jar.
41
14.3.2 Deploying Session EJBs (Cont.)
Fig Successful completion of deployment process.
42
14.3.3 Stateless Session EJBs
Maintain no state information between business method invocations Any Stateless Session EJB instance of a particular type can respond to any client request
43
Remote interface must extend interface EJBObject
1 // MathTool.java 2 // MathTool is the remote interface for the MathTool EJB. 3 package com.deitel.advjhtp1.ejb.session.stateless.ejb; 4 5 // Java core libraries 6 import java.rmi.RemoteException; 7 8 // Java standard extensions 9 import javax.ejb.EJBObject; 10 11 public interface MathTool extends EJBObject 12 { // get Fibonacci series public int[] getFibonacciSeries( int howMany ) throws RemoteException, IllegalArgumentException; 16 // get factorial of given integer public int getFactorial( int number ) throws RemoteException, IllegalArgumentException; 20 } Fig MathTool remote interface for calculating factorias and generating Fibonacci series. Line 11 Lines 15 and 19 Remote interface must extend interface EJBObject throws clauses of business methods must include RemoteException throws clauses of business methods can include application-specific exceptions
44
EJB implementation must implement interface SessionBean
1 // MathToolEJB.java 2 // MathToolEJB is a stateless session EJB with methods for 3 // calculating Fibonacci series and factorials. 4 package com.deitel.advjhtp1.ejb.session.stateless.ejb; 5 6 // Java standard extensions 7 import javax.ejb.*; 8 9 public class MathToolEJB implements SessionBean { 10 private SessionContext sessionContext; 12 // get Fibonacci series public int[] getFibonacciSeries( int howMany ) throws IllegalArgumentException { // throw IllegalArgumentException if series length // is less than zero if ( howMany < 2 ) throw new IllegalArgumentException( "Cannot generate Fibonacci series of " + "length less than two." ); 23 // starting points int startPoint1 = 0; int startPoint2 = 1; 27 // array to contain Fibonacci sequence int[] series = new int[ howMany ]; 30 // set base cases series[ 0 ] = 0; series[ 1 ] = 1; 34 EJB implementation must implement interface SessionBean Fig MathToolEJB implementation of MathTool remote interface. Line 9 Line 11 SessionContext provides access to EJB container
45
Fig. 14.22 MathToolEJB implementation of MathTool remote interface.
// generate Fibonacci series for ( int i = 2; i < howMany; i++ ) { 37 // calculate next number in series series[ i ] = startPoint1 + startPoint2; 40 // set start points for next iteration startPoint1 = startPoint2; startPoint2 = series[ i ]; } 45 return series; 47 } // end method getFibonacciSeries 49 // get factorial of given integer public int getFactorial( int number ) throws IllegalArgumentException { // throw IllegalArgumentException if number less than zero if ( number < 0 ) throw new IllegalArgumentException( "Cannot calculate factorial of negative numbers." ); 58 // base case for recursion, return 1 if ( number == 0 ) return 1; 62 // call getFactorial recursively to calculate factorial else return number * getFactorial( number - 1 ); 66 } // end method getFactorial 68 Fig MathToolEJB implementation of MathTool remote interface.
46
Fig. 14.22 MathToolEJB implementation of MathTool remote interface.
// set SessionContext public void setSessionContext( SessionContext context ) { sessionContext = context; } 74 // create new MathTool instance public void ejbCreate() {} 77 // remove MathTool instance public void ejbRemove() {} 80 // activate MathTool instance public void ejbActivate() {} 83 // passivate MathTool instance public void ejbPassivate() {} 86 } Fig MathToolEJB implementation of MathTool remote interface.
47
Home interface must extend interface EJBHome
1 // MathToolHome.java 2 // MathToolHome is the home interface for the MathTool EJB. 3 package com.deitel.advjhtp1.ejb.session.stateless.ejb; 4 5 // Java core libraries 6 import java.rmi.RemoteException; 7 8 // Java standard extensions 9 import javax.ejb.EJBHome; 10 import javax.ejb.CreateException; 11 12 public interface MathToolHome extends EJBHome { 13 // create new MathTool EJB public MathTool create() throws RemoteException, CreateException; 17 } Fig MathToolHome interface for creating of MathTool EJBs. Line 12 Line 15 Home interface must extend interface EJBHome create methods must return the remote interface type (e.g., MathTool) create method enables clients to create MathTool instances
48
Reference to MathToolHome interface
1 // MathToolClient.java 2 // MathToolClient is a GUI for calculating factorials and 3 // Fibonacci series using the MathTool EJB. 4 package com.deitel.advjhtp1.ejb.session.stateless.client; 5 6 // Java core libraries 7 import java.awt.*; 8 import java.awt.event.*; 9 import java.rmi.*; 10 11 // Java standard extensions 12 import javax.swing.*; 13 import javax.rmi.*; 14 import javax.naming.*; 15 import javax.ejb.*; 16 17 // Deitel libraries 18 import com.deitel.advjhtp1.ejb.session.stateless.ejb.*; 19 20 public class MathToolClient extends JFrame { 21 private MathToolHome mathToolHome; private MathTool mathTool; 24 private JTextArea resultsTextArea; private JTextField numberTextField; 27 // MathToolClient constructor public MathToolClient() { super( "Stateless Session EJB Example" ); 32 // create MathTool for calculating factorials // and Fibonacci series createMathTool(); Fig MathToolClient for interacting with MathTool EJB. Line 22 Line 23 Reference to MathToolHome interface Remote reference to MathTool EJB
49
Obtain InitialContext for looking up MathToolHome interface
36 // create and lay out GUI components createGUI(); 39 addWindowListener( getWindowListener() ); 41 setSize( 425, 200 ); setVisible( true ); 44 } // end MathToolClient constructor 46 // create MathTool EJB instance private void createMathTool() { // lookup MathToolHome and create MathTool EJB try { 52 InitialContext initialContext = new InitialContext(); 54 // lookup MathTool EJB Object homeObject = initialContext.lookup( "MathTool" ); 58 // get MathToolHome interface mathToolHome = ( MathToolHome ) PortableRemoteObject.narrow( homeObject, MathToolHome.class ); 63 // create MathTool EJB instance mathTool = mathToolHome.create(); 66 } // end try 68 Fig MathToolClient for interacting with MathTool EJB. Line 53 Lines Lines Line 65 Obtain InitialContext for looking up MathToolHome interface Look up MathToolHome interface in JNDI Cast MathToolHome reference to proper type Create new MathTool EJB instance for use throughout this program
50
Fig. 14.23 MathToolClient for interacting with MathTool EJB.
// handle exception if MathTool EJB is not found catch ( NamingException namingException ) { namingException.printStackTrace(); } 73 // handle exception when creating MathTool EJB catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } 78 // handle exception when creating MathTool EJB catch ( CreateException createException ) { createException.printStackTrace(); } } // end method createMathTool 84 // create JButton for calculating factorial private JButton getFactorialButton() { JButton factorialButton = new JButton( "Calculate Factorial" ); 90 // add ActionListener for factorial button factorialButton.addActionListener( new ActionListener() { 94 public void actionPerformed( ActionEvent event ) { // use MathTool EJB to calculate factorial try { 99 int number = Integer.parseInt( numberTextField.getText() ); 102 Fig MathToolClient for interacting with MathTool EJB.
51
Fig. 14.23 MathToolClient for interacting with MathTool EJB. Line 104
// get Factorial of number input by user int result = mathTool.getFactorial( number ); 105 // display results in resultsTextArea resultsTextArea.setText( number + "! = " + result ); 109 } // end try 111 // handle exception calculating factorial catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } } // end method actionPerformed } ); // end addActionListener 119 return factorialButton; 121 } // end method getFactorialButton 123 // create JButton for generating Fibonacci series private JButton getFibonacciButton() { JButton fibonacciButton = new JButton( "Fibonacci Series" ); 129 // add ActionListener for generating Fibonacci series fibonacciButton.addActionListener( new ActionListener() { 133 public void actionPerformed( ActionEvent event ) { Invoke getFactorial business method in stateless MathTool EJB to calculate factorial Fig MathToolClient for interacting with MathTool EJB. Line 104
52
Append each value in Fibonacci sequence to a StringBuffer for display
// generate Fibonacci series using MathTool EJB try { 138 // get number entered by user int number = Integer.parseInt( numberTextField.getText() ); 142 // get Fibonacci series int[] series = mathTool.getFibonacciSeries( number ); 146 // create StringBuffer to store series StringBuffer buffer = new StringBuffer( "The first " ); 150 buffer.append( number ); 152 buffer.append( " Fibonacci number(s): \n" ); 154 // append each number in series to buffer for ( int i = 0; i < series.length; i++ ) { 157 // do not add comma before first number if ( i != 0 ) buffer.append( ", " ); 161 // append next number in series to buffer buffer.append( String.valueOf( series[ i ] ) ); } 166 // display series in resultsTextArea resultsTextArea.setText( buffer.toString() ); 169 } // end try Fig MathToolClient for interacting with MathTool EJB. Lines Lines Invoke getFibonacciSeries business method in stateless MathTool EJB to calculate Fibonacci sequence Append each value in Fibonacci sequence to a StringBuffer for display
53
Fig. 14.23 MathToolClient for interacting with MathTool EJB.
171 // handle exception calculating series catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } } // end method actionPerformed } ); // end addActionListener 179 return fibonacciButton; 181 } // end method getFibonacciButton 183 // create lay out GUI components public void createGUI() { // create JTextArea to show results resultsTextArea = new JTextArea(); resultsTextArea.setLineWrap( true ); resultsTextArea.setWrapStyleWord( true ); resultsTextArea.setEditable( false ); 192 // create JTextField for user input numberTextField = new JTextField( 10 ); 195 // create JButton for calculating factorial JButton factorialButton = getFactorialButton(); 198 // create JButton for generating Fibonacci series JButton fibonacciButton = getFibonacciButton(); 201 Container contentPane = getContentPane(); 203 Fig MathToolClient for interacting with MathTool EJB.
54
Fig. 14.23 MathToolClient for interacting with MathTool EJB.
// put resultsTextArea in a JScrollPane JScrollPane resultsScrollPane = new JScrollPane( resultsTextArea ); 207 contentPane.add( resultsScrollPane, BorderLayout.CENTER ); 210 // add input components to new JPanel JPanel inputPanel = new JPanel( new FlowLayout() ); inputPanel.add( new JLabel( "Enter an integer: " ) ); inputPanel.add( numberTextField ); 215 // add JButton components to new JPanel JPanel buttonPanel = new JPanel( new FlowLayout() ); buttonPanel.add( factorialButton ); buttonPanel.add( fibonacciButton ); 220 // add inputPanel and buttonPanel to new JPanel JPanel controlPanel = new JPanel( new GridLayout( 2, 2 ) ); 224 controlPanel.add( inputPanel ); controlPanel.add( buttonPanel ); 227 contentPane.add( controlPanel, BorderLayout.NORTH ); 229 } // end method createGUI 231 // get WindowListener for exiting application private WindowListener getWindowListener() { return new WindowAdapter() { 236 public void windowClosing( WindowEvent event ) { Fig MathToolClient for interacting with MathTool EJB.
55
Fig. 14.23 MathToolClient for interacting with MathTool EJB. Line 241
// remove MathTool instance try { mathTool.remove(); } 243 // handle exception when removing MathTool EJB catch ( RemoveException removeException ) { removeException.printStackTrace(); System.exit( -1 ); } 249 // handle exception when removing MathTool EJB catch ( RemoteException remoteException ) { remoteException.printStackTrace(); System.exit( -1 ); } 255 System.exit( 0 ); } // end method windowClosing }; } // end method getWindowListener 260 // execute application public static void main( String[] args ) { MathToolClient client = new MathToolClient(); } 266 } Remove MathTool EJB instance when user closes window Fig MathToolClient for interacting with MathTool EJB. Line 241
56
Fig. 14.23 MathToolClient for interacting with MathTool EJB.
57
EJB Transactions Distributed transactions include multiple databases and/or multiple application servers E.g., a transfer of funds from one bank to another Such a transfer must occur in the context of an atomic transaction, otherwise there is the potential for data loss Bean-managed transaction demarcation enables bean developers to specify transaction boundaries using the Java Transaction API Container-managed transaction demarcation enables EJB deployers to specify transaction boundaries declaratively when deploying EJBs
58
1 // MoneyTransfer.java 2 // MoneyTransfer is the remote interface for the MoneyTransfer 3 // EJB. 4 package com.deitel.advjhtp1.ejb.transactions; 5 6 // Java core libraries 7 import java.rmi.RemoteException; 8 9 // Java standard extensions 10 import javax.ejb.EJBObject; 11 12 public interface MoneyTransfer extends EJBObject { 13 // transfer amount from BankABC to BankXYZ public void transfer( double amount ) throws RemoteException; 16 // get BankABC account balance public double getBankABCBalance() throws RemoteException; 19 // get BankXYZ account balance public double getBankXYZBalance() throws RemoteException; 22 } Fig MoneyTransfer remote interface for transferring money and getting account balances. Lines 15, 18 and 21 Business methods whose implementations include programmer-defined transaction boundaries
59
1 // MoneyTransferHome.java
2 // MoneyTransferHome is the home interface for the 3 // MoneyTransferHome EJB. 4 package com.deitel.advjhtp1.ejb.transactions; 5 6 // Java core libraries 7 import java.rmi.RemoteException; 8 9 // Java standard extensions 10 import javax.ejb.*; 11 12 public interface MoneyTransferHome extends EJBHome { 13 // create MoneyTransfer EJB public MoneyTransfer create() throws RemoteException, CreateException; 17 } Fig MoneyTransferHome remote interface for creating MoneyTransfer EJBs.
60
Connections for bank databases
1 // MoneyTransferEJB.java 2 // MoneyTransferEJB is a stateless session EJB for transferring 3 // funds from an Account at BankABC to an Account at BankXYZ 4 // using bean-managed transaction demarcation. 5 package com.deitel.advjhtp1.ejb.transactions.beanmanaged; 6 7 // Java core libraries 8 import java.util.*; 9 import java.sql.*; 10 11 // Java standard extensions 12 import javax.ejb.*; 13 import javax.naming.*; 14 import javax.transaction.*; 15 import javax.sql.*; 16 17 public class MoneyTransferEJB implements SessionBean { 18 private SessionContext sessionContext; private Connection bankOneConnection; private Connection bankTwoConnection; private PreparedStatement withdrawalStatement; private PreparedStatement depositStatement; 24 // transfer funds from BankABC to BankXYZ public void transfer( double amount ) throws EJBException { // create transaction for transferring funds UserTransaction transaction = sessionContext.getUserTransaction(); 31 // begin bean-managed transaction demarcation try { transaction.begin(); } Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation. Lines Lines Lines Line 34 Connections for bank databases PreparedStatements for withdrawing from, and depositing to, bank accounts Create UserTransaction for transferring money between accounts Begin transaction
61
If transaction cannot be started, throw an EJBException
36 // catch exception if method begin fails catch ( Exception exception ) { 39 // throw EJBException indicating transaction failed throw new EJBException( exception ); } 43 // transfer funds from account in BankABC to account // in BankXYZ using bean-managed transaction demarcation try { 47 withdrawalStatement.setDouble( 1, amount ); 49 // withdraw funds from account at BankABC withdrawalStatement.executeUpdate(); 52 depositStatement.setDouble( 1, amount ); 54 // deposit funds in account at BankXYZ depositStatement.executeUpdate(); 57 // commit transaction transaction.commit(); 60 } // end try 62 // handle exceptions when withdrawing, depositing and // committing transaction catch ( Exception exception ) { 66 // attempt rollback of transaction try { transaction.rollback(); } Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation. Lines Lines Line 59 Line 69 If transaction cannot be started, throw an EJBException Transfer funds between accounts If database updates are successful, commit the transaction If there are problems with any of the database updates, rollback the transaction to restore the original data
62
71 // handle exception when rolling back transaction catch ( SystemException systemException ) { throw new EJBException( systemException ); } 76 // throw EJBException indicating transaction failed throw new EJBException( exception ); } 80 } // end method transfer 82 // get balance of Account at BankABC public double getBankABCBalance() throws EJBException { // get balance of Account at BankABC try { 88 // select balance for Account # 12345 String select = "SELECT balance FROM Account " + "WHERE accountID = 12345"; 92 PreparedStatement selectStatement = bankOneConnection.prepareStatement( select ); 95 ResultSet resultSet = selectStatement.executeQuery(); 97 // get first record in ResultSet and return balance if ( resultSet.next() ) return resultSet.getDouble( "balance" ); else throw new EJBException( "Account not found" ); 103 } // end try 105 Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation. Lines Execute simple SQL SELECT statement to retrieve the balances of the accounts at each bank.
63
106 // handle exception when getting Account balance
catch ( SQLException sqlException ) { throw new EJBException( sqlException ); } 110 } // end method getBankABCBalance 112 // get balance of Account at BankXYZ public double getBankXYZBalance() throws EJBException { // get balance of Account at BankXYZ try { 118 // select balance for Account # 54321 String select = "SELECT balance FROM Account " + "WHERE accountID = 54321"; 122 PreparedStatement selectStatement = bankTwoConnection.prepareStatement( select ); 125 ResultSet resultSet = selectStatement.executeQuery(); 127 // get first record in ResultSet and return balance if ( resultSet.next() ) return resultSet.getDouble( "balance" ); else throw new EJBException( "Account not found" ); 133 } // end try 135 // handle exception when getting Account balance catch ( SQLException sqlException ) { throw new EJBException( sqlException ); } 140 Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation. Lines Execute simple SQL SELECT statement to retrieve the balances of the accounts at each bank.
64
141 } // end method getBankXYZBalance
142 // set SessionContext public void setSessionContext( SessionContext context ) throws EJBException { sessionContext = context; 148 openDatabaseResources(); } 151 // create MoneyTransfer instance public void ejbCreate() {} 154 // remove MoneyTransfer instance public void ejbRemove() throws EJBException { closeDatabaseResources(); } 160 // passivate MoneyTransfer instance public void ejbPassivate() throws EJBException { closeDatabaseResources(); } 166 // activate MoneyTransfer instance public void ejbActivate() throws EJBException { openDatabaseResources(); } 172 Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation. Lines 149 and Lines 158 and 164 Allocate database Connections when the EJB container provides a SessionContext or activates the EJB Close database Connections when the container removes or passiavates the EJB
65
Close the Connections and PreparedStatements.
// close database Connections and PreparedStatements private void closeDatabaseResources() throws EJBException { // close database resources try { 178 // close PreparedStatements depositStatement.close(); depositStatement = null; 182 withdrawalStatement.close(); withdrawalStatement = null; 185 // close database Connections bankOneConnection.close(); bankOneConnection = null; 189 bankTwoConnection.close(); bankTwoConnection = null; } 193 // handle exception closing database connections catch ( SQLException sqlException ) { throw new EJBException( sqlException ); } 198 } // end method closeDatabaseResources 200 // open database Connections and create PreparedStatements private void openDatabaseResources() throws EJBException { // look up the BankABC and BankXYZ DataSources and create // Connections for each try { Context initialContext = new InitialContext(); Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation. Lines Lines Create Connections and PreparedStatements for each database for use throughout the lifetime of the MoneyTransfer EJB instance.
66
208 // get DataSource reference from JNDI directory DataSource dataSource = ( DataSource ) initialContext.lookup( "java:comp/env/jdbc/BankABC" ); 213 // get Connection from DataSource bankOneConnection = dataSource.getConnection(); 216 dataSource = ( DataSource) initialContext.lookup( "java:comp/env/jdbc/BankXYZ" ); 219 bankTwoConnection = dataSource.getConnection(); 221 // prepare withdraw statement for account #12345 at // BankABC String withdrawal = "UPDATE Account SET balance = " + "balance - ? WHERE accountID = 12345"; 226 withdrawalStatement = bankOneConnection.prepareStatement( withdrawal ); 229 // prepare deposit statment for account #54321 at // BankXYZ String deposit = "UPDATE Account SET balance = " + "balance + ? WHERE accountID = 54321"; 234 depositStatement = bankTwoConnection.prepareStatement( deposit ); 237 } // end try 239 // handle exception if DataSource not found in directory catch ( NamingException namingException ) { throw new EJBException( namingException ); Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation.
67
} 244 // handle exception getting Connection to DataSource catch ( SQLException sqlException ) { throw new EJBException( sqlException ); } 249 } // end method openDatabaseResources 251 } Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation.
68
1 // MoneyTransferEJB.java
2 // MoneyTransferEJB is a stateless session EJB for transferring 3 // funds from an Account at BankABC to an Account at BankXYZ 4 // using container-managed transaction demarcation. 5 package com.deitel.advjhtp1.ejb.transactions.containermanaged; 6 7 // Java core libraries 8 import java.util.*; 9 import java.sql.*; 10 11 // Java standard extensions 12 import javax.ejb.*; 13 import javax.naming.*; 14 import javax.sql.*; 15 16 public class MoneyTransferEJB implements SessionBean { 17 private SessionContext sessionContext; private Connection bankOneConnection; private Connection bankTwoConnection; private PreparedStatement withdrawalStatement; private PreparedStatement depositStatement; 23 // transfer funds from BankABC to BankXYZ public void transfer( double amount ) throws EJBException { // transfer funds from account in BankABC to account in // BankXYZ using container-managed transaction demarcation try { 30 withdrawalStatement.setDouble( 1, amount ); 32 // withdraw funds from account at BankABC withdrawalStatement.executeUpdate(); 35 Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using container-managed transaction demarcation.
69
36 depositStatement.setDouble( 1, amount );
37 // deposit funds in account at BankXYZ depositStatement.executeUpdate(); 40 } // end try 42 // handle exception withdrawing and depositing catch ( SQLException sqlException ) { 45 // throw EJBException to indicate transfer failed // and roll back container-managed transaction throw new EJBException( sqlException ); } 50 } // end method transfer 52 // get balance of Account at BankABC public double getBankABCBalance() throws EJBException { // get balance of Account at BankABC try { 58 // select balance for Account # 12345 String select = "SELECT balance FROM Account " + "WHERE accountID = 12345"; 62 PreparedStatement selectStatement = bankOneConnection.prepareStatement( select ); 65 ResultSet resultSet = selectStatement.executeQuery(); 67 Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using container-managed transaction demarcation. Line 48 Throws an EJBException in response to any SQLException thrown from lines
70
68 // get first record in ResultSet and return balance
if ( resultSet.next() ) return resultSet.getDouble( "balance" ); else throw new EJBException( "Account not found" ); 73 } // end try 75 // handle exception when getting Account balance catch ( SQLException sqlException ) { throw new EJBException( sqlException ); } 80 } // end method getBankABCBalance 82 // get balance of Account at BankXYZ public double getBankXYZBalance() throws EJBException { // get balance of Account at BankXYZ try { 88 // select balance for Account # 54321 String select = "SELECT balance FROM Account " + "WHERE accountID = 54321"; 92 PreparedStatement selectStatement = bankTwoConnection.prepareStatement( select ); 95 ResultSet resultSet = selectStatement.executeQuery(); 97 // get first record in ResultSet and return balance if ( resultSet.next() ) return resultSet.getDouble( "balance" ); Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using container-managed transaction demarcation.
71
else throw new EJBException( "Account not found" ); 103 } // end try 105 // handle exception when getting Account balance catch ( SQLException sqlException ) { throw new EJBException( sqlException ); } 110 } // end method getBankXYZBalance 112 // set SessionContext public void setSessionContext( SessionContext context ) throws EJBException { sessionContext = context; 118 openDatabaseResources(); } 121 // create MoneyTransfer instance public void ejbCreate() {} 124 // remove MoneyTransfer instance public void ejbRemove() throws EJBException { closeDatabaseResources(); } 130 // passivate MoneyTransfer instance public void ejbPassivate() throws EJBException { closeDatabaseResources(); } Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using container-managed transaction demarcation.
72
136 // activate MoneyTransfer instance public void ejbActivate() throws EJBException { openDatabaseResources(); } 142 // close database Connections and PreparedStatements private void closeDatabaseResources() throws EJBException { // close database resources try { 148 // close PreparedStatements depositStatement.close(); depositStatement = null; 152 withdrawalStatement.close(); withdrawalStatement = null; 155 // close database Connections bankOneConnection.close(); bankOneConnection = null; 159 bankTwoConnection.close(); bankTwoConnection = null; } 163 // handle exception closing database connections catch ( SQLException sqlException ) { throw new EJBException( sqlException ); } 168 } // end method closeDatabaseConnections 170 Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using container-managed transaction demarcation.
73
171 // open database Connections and create PreparedStatements
private void openDatabaseResources() throws EJBException { // look up the BankABC and BankXYZ DataSources and create // Connections for each try { Context initialContext = new InitialContext(); 178 // get DataSource reference from JNDI directory DataSource dataSource = ( DataSource ) initialContext.lookup( "java:comp/env/jdbc/BankABC" ); 183 // get Connection from DataSource bankOneConnection = dataSource.getConnection(); 186 dataSource = ( DataSource) initialContext.lookup( "java:comp/env/jdbc/BankXYZ" ); 189 bankTwoConnection = dataSource.getConnection(); 191 // prepare withdraw statement for account #12345 at // BankABC String withdrawal = "UPDATE Account SET balance = " + "balance - ? WHERE accountID = 12345"; 196 withdrawalStatement = bankOneConnection.prepareStatement( withdrawal ); 199 // prepare deposit statment for account #54321 at // BankXYZ String deposit = "UPDATE Account SET balance = " + "balance + ? WHERE accountID = 54321"; 204 Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using container-managed transaction demarcation.
74
depositStatement = bankTwoConnection.prepareStatement( deposit ); 207 } // end try 209 // handle exception if DataSource not found in directory catch ( NamingException namingException ) { throw new EJBException( namingException ); } 214 // handle exception getting Connection to DataSource catch ( SQLException sqlException ) { throw new EJBException( sqlException ); } 219 } // end method openDatabaseConnections 221 } Fig MoneyTransferEJB implementation of MoneyTransfer remote interface using container-managed transaction demarcation.
75
14.4.3 Container-Managed Transaction Demarcation
76
1 // MoneyTransferEJBClient.java
2 // MoneyTransferEJBClient is a client for interacting with 3 // the MoneyTransfer EJB. 4 package com.deitel.advjhtp1.ejb.transactions.client; 5 6 // Java core libraries 7 import java.awt.*; 8 import java.awt.event.*; 9 import java.rmi.*; 10 11 // Java standard extensions 12 import javax.swing.*; 13 import javax.ejb.*; 14 import javax.rmi.*; 15 import javax.naming.*; 16 17 // Deitel libraries 18 import com.deitel.advjhtp1.ejb.transactions.*; 19 20 public class MoneyTransferEJBClient extends JFrame { 21 private MoneyTransfer moneyTransfer; 23 private JTextField bankABCBalanceTextField; private JTextField bankXYZBalanceTextField; private JTextField transferAmountTextField; 27 // MoneyTransferEJBClient constructor public MoneyTransferEJBClient( String JNDIName ) { super( "MoneyTransferEJBClient" ); 32 // create MoneyTransfer EJB for transferring money createMoneyTransfer( JNDIName ); 35 Fig MoneyTransferEJBClient for interacting with MoneyTransfer EJB. Lines Line 34 Declare JTextFields to display the account balances and accept a user-input transfer amount. Invokes method createMoneyTransfer to create a new MoneyTransfer EJB instance.
77
Invokes method createGUI to create and lay out GUI components for the application.
38 // display current balances at BankABC and BankXYZ displayBalances(); 41 setSize( 400, 300 ); setVisible( true ); } 45 // create MoneyTransferEJB for transferring money private void createMoneyTransfer( String JNDIName ) { // look up MoneyTransfer EJB using given JNDIName try { InitialContext context = new InitialContext(); 52 // lookup MoneyTransfer EJB Object homeObject = context.lookup( JNDIName ); 55 // get MoneyTransfer interface MoneyTransferHome moneyTransferHome = ( MoneyTransferHome ) PortableRemoteObject.narrow( homeObject, MoneyTransferHome.class ); 60 // create MathTool EJB instance moneyTransfer = moneyTransferHome.create(); 63 } // end try 65 // handle exception when looking up MoneyTransfer EJB catch ( NamingException namingException ) { namingException.printStackTrace(); } 70 Invokes method displayBalances to display the current account balances at BankABC and BankXYZ. Fig MoneyTransferEJBClient for interacting with MoneyTransfer EJB. Line 37 Line 40 Lines Line 51 Lines Line 62 Method createMoneyTransfer uses the MoneyTransferHome interface to create a MoneyTransfer EJB instance. Creates an InitialContext for locating the MoneyTransfer EJB in the JNDI directory. Invoke InitialContext method lookup to get a remote reference to the MoneyTransferHome interface. Creates a new MoneyTransfer EJB instance by invoking MoneyTransferHome method create.
78
71 // handle exception when looking up MoneyTransfer EJB
catch ( CreateException createException ) { createException.printStackTrace(); } 75 // handle exception when looking up MoneyTransfer EJB catch ( RemoteException remoteException ) { remoteException.printStackTrace(); } } // end method createMoneyTransfer 81 // display balance in account at BankABC private void displayBalances() { try { 86 // get and display BankABC Account balance double balance = moneyTransfer.getBankABCBalance(); 89 bankABCBalanceTextField.setText( String.valueOf( balance ) ); 92 // get and display BankXYZ Account balance balance = moneyTransfer.getBankXYZBalance(); 95 bankXYZBalanceTextField.setText( String.valueOf( balance ) ); } 99 // handle exception when invoke MoneyTransfer EJB methods catch ( RemoteException remoteException ) { JOptionPane.showMessageDialog( this, remoteException.getMessage() ); } } // end method displayBalances Fig MoneyTransferEJBClient for interacting with MoneyTransfer EJB.
79
106 // create button to transfer funds between accounts private JButton getTransferButton() { JButton transferButton = new JButton( "Transfer" ); 111 transferButton.addActionListener( new ActionListener() { 114 public void actionPerformed( ActionEvent event ) { try { 118 // get transfer amount from JTextField double amount = Double.parseDouble( transferAmountTextField.getText() ); 122 // transfer money moneyTransfer.transfer( amount ); 125 // display new balances displayBalances(); } 129 // handle exception when transferring money catch ( RemoteException remoteException ) { JOptionPane.showMessageDialog( MoneyTransferEJBClient.this, remoteException.getMessage() ); } } // end method actionPerformed } ); // end addActionListener 139 return transferButton; Method getTransferButton creates a JButton to transfer funds from BankABC to BankXYZ. Fig MoneyTransferEJBClient for interacting with MoneyTransfer EJB. Lines Lines Line 127 Read the transfer amount from the user and invoke MoneyTransfer method transfer. Invokes method displayBalances to update the display with the new account balances.
80
141 } // end method getTransferButton 143 // create and lay out GUI components private void createGUI() { // create JTextFields for user input and display bankABCBalanceTextField = new JTextField( 10 ); bankABCBalanceTextField.setEditable( false ); 150 bankXYZBalanceTextField = new JTextField( 10 ); bankXYZBalanceTextField.setEditable( false ); 153 transferAmountTextField = new JTextField( 10 ); 155 // create button to transfer between accounts JButton transferButton = getTransferButton(); 158 // layout user interface Container contentPane = getContentPane(); contentPane.setLayout( new GridLayout( 3, 2 ) ); 162 contentPane.add( transferButton ); contentPane.add( transferAmountTextField ); 165 contentPane.add( new JLabel( "Bank ABC Balance: " ) ); contentPane.add( bankABCBalanceTextField ); 168 contentPane.add( new JLabel( "Bank XYZ Balance: " ) ); contentPane.add( bankXYZBalanceTextField ); 171 } // end method createGUI 173 Fig MoneyTransferEJBClient for interacting with MoneyTransfer EJB.
81
174 // get WindowListener for exiting application
private WindowListener getWindowListener() { // remove MoneyTransfer EJB when user exits application return new WindowAdapter() { 179 public void windowClosing( WindowEvent event ) { 181 // remove MoneyTransfer EJB try { moneyTransfer.remove(); } 186 // handle exception removing MoneyTransfer EJB catch ( RemoveException removeException ) { removeException.printStackTrace(); System.exit( 1 ); } 192 // handle exception removing MoneyTransfer EJB catch ( RemoteException remoteException ) { remoteException.printStackTrace(); System.exit( 1 ); } 198 System.exit( 0 ); 200 } // end method windowClosing }; } // end method getWindowListener 204 Fig MoneyTransferEJBClient for interacting with MoneyTransfer EJB.
82
205 // execute application
public static void main( String[] args ) { // ensure user provided JNDI name for MoneyTransfer EJB if ( args.length != 1 ) System.err.println( "Usage: java MoneyTransferEJBClient <JNDI Name>" ); 212 // start application using provided JNDI name else new MoneyTransferEJBClient( args[ 0 ] ); } 217 } Fig MoneyTransferEJBClient for interacting with MoneyTransfer EJB.
83
MoneyTransferEJBClient.java program output
84
14.4.5 Deploying the MoneyTransfer EJB
Create resource references to the databases Transaction management
85
14.4.5 Deploying the MoneyTransfer EJB (Cont.)
Fig Resource References dialog of New Enterprise Bean Wizard.
86
14.4.5 Deploying the MoneyTransfer EJB (Cont.)
Fig Add Resource Reference for BankABC.
87
14.4.5 Deploying the MoneyTransfer EJB (Cont.)
Fig Add Resource Reference for BankXYZ.
88
14.4.5 Deploying the MoneyTransfer EJB (Cont.)
Fig Selecting Bean-Managed Transactions.
89
14.4.5 Deploying the MoneyTransfer EJB (Cont.)
Fig Selecting Container-Managed Transactions.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.