You are on page 1of 20

Entity Bean

View Edit

Aim: Write a program to develop a Enterprise Java Bean of "Entity Session Bean" type. Procedure The following procedure demonstrates the container-managed persistence feature of entity beans. It is a very simple application in which the user can create, find, update, and delete stocks. This application uses two enterprise beans:

An entity bean named Stock that holds information about stocks. There is one instance of this entity bean per stock. A session bean named StockList that uses the Stock beans and provides business methods to the UI that enables it to maintain the Stock beans.

Steps for Execution 1. 2. Create a folder called cmp and in that create two sub-directories called beans and client. Write the coding for the following files and save it in the beans sub folder

The source files used to define the Stock entity bean Stock.java StockBean.java StockHome.java The source files that define the StockList session bean StockList.java StockListBean.java StockListHome.java 3. The source file that defines the user interface client called StockClient.java is placed in the client subfolder: 4. a. b. c. d. e. Compile the java file to get the class files. Open the command prompt. Move to the cmp directory. Set PATH=.;C:\Sun\AppServer\jdk\bin Set classpath=.;C:\Sun\AppServer\lib\j2ee.jar Compile the java files as

javac -d . beans\*.java javac -d . client\*.java Creating the J2EE Application 1. Start the J2EE server as Start - > All Program - > Sun Micro Systems - >Application Server PE - >Start Default Server

2. Start the deploy tool utility as Start - >All Program - > Sun Micro Systems - > Application Server PE > Deploy Tool 3. A new application deployment tool screen will be displayed.

4. The first thing that we need the Deployment Tool to do is create the J2EE application, which will be bundled together in an Enterprise Application Resource (EAR) file. 5. To create the application EAR file, from the File menu choose New - >Application. A dialog box will be displayed, prompting you to enter the name of the EAR file, and the application name that you want displayed. Click Browse and select the cmp folder and give the New Application name as StockListApp 6. Click New Application and in the next window that appears Click OK to accept the changes to this dialog. 7. Now well create the JAR file in which the session bean classes and resources will be packaged. To do this, choose File -> New -> Enterprise Bean menu item. A New Enterprise Bean Wizard appears. Click Next 8. A screen showing a new enterprise bean wizard will be displayed. From the combo box of Create New Jar Module in Application, select StockListApp. In the JAR display name, enter StockAppJar. Then click the Edit Contents button. 9. In the Available Files panel of the dialog box shown below, navigate to the beans directory of StockListApp example. Choose the StockList.class, StockListBean.class and the StockListHome.class, and click the Add button. Those bean classes will appear in the Contents of <EJB Bundle> panel as seen below: 10. 11. a. b. c. d. e. Click OK in the dialog box and then click the Next button In the page that is displayed you will then have four drop-down lists in which to make choices: From the Enterprise Bean Class drop-down list, choose beans.StockListBean. Type StockListEjb in the Enterprise Bean box. From the Enterprise Bean Type dropdown list choose Stateless Session. From the Remote Home Interface drop-down list, choose beans. StockListHome. From the Remote Interface drop-down list, choose beans. StockList.

12. Click Next and the resulting dialog asks if you want the bean to be exposed as a web service; Select No and click Next. The last page of the Enterprise Bean Wizard suggests some steps to do next. Click the Finish button to leave the wizard: 13. Now create another bean JAR, for the Stock entity bean. Select File - > New - > Enterprise Bean. The introduction screen appears click Next. The following window appears. Perform the following steps: a. Choose the Add to Existing JAR Module option if it isnt already selected. This is because were going to put our entity bean in the same bean JAR file as the session bean. b. Verify that the application shown in the drop-down is StockListApp.

c. Then click the Edit Contents button to select only the three Stock entity bean .class files (Stock.class, StockBean.class, and StockHome.class) to be put into this JAR. 14. a. b. c. d. e. Click the Next button. Do the following in the window that appears Select the Enterprise Bean Class as beans.StockBean Set the Enterprise Bean Name as StockEjb Select the Enterprise Bean Type as Entity Select the Remote Home Interfaces as beans.StockHome Select the Remote Interface as beans.

15. 16. a. b.

Click Next on the Configuration Options page. The next page in this wizard is the Entity Settings page: Do the following Select Container-Managed Persistence 2.0, from the Persistence Management drop-down. Mark both fields in fields to be persisted

c. Were going to use the tickerSymbol field as the primary key for the Stock bean. So select tickersymbo[java.lang.String] in the Primary Key specification by selecting the option Select an Existing Field. d. 17. Set Stock as the abstract persistence schema. Click Next and click Finish

18. In the first window select StockEjb in the left-hand panel, and the Transactions tab on the right. The Transaction Management page should appear: In that Container-Managed should be selected, and then select Remote, and then Remote Home, verifying that the Transaction Attribute of each method is set to Required. 19. Now select StockListApp in the left-hand panel, and then then select Sun-Specific Settings in the righthand panel and the window appears set the following In the JNDI Name tab: a. Give the Stock entity bean the JNDI Name ejb/beans.Stock.

b. Give the StockList session bean the JNDI Name ejb/beans.StockList. 20. Select the File - > Save All menu option.

21. Select StockListJar in the left-hand panel, and click the Sun-specific Settings button at the bottom of the page. The Sun-specific Settings page shown on the next page will appear, and in it well take care of some database-related issues: a. Well be using the Derby the default database, so enter jdbc/_default as the Database JNDI Name in the CMP Resource panel. b. 22. a. b. Click the Create Database Mappings button. In the Create Dialog Mappings dialog, make sure that: The Automatically Generate Necessary Tables option is selected. Derby is selected in the Datasource Vendor drop-down list.

23. The Sun-specfic Settings dialog will reappear with the database table and field names that will be used to persist the data in the Stock entity bean. Click the Close button. 24. Save the application by choosing the File -> Save All menu item. Select the StockListApp node from the tree on the left panel and choose Verify J2EE Compliance from the Tools menu. Choose the Failures Only option and click OK. Creating & Packaging the Application Client Application Client.New 1. In the Application Deployment Tool screen, go to File

2. Click Next in the Introduction wizard that appears. The New Application Client wizard screen will be displayed as shown below: Give the Jar Display name as StockListClient. And click Edit Contents button 3. A screen saying Edit contents of StockListClient will be displayed. In that select the StockClient.class in the client folder and click Add and then click Next in the wizard that appears. 4. In the window that appears Select the Main class as Client.StockClient. Click Next and then click finish to return to the main window. Specifying the Application Client's Enterprise Bean Reference

1. 2. a. b. c. d. e. f. g. 3. 4. a. b. c. d. e. f. g.

Select the StockListClient in the Left panel and select the EJB Refs tab. In that click Add In the Add Enterprise Bean Reference wizard provide the following values. Give the Coded Name as StockListEjb Select the EJB type as Session. Select the Interfaces as Remote Select the Home Interface as beans. StockListHome Select the Remote Interface as beans. StockList. In the Target EJB , select the JNDI Name option and select ejb/beans.StockList Click Ok. Again in the EJB Refs tab Click add . In the Add Enterprise Bean Reference wizard provide the following values. Give the Coded Name as StockEjb Select the EJB type as entity. Select the Interfaces as Remote Select the Home Interface as beans. StockHome Select the Remote Interface as beans. Stock. In the Target EJB , select the JNDI Name option and select ejb/beans.Stock Click Ok.

Deploying the J2EE Application 1. 2. 3. 4. a. b. 5. 6. 7. Select the StockListApp application. Select Tools -> Deploy. Under Connection Settings, enter the user name and password for the Application Server. Tell deploytool to create a JAR file that contains the client stubs. Select the Return Client JAR checkbox. In the field below the checkbox, enter C:\cmp Click OK. In the Distribute Module dialog box, click Close when the deployment completes. Verify that a stub client JAR named StockListAppClient.jar resides in C:\cmp.

Running the Application Client 1. 2. 3. 4. In the command prompt go to the directory C:\cmp set APPCPATH= c:\cmp\StockListAppClient.jar set path=c:\Sun\AppServer\bin Run the client as

C:\cmp>appclient -client StockListApp.ear

5.

The user interface window appears which allows you to add, delete, update the stock

Program: Stock.java
1. 2. 3. 4. 5. 6. package beans; import java.rmi.*; import javax.ejb.*; public interface Stock extends EJBObject { /* The public business methods on the Stock bean these include the accessor methods from the bean get the ticker. Do not allow ticker to be set through the interface because it is the primary key */ 7. public String getTickerSymbol() throws RemoteException; 8. // get and set the name 9. public String getName() throws RemoteException; 10. public void setName(String name) throws RemoteException; 11. }

StockBean.java
1. package beans; 2. import javax.ejb.*; 3. public abstract class StockBean implements EntityBean 4. { 5. // keeps the reference to the context 6. EntityContext _context; 7. // the abstract access methods for persistent fields 8. public abstract String getTickerSymbol(); 9. public abstract void setTickerSymbol(String ticker); 10. public abstract String getName(); 11. public abstract void setName(String name); 12. // standard entity bean methods 13. public String ejbCreate(String ticker, String name)throws CreateException 14. { 15. setTickerSymbol(ticker); 16. setName(name); 17. return null; 18. } 19. public void ejbPostCreate(String ticker, String name)throws CreateException { } 20. public void setEntityContext(EntityContext ctx) 21. { 22. _context = ctx; 23. } 24. public void unsetEntityContext() 25. { 26. _context = null; 27. } 28. public void ejbRemove() { } 29. public void ejbLoad() { } 30. public void ejbStore() { } 31. public void ejbPassivate() { } 32. public void ejbActivate() { } 33. }

StockHome.java
1. 2. 3. 4. 5. 6. 7. package beans; import java.rmi.*; import javax.ejb.*; public interface StockHome extends EJBHome { // the create method for the Stock bean public Stock create(String ticker, String name)throws CreateException, RemoteException; 8. // the find by primary key method for the Stock bean 9. public Stock findByPrimaryKey(String ticker)throws FinderException, RemoteException; 10. }

StockList.java
1. 2. 3. 4. package beans; import java.rmi.*; import javax.ejb.*; public interface StockList extends EJBObject

5. { 6. // the public business methods on the Stock List bean 7. public String getStock(String ticker)throws FinderException, RemoteException; 8. public void addStock(String ticker, String name)throws CreateException, RemoteException; 9. public void updateStock(String ticker, String name)throws FinderException, RemoteException; 10. public void deleteStock(String ticker)throws FinderException, RemoteException; 11. }

StockListBean.java
1. 2. 3. 4. 5. 6. 7. package beans; import javax.ejb.*; import javax.naming.*; import javax.rmi.*; public class StockListBean implements SessionBean { /* the public business methods. these must be coded in the remote interface also */ 8. public String getStock(String ticker) throws FinderException 9. { 10. try 11. { 12. StockHome stockHome = getStockHome(); 13. Stock stock = stockHome.findByPrimaryKey(ticker); 14. return stock.getName(); 15. } 16. catch (FinderException fe) 17. { 18. throw fe; 19. } 20. catch (Exception ex) 21. { 22. throw new RuntimeException(ex.getMessage()); 23. } 24. } 25. public void addStock(String ticker, String name)throws CreateException 26. { 27. try 28. { 29. StockHome stockHome = getStockHome(); 30. stockHome.create(ticker, name); 31. } 32. catch (CreateException ce) 33. { 34. throw ce; 35. } 36. catch (Exception ex) 37. { 38. throw new RuntimeException(ex.getMessage()); 39. } 40. } 41. public void updateStock(String ticker, String name)throws FinderException 42. { 43. try 44. { 45. StockHome stockHome = getStockHome(); 46. Stock stock = stockHome.findByPrimaryKey(ticker); 47. stock.setName(name); 48. } 49. catch (FinderException fe) 50. { 51. throw fe; 52. } 53. catch (Exception ex) 54. { 55. throw new RuntimeException(ex.getMessage()); 56. } 57. } 58. public void deleteStock(String ticker)throws FinderException 59. { 60. try 61. { 62. StockHome stockHome = getStockHome(); 63. Stock stock = stockHome.findByPrimaryKey(ticker); 64. stock.remove(); 65. } 66. catch (FinderException fe) 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. }

throw fe; } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } private StockHome getStockHome() throws NamingException { // get the initial context InitialContext initial = new InitialContext(); // get the object reference Object objref = initial.lookup("ejb/beans.Stock"); StockHome home = (StockHome) PortableRemoteObject.narrow(objref, StockHome.class); return home; } // standard ejb methods public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void ejbCreate() {} public void setSessionContext(SessionContext context) { }

StockListHome.java
1. 2. 3. 4. 5. 6. 7. 8. package beans; import java.rmi.*; import javax.ejb.*; public interface StockListHome extends EJBHome { // the create method for the Stock List bean. public StockList create()throws CreateException,RemoteException; }

StockClient.java
1. package client; 2. import beans.*; 3. import javax.ejb.*; 4. import javax.naming.*; 5. import javax.rmi.*; 6. // general imports 7. import java.awt.*; 8. import java.awt.event.*; 9. import javax.swing.*; 10. public class StockClient extends JFrame implements ActionListener 11. { 12. private StockList _stockList; 13. private JTextField _ticker = new JTextField(); 14. private JTextField _name = new JTextField(); 15. private JButton _get = new JButton("Get"); 16. private JButton _add = new JButton("Add"); 17. private JButton _update = new JButton("Update"); 18. private JButton _delete = new JButton("Delete"); 19. public StockClient() 20. { 21. // get the stock lister 22. _stockList = getStockList(); 23. // add the title 24. JLabel title = new JLabel("Stock List"); 25. title.setHorizontalAlignment(JLabel.CENTER); 26. getContentPane().add(title, BorderLayout.NORTH); 27. // add the stock label panel 28. JPanel stockLabelPanel = new JPanel(new GridLayout(2, 1)); 29. stockLabelPanel.add(new JLabel("Symbol")); 30. stockLabelPanel.add(new JLabel("Name")); 31. getContentPane().add(stockLabelPanel, BorderLayout.WEST); 32. // add the stock field panel 33. JPanel stockFieldPanel = new JPanel(new GridLayout(2, 1)); 34. stockFieldPanel.add(_ticker); 35. stockFieldPanel.add(_name); 36. getContentPane().add(stockFieldPanel, BorderLayout.CENTER); 37. // add the buttons 38. JPanel buttonPanel = new JPanel(new GridLayout(1, 4)); 39. _get.addActionListener(this); 40. buttonPanel.add(_get); 41. _add.addActionListener(this); 42. buttonPanel.add(_add); 43. _update.addActionListener(this);

44. buttonPanel.add(_update); 45. _delete.addActionListener(this); 46. buttonPanel.add(_delete); 47. getContentPane().add(buttonPanel, BorderLayout.SOUTH); 48. addWindowListener(new WindowAdapter() 49. { 50. public void windowClosing(WindowEvent e) 51. { System.exit(0);} 52. }); 53. setSize(330, 130); 54. setVisible(true); 55. } 56. private StockList getStockList() 57. { 58. StockList stockList = null; 59. try 60. { 61. // Get a naming context 62. InitialContext jndiContext = new InitialContext(); 63. // Get a reference to the StockList JNDI entry 64. Object ref = jndiContext.lookup("ejb/beans.StockList"); 65. // Get a reference from this to the Bean's Home interface 66. StockListHome home = (StockListHome) 67. PortableRemoteObject.narrow(ref, StockListHome.class); 68. // Create a StockList object from the Home interface 69. stockList = home.create(); 70. } 71. catch(Exception e) 72. { 73. e.printStackTrace(); 74. } 75. return stockList; 76. } 77. public void actionPerformed(ActionEvent ae) 78. { 79. // if get was clicked, get the stock 80. if (ae.getSource() == _get) 81. { 82. getStock(); 83. } 84. // if add was clicked, add the stock 85. if (ae.getSource() == _add) 86. { 87. addStock(); 88. } 89. // if update was clicked, update the stock 90. if (ae.getSource() == _update) 91. { 92. updateStock(); 93. } 94. // if delete was clicked, delete the stock 95. if (ae.getSource() == _delete) 96. { 97. deleteStock(); 98. } 99. } 100. private void getStock() 101. { 102. // get the ticker 103. String ticker = _ticker.getText(); 104. if (ticker == null || ticker.length() == 0) 105. { 106. JOptionPane.showMessageDialog(this, "Ticker is required"); 107. return; 108. } 109. // get the stock 110. try 111. { 112. String name = _stockList.getStock(ticker); 113. _name.setText(name); 114. } 115. catch (FinderException fe) 116. { 117. JOptionPane.showMessageDialog(this, "Not found!"); 118. } 119. catch (Exception e) 120. { 121. e.printStackTrace(); 122. } 123. } 124. private void addStock() 125. {

126. 127. 128. 129. 130. required"); 131. 132. 133. 134. 135. 136. 137. 138. 139. 140. 141. 142. 143. 144. 145. 146. 147. 148. 149. 150. 151. 152. 153. 154. } 155. private 156. { 157. 158. 159. 160. 161. required"); 162. 163. 164. 165. 166. 167. 168. 169. 170. 171. 172. 173. 174. 175. 176. 177. 178. 179. 180. 181. 182. 183. 184. } 185. private 186. { 187. 188. 189. 190. 191. required"); 192. 193. 194. 195. 196. 197. 198. 199. 200. 201. 202. 203. 204. 205.

// get the ticker String ticker = _ticker.getText(); if (ticker == null || ticker.length() == 0) { JOptionPane.showMessageDialog(this, "Ticker is return; } // get the name String name = _name.getText(); if (name == null || name.length() == 0) { JOptionPane.showMessageDialog(this, "Name is required"); return; } // add the stock try { _stockList.addStock(ticker, name); JOptionPane.showMessageDialog(this, "Stock added!"); } catch (CreateException fe) { JOptionPane.showMessageDialog(this, "Already found!"); } catch (Exception e) { e.printStackTrace(); } void updateStock() // get the ticker String ticker = _ticker.getText(); if (ticker == null || ticker.length() == 0) { JOptionPane.showMessageDialog(this, "Ticker is return; } // get the name String name = _name.getText(); if (name == null || name.length() == 0) { JOptionPane.showMessageDialog(this, "Name is required"); return; } //update the stock try { _stockList.updateStock(ticker, name); JOptionPane.showMessageDialog(this, "Stock updated!"); } catch (FinderException fe) { JOptionPane.showMessageDialog(this, "Not found!"); } catch (Exception e) { e.printStackTrace(); void deleteStock() // get the ticker String ticker = _ticker.getText(); if (ticker == null || ticker.length() == 0) { JOptionPane.showMessageDialog(this, "Ticker is return; } // delete the stock try { _stockList.deleteStock(ticker); JOptionPane.showMessageDialog(this, "Stock deleted!"); } catch (FinderException fe) { JOptionPane.showMessageDialog(this, "Not found!"); } catch (Exception e) { e.printStackTrace(); } }

206. 207. 208. 209. 210. 211. }

} public static void main(String[] args) { StockClient stockClient = new StockClient(); }

Output:

Message Driven Bean


View Edit

Aim: Write a program to develop a Enterprise Java Bean of "Message Driven Bean" type Procedure: Steps for Execution 1. 2. Create a folder called mdb and in that create two sub-directories called msg and client. Write the coding for the SimpleMessageBean.java and save it in the msg sub folder

3. The source file that defines the user interface client called SimpleMessageClient.java is placed in the client subfolder: 4. a. b. c. d. e. Compile the java file to get the class files. Open the command prompt. Move to the mdb directory. Set PATH=.;C:\Sun\AppServer\jdk\bin Set classpath=.;C:\Sun\AppServer\lib\j2ee.jar Compile the java files as

javac -d . msg\*.java javac -d . client\*.java Creating the Administered Objects 1. Start the Admin Console, as Start - > All Programs -> Sun Micro Systems - > Application Server PE - > Admin Console 2. Enter the User name and Password in the Login page.

3. a) b) c) d) e) f) g) h) 4. a) b)

To create the connection factory, perform the following steps: In the tree component, expand the Resources node Then expand the JMS Resources node. Select the Connection Factories node. On the JMS Connection Factories page, click New. The Create JMS Connection Factory page appears. In the JNDI Name field, type jms/MyMDBQcf Choose javax.jms.QueueConnectionFactory from the Type combo box. Select the Enabled checkbox. Click OK. To create the destination resource and link it to the physical destination, perform the following steps: In the tree component, expand the Resources node, then expand the JMS Resources node. Select the Destination Resources node.

c) On the JMS Destination Resources page, click New. The Create JMS Destination Resource page appears. d) e) f) g) h) In the JNDI Name field, type jms/MyQueue. Choose javax.jms.Queue from the Type combo box. Select the Enabled checkbox. In the Additional Properties area, type PhysicalQueue in the Value field for the Name property. Click OK.

Creating the J2EE Application 1. Start the J2EE server as Start - > All Program - > Sun Micro Systems - > Application Server PE - > Start Default Server 2. Start the deploy tool utility as Start - > All Program - > Sun Micro Systems - > Application Server PE > Deploy Tool 3. A new application deployment tool screen will be displayed.

4. The first thing that we need the Deployment Tool to do is create the J2EE application, which will be bundled together in an Enterprise Application Resource (EAR) file. 5. To create the application EAR file, from the File menu choose New ->Application. A dialog box will be displayed, prompting you to enter the name of the EAR file, and the application name that you want displayed. Click Browse and select the mdb folder and give the New Application name as SimpleMessageApp 6. Click New Application and in the next window that appears click OK to accept the changes to this dialog. 7. Now well create the JAR file in which the session bean classes and resources will be packaged. To do this, choose File -> New -> Enterprise Bean menu item. A New Enterprise Bean Wizard appears. Click Next 8. A screen showing a new enterprise bean wizard will be displayed. From the combo box of Create New Jar Module in Application, select SimpleMessageApp. In the JAR display name, enter SimpleMessageJar. Then click the Edit Contents button. 9. In the Available Files panel of the dialog box shown below, navigate to the msgdirectory of SimpleMessageApp. Choose the SimpleMessageBean.class, and click the Add button. Those bean classes will appear in the Contents of <EJB Bundle> panel as seen below:

10. 11.

Click OK in the dialog box and then click the Next button In the page that is displayed make the following settings

* From the Enterprise Bean Class drop-down list, choose msg.SimpleMessageBean. * Type SimpleMessageEjb in the Enterprise Bean Name box. * From the Enterprise Bean Type dropdown list choose Message-Driven. 12. In the Message-Driven Bean Settings dialog, shown below, do the following:

* Select the JMS option from the Messaging Service drop-down list * Select javax.jms.Queue from the Destination Type drop-down list. * Type PhysicalQueue into the Target Destination Name field. * Type jms/MyMDBQcf in the Connection Factory JNDI Name field. * Dont click the Next button just yet. 13. Now select the Non-JMS option from the Messaging Service drop-down list on that page. In the Message-Driven Bean Settings page javax.jms.MessageListener is chosen in the Message Listener Interface drop-down list. This is the interface that specifies the onMessage() method: 14. Use the Add button, shown above, to add each of two Activation Configuration Properties:

* The destinationType property, which as explained previously is javax.jms.Queue * The destination property, which is PhysicalQueue * The message-driven bean will listen for messages arriving at the destination specified in these properties. 15. Now click the Sun-specific Settings button and enter jaxr into the Resource Adapter field as shown below, and click OK. ( A resource adapter is analogous to a JDBC driver, and in this case allows the JMS provider to interact with the J2EE server ) 16. Click Next and click finish in the wizard that appears.

17. After finishing the wizard, select SimpleMessageEjb in the left panel, and select the Transactions tab. Choose Container-Managed and let the Transaction Attribute default to Required. 18. Select SimpleMessageJar in the left panel and MessageDestinations Tab in the right panel and do the following: a) Click Add.

b) Type the physical destination name (for this example, PhysicalQueue) in the Destination Name field, and press Enter. c) Type the JNDI name of the destination resource (for this example, jms/ MyQueue) in the JNDI Name field 19. Do File -> Save All. Select SimpleMessageApp on the left, and select Sun-Specific Settings in the right and then assign the JNDI name as jms/MyQueue Creating & Packaging the Application Client 1. In the Application Deployment Tool screen, go to File - > New - >Application Client.

2. Click Next in the Introduction wizard that appears. The New Application Client wizard screen will be displayed as shown below: Give the Jar Display name as SimpleMessageClient. And click Edit Contents button 3. A screen saying Edit contents of SimpleMessageClient will be displayed. In that select the SimpleMessageClient.class in the client folder and click Add and then click Next in the wizard that appears.

4. In the window that appears Select the Main class as Client.SimpleMessageClient. Click Next and then click finish to return to the main window. Setting the Resource References of the client Select the SimpleMessageClient in the Left pane and use the Resource Refs tabbed pane on the right to specify the connection factory references for the component. 1. 2. Select the Resource Refs tab. Click Add.

3. In the Coded Name field, enter the name that matches the parameter of the lookup method in the component code. For our example, because the coded name should be jms/MyMDBQcf 4. In the Type field, select the connection factory class that matches the destination type. The destination class in the code is javax.jms.QueueConnectionFactory, so select that class. 5. In the Authentication field select Container.

6. In the Sharable field, make sure that the checkbox is selected. This choice allows the container to optimize connections. 7. In the Sun-specific Settings area, enter the name of the connection factory in this case, enter jms/MyMDBQcf in the JNDI Name field. 8. Enter guest in both the User Name and the Password fields.

Setting the Message Destination References For any new application, we use the Msg Dest Refs tab to specify the destination of messages. 1. 2. Select the Msg Dest Refs tab. Click Add.

3. In the Coded Name field of the dialog box that appears, type a name that matches the parameter of the lookup call that locates the queue or topic. In this example, the the coded name is jms/MyQueue 4. 5. In the Destination Type combo box, choose the class that matches the destination type (in this case, javax.jms.Queue).

6. From the Usage combo box, choose either Produces or ConsumesProduces, depending on whether this component sends messages or both sends and receives messages. For this example, choose Produces. 7. In the Destination Name field, type the name of the physical destination you created (in this case, PhysicalQueue). Setting the Message Destinations 1. 2. Select the Message Destinations tab. Click Add.

3. In the Destination Name field, type the name of the destination (in this case, PhysicalQueue) and press Return. The name also appears in the Display Name field. The names of the components that consume and produce messages for the destination appear in the Producers and Consumers areas. 4. In the JNDI Name field, type the name of the JMS resource you created (in this case, jms/MyQueue).

Deploying the J2EE Application 1. 2. 3. Select the simpleMessageApp application. Select Tools -> Deploy. Under Connection Settings, enter the user name and password for the Application Server.

4. a. b. 5. 6. 7.

Tell deploytool to create a JAR file that contains the client stubs. Select the Return Client JAR checkbox. In the field below the checkbox, enter C:\mdb Click OK. In the Distribute Module dialog box, click Close when the deployment completes. Verify that a stub client JAR named SimpleMessageAppClient.jar resides in C:\mdb

Running the Application Client 1. 2. 3. 4. In the command prompt go to the directory C:\mdb set APPCPATH=c:\mdb\SimpleMessageAppClient.jar set path=c:\Sun\AppServer\bin Run the client as

C:\mdb>appclient -client SimpleMessageApp.ear The client displays these lines: Sending message: This is message 1 Sending message: This is message 2 Sending message: This is message 3 To see if the bean received the messages, Check C:/Sun/AppServer/domains/domain1/logs/server.log. In the server log file, the following lines should be displayed, wrapped in logging information: MESSAGE BEAN: Message received: This is message 1 MESSAGE BEAN: Message received: This is message 2 MESSAGE BEAN: Message received: This is message 3 Program:

SimpleMessageClient.java
1. 2. 3. 4. 5. 6. package client; import javax.jms.*; import javax.naming.*; public class SimpleMessageClient { /* The main method of the client. The client sends three messages to the message queue and on the other hand the bean receives these messges asynchronously from the queue.*/ 7. public static void main(String[] args) 8. { 9. Context jndiContext = null; 10. QueueConnectionFactory queueConnectionFactory = null; 11. QueueConnection queueConnection = null; 12. QueueSession queueSession = null; 13. Queue queue = null; 14. QueueSender queueSender = null; 15. TextMessage message = null; 16. final int NUM_MSGS = 3; 17. try 18. { 19. jndiContext = new InitialContext(); 20. }

21. catch (NamingException e) 22. { 23. System.out.println("Could not create JNDI " + "context: " + e.toString()); 24. System.exit(1); 25. } 26. try 27. { 28. queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("java:comp/env/jms/MyMDBQcf"); 29. queue=(Queue) jndiContext.lookup ("java:comp/env/jms/MyQueue"); 30. } 31. catch (NamingException e) 32. { 33. System.out.println("JNDI lookup failed: " + e.toString()); 34. System.exit(1); 35. } 36. try 37. { 38. queueConnection = queueConnectionFactory.createQueueConnection(); 39. queueSession= queueConnection.createQueueSession (false,Session.AUTO_ACKNOWLEDGE); 40. queueSender = queueSession.createSender(queue); 41. message = queueSession.createTextMessage(); 42. for (int i = 0; i < NUM_MSGS; i++) 43. { 44. message.setText("This is message " + (i + 1)); 45. System.out.println("Sending message: "+ message.getText()); 46. queueSender.send(message); 47. } 48. } 49. catch (Throwable e) 50. { 51. System.out.println("Exception occurred: " + e.toString()); 52. } 53. finally 54. { 55. if (queueConnection != null) 56. { 57. try 58. { 59. queueConnection.close(); 60. } 61. catch (JMSException e) {} 62. } // if 63. System.exit(0); 64. } // finally 65. } // main 66. } // class

SimpleMessageBean.java
1. package msg; 2. import java.io.Serializable; 3. import java.rmi.RemoteException; 4. import javax.ejb.EJBException; 5. import javax.ejb.MessageDrivenBean; 6. import javax.ejb.MessageDrivenContext; 7. import javax.ejb.CreateException; 8. import javax.naming.*; 9. import javax.jms.*; 10. public class SimpleMessageBean implements MessageDrivenBean, MessageListener 11. { 12. private transient MessageDrivenContext mdc = null; 13. private Context context; 14. /*Default constructor. Creates a bean. Required by EJB spec. */ 15. public SimpleMessageBean() 16. { 17. System.out.println("In SimpleMessageBean.SimpleMessageBean()"); 18. } 19. /* Sets the context for the bean */ 20. public void setMessageDrivenContext(MessageDrivenContext mdc) 21. { 22. System.out.println("In " + "SimpleMessageBean.setMessageDrivenContext()"); 23. this.mdc = mdc; 24. } 25. /*Creates a bean. Required by EJB spec.*/ 26. public void ejbCreate() 27. {

28. System.out.println("In SimpleMessageBean.ejbCreate()"); 29. } 30. /* When the queue receives a message, the EJB container invokes the onMessage method of the message-driven */ 31. public void onMessage(Message inMessage) 32. { 33. TextMessage msg = null; 34. try 35. { 36. if (inMessage instanceof TextMessage) 37. { 38. msg = (TextMessage) inMessage; 39. System.out.println("MESSAGE BEAN: Message received: "+ msg.getText()); 40. } 41. else 42. { 43. System.out.println("Message of wrong type: "+ inMessage.getClass().getName()); 44. } 45. } 46. catch (JMSException e) 47. { e.printStackTrace(); } 48. catch (Throwable te) 49. { te.printStackTrace(); } 50. } // onMessage 51. /* Removes the bean. Required by EJB spec. */ 52. public void ejbRemove() 53. { 54. System.out.println("In SimpleMessageBean.remove()"); 55. } 56. } // class

Session Bean

View Edit

Aim: Write a program to develop a Enterprise Java Bean of "Session Bean" type. Procedure Steps for Execution 1.Create a folder called welcome and in that create two sub-directories called beans and client. 2.Write code for a Remote interface and save the file as Welcome.java in the beans folder. 3.Write code for a Home interface and save the file as WelcomeHome.java in the beans folder.. 4.Write code for a bean class and save the file as WelcomeBean.java in the beans folder. 5.Write the code for client and save the file as WelcomeClient.java in the client folder. 6.Compile the Remote interface, the Home interface, the bean class, and the client file. a. Open the command prompt. b. Move to the welcome directory. c. Set PATH=.;%j2ee_home%\jdk\bin d. Set classpath=.;%j2ee_home%\lib\j2ee.jar e. Compile the java files as javac -d . beans\*.java javac -d . client\*.java

Creating the J2EE Application Start Default ServerApplication Server PE Sun Micro Systems All Program 1.Start the J2EE server as Start Deploy ToolApplication Server PE Sun Micro Systems All Program 2.Start the deploy tool utility as Start 3.A new application deployment tool screen will be displayed. 4.The first thing that we need the Deployment Tool to do is create the J2EE application, which will be bundled together in an Enterprise Application Resource (EAR) file. 5.To create the application EAR file, from the File menu choose Application. A dialog box will be displayed, prompting you to enterNew the name of the EAR file, and the application name that you want displayed. 6.Click Browse and select the welcome folder and give the New Application name as WelcomeApp 7.Click New Application and in the next window that appears Click OK to accept the changes to this dialog. 8.Now well create the JAR file in which the session bean classes and Enterprise New resources will be packaged. To do this, choose File Bean menu item. A New Enterprise Bean Wizard appears. Click Next 9.A screen showing a new enterprise bean wizard will be displayed. From the combo box of Create New Jar Module in Application, select WelcomeApp. In the JAR display name, enter WelcomeAppJar. Then click the Edit Contents button. 10.In the Available Files panel of the dialog box shown below, navigate to the beans directory of WelcomeApp example. Choose the Welcome.class, WelcomeBean.class and the WelcomeHome.class, and click the Add button. Those bean classes will appear in the Contents of <EJB Bundle> panel as seen below: 11.Click OK in the dialog box and then click the Next button to see the page shown below. You will then have four drop-down lists in which to make choices: From the Enterprise Bean Class drop-down list, choose beans.WelcomeBean.8 Type WelocmeJNDI in the Enterprise Bean box.8 From the Enterprise Bean Type dropdown list choose Stateless Session.8 From the Remote Home Interface drop-down list, choose beans.WelcomeHome.8 From the Remote Interface drop-down list, choose beans.Welcome.8 12.Click Next and the resulting dialog asks if you want the bean to be exposed as a web service; Select No and click Next. The last page of the Enterprise Bean Wizard suggests some steps to do next. Click the Finish button to leave the wizard: 13.The Deploy tool will appear as shown below 14.Select WelcomeApp in the tree of the left hand panel and Select Sun-specific Settings button in the right panel the Sun specific settings window appears. In that select JNDI name in the view combo-box and Type WelcomeJNDI field of the JNDI names table (This is the name the client application uses in the lookup() method to obtain the beans home reference.).Then click Close Save All .15.Select File 16.Select the WelcomeApp node from the tree on the left panel and choose Verify J2EE Compliance from the Tools menu. You may be prompted to save the application. To run the verification tests against the application, choose one of the Display options and click the OK button. We usually choose Failures only option as shown below so that only the failed tests show up. The Results and the Details panels show the results of the tests and details of any problems encountered, respectively. If there are any problems encountered, then read the Details and go to the Deployment Tool page in which that detail is configured and verify whether all the fields are specified properly as detailed above. Creating & Packaging the Application Client

Application Client.New 1.In the Application Deployment Tool screen, go to File 2.Click Next in the Introduction wizard that appears. The New Application Client wizard screen will be displayed as shown below: Give the Jar Display name as WelcomeClient. And click Edit Contents button 3.A screen saying Edit contents of WelcomeClient will be displayed. In that select the WelcomeClient.class in the client folder and click Add and tehn click Next in the wizard that appears. 4.In the window that appears select the Main class as Client.WelcomeClient.click Next and then click finish to return to the main window. Specifying the Application Client's Enterprise Bean Reference 1.Select the WelcomeClient in the Left panel and select the EJB Refs tab. In that click Add 2.In the Add Enterprise Bean Reference wizard provide the following values. Give the Coded Name as WelcomeJNDI8 Select the EJB type as Session.8 Select the Interfaces as Session8 Select the Home Interface as beans.WelcomeHome8 Select the Remote Interface as beans.Welcome.8 In the Target EJB , select the JNDI Name option and select WelcomeJNDI.8 Click Ok.8

Deploying the J2EE Application 1.Select the WelcomeApp application. 2.Select Tools -> Deploy. 3.Under Connection Settings, enter the user name and password for the Application Server. 4.Tell deploytool to create a JAR file that contains the client stubs. a.Select the Return Client JAR checkbox. b.In the field below the checkbox, enter C:\welcome 5.Click OK. 6.In the Distribute Module dialog box, click Close when the deployment completes. 7.Verify that a stub client JAR named WelcomeAppClient.jar resides in C:\welcome. Running the Application Client 1.In the command prompt go to the directory C:\Welcome 2.set APPCPATH=c:\welcome\WelcomeAppClient.jar 3.set path=c:\Sun\AppServer\bin 4.Run the client as C:\welcome>appclient -client WelcomeApp.ear -name WelcomeClient -textauth 5.In the terminal window, the client displays the result

Welcome to your first EJB program. Program WelcomeBean.java


1. import javax.ejb.*; 2. public class WelcomeBean implements SessionBean 3. { 4. public void ejbActivate() 5. { 6. 7. } 8. public void ejbPassivate() 9. { 10. } 11. public void ejbCreate() 12. { 13. 14. } 15. public void ejbRemove() 16. { 17. 18. } 19. public void setSessionContext(SessionContext ctx) 20. { 21. 22. } 23. public String printMessage() 24. { 25. return "Welcome to your first EJB program. "; 26. } 27. }

WelcomeHome.java
1. 2. 3. 4. 5. 6. import javax.ejb.*; import java.rmi.RemoteException; public interface WelcomeHome extends EJBHome { public Welcome create() throws CreateException, RemoteException; }

Welcome.java
1. 2. 3. 4. 5. 6. import javax.ejb.*; import java.rmi.RemoteException; public interface Welcome extends EJBObject { public String printMessage() throws RemoteException; }

WelcomeClient.java
1. import java.rmi.*; 2. import javax.naming.*; 3. public class WelcomeClient 4. { 5. public static void main(String args[]) 6. { 7. try 8. { 9. InitialContext ic=new InitialContext(); 10. WelcomeHome welhome = (WelcomeHome)ic.lookup("WelcomeJNDI"); 11. Welcome wel=welhome.create(); 12. String retval=wel.printMessage(); 13. System.out.println(retval); 14. wel.remove(); 15. } 16. catch(java.rmi.RemoteException e) 17. { 18. System.out.println("Remote Exception Occured" + e); 19. } 20. catch(javax.ejb.CreateException e) 21. { 22. System.out.println("Create Exception Occured" + e); } 23. catch(javax.ejb.RemoveException e)

24. 25. 26. 27. 28. 29. 30. 31. 32. }

System.out.println("Remove Exception Occured" + e); } catch(javax.naming.NamingException e) { System.out.println("Naming Exception occured"+e); }

Output:

You might also like