Advanced Java 2 Platform HOW TO PROGRAM phần 6 pptx

187 356 0
Advanced Java 2 Platform HOW TO PROGRAM phần 6 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 14 Session EJBs and Distributed Transactions 873 Please refer to Section 14.3.2 for deployment instructions. Recall that MathTool is a stateless session EJB, so you must specify this in the deployment process. Also, be sure to specify an appropriate JNDI name (e.g., MathTool) for the MathTool EJB. MathToolClient (Fig. 14.24) is an application client for the MathTool EJB. The user interface consists of a JTextField into which the user can enter an integer, a JButton to invoke MathTool method getFactorial and a JButton to invoke MathTool method getFibonacciSeries. The calculation results are displayed in a JTextArea. The MathToolClient constructor (lines 29–45) invokes method createMath- Tool (line 35) to create a new instance of the MathTool EJB. Line 38 invokes method createGUI to create and lay out GUI components for the application’s user interface. Method createMathTool (lines 48–83) uses an InitialContext (line 53) to look up the MathToolHome interface in the JNDI Directory (lines 56–57). Line 65 invokes MathToolHome method create to create a MathTool EJB instance. Method getFactorialButton (lines 86–122) creates a JButton that, when pressed, invokes MathTool EJB method getFactorial. Lines 100–104 parse the number entered in numberTextField and invoke method getFactorial of the MathTool remote interface. Lines 107–108 display the factorial in resultsText- Area. Lines 113–115 catch a RemoteException if there is an error invoking method getFactorial. Method getFibonacciButton (lines 125–182) creates a JButton that, when clicked, invokes MathTool EJB method getFibonacciSeries. Lines 140–145 parse the number entered in numberTextField and invoke method getFibonac- ciSeries of the MathTool remote interface. Method getFibonacciSeries returns an array of integers containing a Fibonacci series of the length specified by the integer argument howMany. Lines 148–168 build a StringBuffer containing the Fibonacci series and display the series in resultsTextArea. 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 14 // create new MathTool EJB 15 public MathTool create() throws RemoteException, 16 CreateException; 17 } Fig. 14.23 Fig. 14.23Fig. 14.23 Fig. 14.23 MathToolHome interface for creating MathTool EJBs. 874 Session EJBs and Distributed Transactions Chapter 14 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 22 private MathToolHome mathToolHome; 23 private MathTool mathTool; 24 25 private JTextArea resultsTextArea; 26 private JTextField numberTextField; 27 28 // MathToolClient constructor 29 public MathToolClient() 30 { 31 super( "Stateless Session EJB Example" ); 32 33 // create MathTool for calculating factorials 34 // and Fibonacci series 35 createMathTool(); 36 37 // create and lay out GUI components 38 createGUI(); 39 40 addWindowListener( getWindowListener() ); 41 42 setSize( 425, 200 ); 43 setVisible( true ); 44 45 } // end MathToolClient constructor 46 47 // create MathTool EJB instance 48 private void createMathTool() 49 { 50 // lookup MathToolHome and create MathTool EJB 51 try { 52 53 InitialContext initialContext = new InitialContext(); Fig. 14.24 Fig. 14.24Fig. 14.24 Fig. 14.24 MathToolClient for interacting with MathTool EJB (part 1 of 6). Chapter 14 Session EJBs and Distributed Transactions 875 54 55 // lookup MathTool EJB 56 Object homeObject = 57 initialContext.lookup( "MathTool" ); 58 59 // get MathToolHome interface 60 mathToolHome = ( MathToolHome ) 61 PortableRemoteObject.narrow( homeObject, 62 MathToolHome.class ); 63 64 // create MathTool EJB instance 65 mathTool = mathToolHome.create(); 66 67 } // end try 68 69 // handle exception if MathTool EJB is not found 70 catch ( NamingException namingException ) { 71 namingException.printStackTrace(); 72 } 73 74 // handle exception when creating MathTool EJB 75 catch ( RemoteException remoteException ) { 76 remoteException.printStackTrace(); 77 } 78 79 // handle exception when creating MathTool EJB 80 catch ( CreateException createException ) { 81 createException.printStackTrace(); 82 } 83 } // end method createMathTool 84 85 // create JButton for calculating factorial 86 private JButton getFactorialButton() 87 { 88 JButton factorialButton = 89 new JButton( "Calculate Factorial" ); 90 91 // add ActionListener for factorial button 92 factorialButton.addActionListener( 93 new ActionListener() { 94 95 public void actionPerformed( ActionEvent event ) 96 { 97 // use MathTool EJB to calculate factorial 98 try { 99 100 int number = Integer.parseInt( 101 numberTextField.getText() ); 102 103 // get Factorial of number input by user 104 int result = mathTool.getFactorial( number ); 105 Fig. 14.24 Fig. 14.24Fig. 14.24 Fig. 14.24 MathToolClient for interacting with MathTool EJB (part 2 of 6). 876 Session EJBs and Distributed Transactions Chapter 14 106 // display results in resultsTextArea 107 resultsTextArea.setText( number + "! = " + 108 result ); 109 110 } // end try 111 112 // handle exception calculating factorial 113 catch ( RemoteException remoteException ) { 114 remoteException.printStackTrace(); 115 } 116 } // end method actionPerformed 117 } 118 ); // end addActionListener 119 120 return factorialButton; 121 122 } // end method getFactorialButton 123 124 // create JButton for generating Fibonacci series 125 private JButton getFibonacciButton() 126 { 127 JButton fibonacciButton = 128 new JButton( "Fibonacci Series" ); 129 130 // add ActionListener for generating Fibonacci series 131 fibonacciButton.addActionListener( 132 new ActionListener() { 133 134 public void actionPerformed( ActionEvent event ) 135 { 136 // generate Fibonacci series using MathTool EJB 137 try { 138 139 // get number entered by user 140 int number = Integer.parseInt( 141 numberTextField.getText() ); 142 143 // get Fibonacci series 144 int[] series = mathTool.getFibonacciSeries( 145 number ); 146 147 // create StringBuffer to store series 148 StringBuffer buffer = 149 new StringBuffer( "The first " ); 150 151 buffer.append( number ); 152 153 buffer.append( " Fibonacci number(s): \n" ); 154 155 // append each number in series to buffer 156 for ( int i = 0; i < series.length; i++ ) { 157 Fig. 14.24 Fig. 14.24Fig. 14.24 Fig. 14.24 MathToolClient for interacting with MathTool EJB (part 3 of 6). Chapter 14 Session EJBs and Distributed Transactions 877 158 // do not add comma before first number 159 if ( i != 0 ) 160 buffer.append( ", " ); 161 162 // append next number in series to buffer 163 buffer.append( String.valueOf( 164 series[ i ] ) ); 165 } 166 167 // display series in resultsTextArea 168 resultsTextArea.setText( buffer.toString() ); 169 170 } // end try 171 172 // handle exception calculating series 173 catch ( RemoteException remoteException ) { 174 remoteException.printStackTrace(); 175 } 176 } // end method actionPerformed 177 } 178 ); // end addActionListener 179 180 return fibonacciButton; 181 182 } // end method getFibonacciButton 183 184 // create lay out GUI components 185 public void createGUI() 186 { 187 // create JTextArea to show results 188 resultsTextArea = new JTextArea(); 189 resultsTextArea.setLineWrap( true ); 190 resultsTextArea.setWrapStyleWord( true ); 191 resultsTextArea.setEditable( false ); 192 193 // create JTextField for user input 194 numberTextField = new JTextField( 10 ); 195 196 // create JButton for calculating factorial 197 JButton factorialButton = getFactorialButton(); 198 199 // create JButton for generating Fibonacci series 200 JButton fibonacciButton = getFibonacciButton(); 201 202 Container contentPane = getContentPane(); 203 204 // put resultsTextArea in a JScrollPane 205 JScrollPane resultsScrollPane = 206 new JScrollPane( resultsTextArea ); 207 208 contentPane.add( resultsScrollPane, 209 BorderLayout.CENTER ); 210 Fig. 14.24 Fig. 14.24Fig. 14.24 Fig. 14.24 MathToolClient for interacting with MathTool EJB (part 4 of 6). 878 Session EJBs and Distributed Transactions Chapter 14 211 // add input components to new JPanel 212 JPanel inputPanel = new JPanel( new FlowLayout() ); 213 inputPanel.add( new JLabel( "Enter an integer: " ) ); 214 inputPanel.add( numberTextField ); 215 216 // add JButton components to new JPanel 217 JPanel buttonPanel = new JPanel( new FlowLayout() ); 218 buttonPanel.add( factorialButton ); 219 buttonPanel.add( fibonacciButton ); 220 221 // add inputPanel and buttonPanel to new JPanel 222 JPanel controlPanel = 223 new JPanel( new GridLayout( 2, 2 ) ); 224 225 controlPanel.add( inputPanel ); 226 controlPanel.add( buttonPanel ); 227 228 contentPane.add( controlPanel, BorderLayout.NORTH ); 229 230 } // end method createGUI 231 232 // get WindowListener for exiting application 233 private WindowListener getWindowListener() 234 { 235 return new WindowAdapter() { 236 237 public void windowClosing( WindowEvent event ) 238 { 239 // remove MathTool instance 240 try { 241 mathTool.remove(); 242 } 243 244 // handle exception when removing MathTool EJB 245 catch ( RemoveException removeException ) { 246 removeException.printStackTrace(); 247 System.exit( -1 ); 248 } 249 250 // handle exception when removing MathTool EJB 251 catch ( RemoteException remoteException ) { 252 remoteException.printStackTrace(); 253 System.exit( -1 ); 254 } 255 256 System.exit( 0 ); 257 } // end method windowClosing 258 }; 259 } // end method getWindowListener 260 261 // execute application 262 public static void main( String[] args ) 263 { Fig. 14.24 Fig. 14.24Fig. 14.24 Fig. 14.24 MathToolClient for interacting with MathTool EJB (part 5 of 6). Chapter 14 Session EJBs and Distributed Transactions 879 14.4 EJB Transactions The Java 2 Enterprise Edition supports distributed transactions. A distributed transaction is a transaction that includes multiple databases or multiple application servers. For exam- ple, a distributed transaction could transfer funds from an account at one bank into an ac- count at another bank atomically. J2EE supports two methods for defining transaction boundaries: bean-managed trans- action demarcation and container-managed transaction demarcation. Bean-managed transaction demarcation requires the EJB developer to code the transaction boundaries manually in the EJBs using the Java Transaction API (JTA). Container-managed transac- tion demarcation allows the EJB deployer to specify transaction boundaries declaratively when deploying EJBs. Software Engineering Observation 14.2 Entity EJBs may use only container-managed transaction demarcation. 14.2 14.4.1 MoneyTransfer EJB Home and Remote Interfaces The MoneyTransfer EJB demonstrates the need for distributed transactions and their implementation using bean-managed and container-managed transaction demarcation. In this example, we transfer money from an account at BankABC to an account at BankXYZ. We first withdraw money from an account at BankABC and then deposit the same amount at BankXYZ. Transactions are needed to ensure that the money is “put back” in the Bank- 264 MathToolClient client = new MathToolClient(); 265 } 266 } Fig. 14.24 Fig. 14.24Fig. 14.24 Fig. 14.24 MathToolClient for interacting with MathTool EJB (part 6 of 6). 880 Session EJBs and Distributed Transactions Chapter 14 ABC account if the deposit at BankXYZ fails. We also need to ensure that if the withdrawal from BankABC fails, the money is not deposited at BankXYZ. The MoneyTransfer remote interface (Fig. 14.25) provides methods for transfer- ring money between accounts and for getting the balances of accounts at two different banks. Method transfer (line 15) transfers the given amount of money from an account at BankABC to an account at BankXYZ. Method getBankABCBalance (line 18) returns the account balance at BankABC. Method getBankXYZBalance (line 21) returns the account balance at BankXYZ. Interface MoneyTransferHome (Fig. 14.26) provides method create (lines 15–16) for creating MoneyTransfer EJB instances. 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 14 // transfer amount from BankABC to BankXYZ 15 public void transfer( double amount ) throws RemoteException; 16 17 // get BankABC account balance 18 public double getBankABCBalance() throws RemoteException; 19 20 // get BankXYZ account balance 21 public double getBankXYZBalance() throws RemoteException; 22 } Fig. 14.25 Fig. 14.25Fig. 14.25 Fig. 14.25 MoneyTransfer remote interface for transferring money and getting account balances. 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 Fig. 14.26 Fig. 14.26Fig. 14.26 Fig. 14.26 MoneyTransferHome interface for creating MoneyTransfer EJBs (part 1 of 2). Chapter 14 Session EJBs and Distributed Transactions 881 14.4.2 Bean-Managed Transaction Demarcation Bean-managed transaction demarcation requires the EJB developer to code the transaction boundaries manually in the EJBs. Bean-managed transaction demarcation may be used only with session EJBs. MoneyTransferEJB (Fig. 14.27) implements the MoneyTransfer remote inter- face using bean-managed transaction demarcation to ensure atomicity of the database updates in method transfer (lines 26–81). Lines 29–30 create a UserTransaction. Line 34 begins the transaction by invoking UserTransaction method begin. All statements after the transaction begins are part of the transaction until the transaction is committed or rolled back. 14 // create MoneyTransfer EJB 15 public MoneyTransfer create() throws RemoteException, 16 CreateException; 17 } 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 19 private SessionContext sessionContext; 20 private Connection bankOneConnection; 21 private Connection bankTwoConnection; 22 private PreparedStatement withdrawalStatement; 23 private PreparedStatement depositStatement; 24 25 // transfer funds from BankABC to BankXYZ 26 public void transfer( double amount ) throws EJBException 27 { 28 // create transaction for transferring funds 29 UserTransaction transaction = 30 sessionContext.getUserTransaction(); Fig. 14.27 Fig. 14.27Fig. 14.27 Fig. 14.27 MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation (part 1 of 6). Fig. 14.26 Fig. 14.26Fig. 14.26 Fig. 14.26 MoneyTransferHome interface for creating MoneyTransfer EJBs (part 2 of 2). 882 Session EJBs and Distributed Transactions Chapter 14 31 32 // begin bean-managed transaction demarcation 33 try { 34 transaction.begin(); 35 } 36 37 // catch exception if method begin fails 38 catch ( Exception exception ) { 39 40 // throw EJBException indicating transaction failed 41 throw new EJBException( exception ); 42 } 43 44 // transfer funds from account in BankABC to account 45 // in BankXYZ using bean-managed transaction demarcation 46 try { 47 48 withdrawalStatement.setDouble( 1, amount ); 49 50 // withdraw funds from account at BankABC 51 withdrawalStatement.executeUpdate(); 52 53 depositStatement.setDouble( 1, amount ); 54 55 // deposit funds in account at BankXYZ 56 depositStatement.executeUpdate(); 57 58 // commit transaction 59 transaction.commit(); 60 61 } // end try 62 63 // handle exceptions when withdrawing, depositing and 64 // committing transaction 65 catch ( Exception exception ) { 66 67 // attempt rollback of transaction 68 try { 69 transaction.rollback(); 70 } 71 72 // handle exception when rolling back transaction 73 catch ( SystemException systemException ) { 74 throw new EJBException( systemException ); 75 } 76 77 // throw EJBException indicating transaction failed 78 throw new EJBException( exception ); 79 } 80 81 } // end method transfer 82 Fig. 14.27 Fig. 14.27Fig. 14.27 Fig. 14.27 MoneyTransferEJB implementation of MoneyTransfer remote interface using bean-managed transaction demarcation (part 2 of 6). [...]... MoneyTransfer remote interface using bean-managed transaction demarcation (part 4 of 6) Chapter 14 1 86 187 188 189 190 191 1 92 193 194 195 1 96 197 198 199 20 0 20 1 20 2 20 3 20 4 20 5 20 6 20 7 20 8 20 9 21 0 21 1 21 2 21 3 21 4 21 5 21 6 21 7 21 8 21 9 22 0 22 1 22 2 22 3 22 4 22 5 22 6 22 7 22 8 22 9 23 0 23 1 23 2 23 3 23 4 23 5 23 6 23 7 Fig 14 .27 Session EJBs and Distributed Transactions 885 // close database Connections bankOneConnection.close();... bankABCBalanceTextField ); MoneyTransferEJBClient for interacting with MoneyTransfer EJB (part 4 of 6) 8 96 Session EJBs and Distributed Transactions 168 169 170 171 1 72 173 174 175 1 76 177 178 179 180 181 1 82 183 184 185 1 86 187 188 189 190 191 1 92 193 194 195 1 96 197 198 199 20 0 20 1 20 2 20 3 20 4 20 5 20 6 20 7 20 8 20 9 21 0 21 1 21 2 21 3 21 4 21 5 21 6 21 7 } Fig 14.30 Chapter 14 contentPane.add( new JLabel( "Bank XYZ Balance: " )... standard extensions import javax.swing.*; Fig 14.30 MoneyTransferEJBClient for interacting with MoneyTransfer EJB (part 1 of 6) Chapter 14 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 Session EJBs and Distributed Transactions 893 import javax.ejb.*; import javax.rmi.*; import javax.naming.*; // Deitel... balance = " + "balance - ? WHERE accountID = 123 45"; withdrawalStatement = bankOneConnection.prepareStatement( withdrawal ); MoneyTransferEJB implementation of MoneyTransfer remote interface using container-managed transaction demarcation (part 4 of 5) Chapter 14 20 0 20 1 20 2 20 3 20 4 20 5 20 6 20 7 20 8 20 9 21 0 21 1 21 2 21 3 21 4 21 5 21 6 21 7 21 8 21 9 22 0 22 1 } Fig 14 .28 Session EJBs and Distributed Transactions... ActionEvent event ) { MoneyTransferEJBClient for interacting with MoneyTransfer EJB (part 3 of 6) Chapter 14 117 118 119 120 121 122 123 124 125 1 26 127 128 129 130 131 1 32 133 134 135 1 36 137 138 139 140 141 1 42 143 144 145 1 46 147 148 149 150 151 1 52 153 154 155 1 56 157 158 159 160 161 1 62 163 164 165 166 167 Fig 14.30 Session EJBs and Distributed Transactions 895 try { // get transfer amount from... 14 .29 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // MoneyTransferEJB .java // MoneyTransferEJB is a stateless session EJB for transferring // funds from an Account at BankABC to an Account at BankXYZ // using container-managed transaction demarcation package com.deitel.advjhtp1.ejb.transactions.containermanaged; // Java. .. remote interface using container-managed transaction demarcation (part 1 of 5) 888 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 Fig 14 .28 Session EJBs and Distributed Transactions Chapter 14 // throw EJBException to indicate transfer failed // and roll back container-managed transaction throw... implementation of MoneyTransfer remote interface using bean-managed transaction demarcation (part 3 of 6) 884 135 1 36 137 138 139 140 141 1 42 143 144 145 1 46 147 148 149 150 151 1 52 153 154 155 1 56 157 158 159 160 161 1 62 163 164 165 166 167 168 169 170 171 1 72 173 174 175 1 76 177 178 179 180 181 1 82 183 184 185 Fig 14 .27 Session EJBs and Distributed Transactions Chapter 14 // handle exception when getting Account... bean-managed transaction demarcation (part 5 of 6) 8 86 23 8 23 9 24 0 24 1 24 2 24 3 24 4 24 5 24 6 24 7 24 8 24 9 25 0 25 1 } Fig 14 .27 Session EJBs and Distributed Transactions Chapter 14 } // end try // handle exception if DataSource not found in directory catch ( NamingException namingException ) { throw new EJBException( namingException ); } // handle exception getting Connection to DataSource catch ( SQLException sqlException... MoneyTransfer remote interface using container-managed transaction demarcation (part 3 of 5) 890 149 150 151 1 52 153 154 155 1 56 157 158 159 160 161 1 62 163 164 165 166 167 168 169 170 171 1 72 173 174 175 1 76 177 178 179 180 181 1 82 183 184 185 1 86 187 188 189 190 191 1 92 193 194 195 1 96 197 198 199 Fig 14 .28 Session EJBs and Distributed Transactions Chapter 14 // close PreparedStatements depositStatement.close(); . factorialButton ); 21 9 buttonPanel.add( fibonacciButton ); 22 0 22 1 // add inputPanel and buttonPanel to new JPanel 22 2 JPanel controlPanel = 22 3 new JPanel( new GridLayout( 2, 2 ) ); 22 4 22 5 controlPanel.add(. in the Bank- 26 4 MathToolClient client = new MathToolClient(); 26 5 } 26 6 } Fig. 14 .24 Fig. 14 .24 Fig. 14 .24 Fig. 14 .24 MathToolClient for interacting with MathTool EJB (part 6 of 6) . 880 Session. ); 22 6 controlPanel.add( buttonPanel ); 22 7 22 8 contentPane.add( controlPanel, BorderLayout.NORTH ); 22 9 23 0 } // end method createGUI 23 1 23 2 // get WindowListener for exiting application 23 3

Ngày đăng: 09/08/2014, 12:23

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan