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 we’ll 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 isn’t already selected. This is because we’re 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.

16. Now select StockListApp in the left-hand panel. and then Remote Home.class in the client folder and click Add and then click Next in the wizard that appears. 21.StockClient. In the Application Deployment Tool screen. Click Next and then click finish to return to the main window. so enter jdbc/_default as the Database JNDI Name in the CMP Resource panel. A screen saying Edit contents of StockListClient will be displayed. In the first window select StockEjb in the left-hand panel. Derby is selected in the Datasource Vendor drop-down list. d. The New Application Client wizard screen will be displayed as shown below: Give the Jar Display name as StockListClient. 24. Choose the Failures Only option and click OK.Stock. Set Stock as the abstract persistence schema. We’re going to use the tickerSymbol field as the primary key for the Stock bean.0. b. In that select the StockClient.15. Select StockListJar in the left-hand panel. 23. and then then select Sun-Specific Settings in the righthand panel and the window appears set the following In the JNDI Name tab: a. 22. Click the Close button. b.String] in the Primary Key specification by selecting the option Select an Existing Field. Give the StockList session bean the JNDI Name ejb/beans. Give the Stock entity bean the JNDI Name ejb/beans. b. and click the Sun-specific Settings button at the bottom of the page. a. So select tickersymbo[java. Click Next in the Introduction wizard that appears. 20.lang. from the Persistence Management drop-down. Save the application by choosing the File -> Save All menu item. In the window that appears Select the Main class as Client. And click Edit Contents button 3. and then select Remote. 17. 19. Click the Create Database Mappings button. Click Next and click Finish 18. a. verifying that the Transaction Attribute of each method is set to Required.> Save All menu option. Creating & Packaging the Application Client Application Client.◊New ◊1. 4. go to File 2.StockList. Select the File . In the Create Dialog Mappings dialog. make sure that: The Automatically Generate Necessary Tables option is selected. Click Next on the Configuration Options page. b. 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. The Sun-specific Settings page shown on the next page will appear. and in it we’ll take care of some database-related issues: a. Mark both fields in fields to be persisted c. and the Transactions tab on the right. We’ll be using the Derby the default database. The next page in this wizard is the Entity Settings page: Do the following Select Container-Managed Persistence 2. The Transaction Management page should appear: In that Container-Managed should be selected. Select the StockListApp node from the tree on the left panel and choose Verify J2EE Compliance from the Tools menu. Specifying the Application Client's Enterprise Bean Reference .

Give the Coded Name as StockListEjb Select the EJB type as Session. Again in the EJB Ref’s tab Click add . Select the StockListClient in the Left panel and select the EJB Ref’s tab. 4. Select the StockListApp application.StockList Click Ok. d. e. 3. In the field below the checkbox.jar resides in C:\cmp. 4. f. select the JNDI Name option and select ejb/beans. g. click Close when the deployment completes. Select the Interfaces as Remote Select the Home Interface as beans.1. StockListHome Select the Remote Interface as beans. select the JNDI Name option and select ejb/beans. enter the user name and password for the Application Server. b. a. b. 3. In the Target EJB . a. Select Tools -> Deploy. e.Stock Click Ok. 7. d. c. StockHome Select the Remote Interface as beans. Running the Application Client 1. c. 4.ear . 6. Give the Coded Name as StockEjb Select the EJB type as entity. In that click Add In the Add Enterprise Bean Reference wizard provide the following values. In the command prompt go to the directory C:\cmp set APPCPATH= c:\cmp\StockListAppClient. 3. 2. g. 5. In the Target EJB . f. In the Distribute Module dialog box.jar set path=c:\Sun\AppServer\bin Run the client as C:\cmp>appclient -client StockListApp. 2. 2. Tell deploytool to create a JAR file that contains the client stubs. Verify that a stub client JAR named StockListAppClient. StockList. a. Stock. Deploying the J2EE Application 1. b. In the Add Enterprise Bean Reference wizard provide the following values. enter C:\cmp Click OK. Select the Return Client JAR checkbox. Under Connection Settings. Select the Interfaces as Remote Select the Home Interface as beans.

// the find by primary key method for the Stock bean 9. import java.java 1. } StockBean. import java. 3. 8. // get and set the name 9.5. } 28. public void ejbStore() { } 31. public interface StockHome extends EJBHome { // the create method for the Stock bean public Stock create(String ticker. 10. } StockHome. 10. package beans. import javax. public void unsetEntityContext() 25. setName(name). public String getTickerSymbol() throws RemoteException. 2. EntityContext _context. import javax. _context = ctx. 12. 6. 3. 6. 17. 9.*. update the stock Program: Stock. 3.rmi. public String ejbCreate(String ticker. public void ejbRemove() { } 29. public void ejbLoad() { } 30. delete. public abstract void setName(String name). // keeps the reference to the context 6. // the abstract access methods for persistent fields 8.*.*. 4. import javax. 7. return null.*. { 15. import java. public abstract class StockBean implements EntityBean 4. 27.ejb. 4. // standard entity bean methods 13. } StockList. RemoteException. 16. } 24. setTickerSymbol(ticker). { 5. public String getName() throws RemoteException.ejb. import javax. } 19. 4. 2. Do not allow ticker to be set through the interface because it is the primary key */ 7. package beans. String name)throws CreateException { } 20.ejb. 11. public abstract String getName(). package beans. 5.*. public void ejbActivate() { } 33. package beans. public abstract String getTickerSymbol().*. 8.rmi. 2.java 1. 5. public void setName(String name) throws RemoteException. public void setEntityContext(EntityContext ctx) 21. 23.java 1. 2.*. String name)throws CreateException. RemoteException.rmi.ejb. String name)throws CreateException 14. 10. 7. _context = null. 3. 18. public void ejbPostCreate(String ticker. public interface StockList extends EJBObject . public Stock findByPrimaryKey(String ticker)throws FinderException.java 1. 11. public abstract void setTickerSymbol(String ticker). public void ejbPassivate() { } 32. { 26. public interface Stock extends EJBObject { /* The public business methods on the Stock bean these include the accessor methods from the bean get the ticker. { 22. The user interface window appears which allows you to add.

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

17. package client. 40. 83. 23.narrow(objref. stockFieldPanel. getContentPane().add(stockFieldPanel. private JButton _add = new JButton("Add"). { 12. 42.NORTH). 41. stockLabelPanel. 29. 80. StockHome. import java. getContentPane(). 77. 71.ejb. // add the stock field panel 33. 37.addActionListener(this). 13. 10.ejb. buttonPanel.add(_get).CENTER). import javax. import javax. { 21.java 1. 5. 2.add(_add). 26.*. 31.add(_name). 2. 19. public StockClient() 20. } catch (Exception ex) { throw new RuntimeException(ex. // add the buttons 38. 73. } // standard ejb methods public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void ejbCreate() {} public void setSessionContext(SessionContext context) { } StockListHome.add(new JLabel("Name")). 39. 9.event. // add the stock label panel 28. 81.*.*. 43. 25. 87. StockHome home = (StockHome) PortableRemoteObject. 79. _stockList = getStockList(). import javax. 8. BorderLayout. 1)). 91.getMessage()).swing. import java. title. 1)). JPanel stockLabelPanel = new JPanel(new GridLayout(2. return home. 84. 88.68. import beans. 30. 14. private JButton _delete = new JButton("Delete"). 76.class). 75. 8.add(title. 86. 15. } } private StockHome getStockHome() throws NamingException { // get the initial context InitialContext initial = new InitialContext().*. private JTextField _ticker = new JTextField(). // add the title 24. 82.*. 18. stockFieldPanel. private JTextField _name = new JTextField(). 27. 70. 34. public class StockClient extends JFrame implements ActionListener 11. JPanel buttonPanel = new JPanel(new GridLayout(1. 4. } StockClient. JPanel stockFieldPanel = new JPanel(new GridLayout(2. } throw fe. import javax.awt.*. getContentPane(). BorderLayout. 85. 6. 7. import javax. 4. _add.CENTER). 36. 3. public interface StockListHome extends EJBHome { // the create method for the Stock List bean.add(new JLabel("Symbol")).*. BorderLayout. 35.rmi. private JButton _get = new JButton("Get").awt.*. 90. // get the object reference Object objref = initial.add(_ticker).addActionListener(this). 3. 5. private StockList _stockList.WEST). 69.RemoteException.java 1. package beans. _update. 32.add(stockLabelPanel. 72. _get.addActionListener(this).*.naming. import java. // get the stock lister 22.Stock"). // general imports 7. buttonPanel. 74.rmi. private JButton _update = new JButton("Update"). 6. .lookup("ejb/beans. public StockList create()throws CreateException.setHorizontalAlignment(JLabel. JLabel title = new JLabel("Stock List"). 16. 78. 4)). stockLabelPanel. 89.

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

if (name == null || name. 135. 189. 180. "Ticker is return. 138. } 185. "Stock added!"). 191. 151. 161. 152.length() == 0) { JOptionPane. 200. } catch (CreateException fe) { JOptionPane. 149.showMessageDialog(this. } // delete the stock try { _stockList. 141. JOptionPane. 139. 198.deleteStock(ticker). return.length() == 0) { JOptionPane. 129. 172. "Not found!"). 192. 188. 158. "Stock updated!"). 173. } void updateStock() // get the ticker String ticker = _ticker. 178. 142. "Not found!"). 163. 150.showMessageDialog(this.getText().printStackTrace(). if (name == null || name. if (ticker == null || ticker. 127. 153. "Already found!"). 194.length() == 0) { JOptionPane. 133. } // get the name String name = _name. 159. } //update the stock try { _stockList. if (ticker == null || ticker. required"). 182. 190. 166. 137. 203. 134. 128.showMessageDialog(this.showMessageDialog(this.showMessageDialog(this. 165. 184. 177.length() == 0) { JOptionPane. } catch (FinderException fe) { JOptionPane.showMessageDialog(this.getText().printStackTrace(). 147. "Ticker is return. "Stock deleted!"). 193. 204.printStackTrace().showMessageDialog(this. 205. private 186. "Name is required"). JOptionPane. 131. { 157. 146. 143. 179. 164. 130. { 187. required"). } catch (Exception e) { e.length() == 0) { JOptionPane. private 156. 169.updateStock(ticker. 202. 170. 140. 168. 196. 160.getText(). required").showMessageDialog(this. 197. if (ticker == null || ticker. 148. 132. name). 181. "Ticker is return. 175.showMessageDialog(this. void deleteStock() // get the ticker String ticker = _ticker.getText(). } catch (Exception e) { e. 145. 195. 167. } // add the stock try { _stockList. return. } } . 162. 183.showMessageDialog(this. } catch (FinderException fe) { JOptionPane. 136.showMessageDialog(this. name). // get the ticker String ticker = _ticker. } // get the name String name = _name. 199. 176.getText(). 174. } catch (Exception e) { e.addStock(ticker. JOptionPane. "Name is required"). 154. } 155.126. 144. 171. 201.

e. 209. as Start .. 208.> Admin Console 2. client\*. . Create a folder called mdb and in that create two sub-directories called msg and client. d.> All Programs -> Sun Micro Systems . b. 2.jar Compile the java files as javac -d . Open the command prompt.C:\Sun\AppServer\lib\j2ee. Write the coding for the SimpleMessageBean.java and save it in the msg sub folder 3. 210. msg\*. c. The source file that defines the user interface client called SimpleMessageClient.206. Set PATH=.java javac -d .> Application Server PE . a.java is placed in the client subfolder: 4.java Creating the Administered Objects 1. 207. } } public static void main(String[] args) { StockClient stockClient = new StockClient(). Enter the User name and Password in the Login page. Start the Admin Console. 211. Compile the java file to get the class files. } 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.. Move to the mdb directory.C:\Sun\AppServer\jdk\bin Set classpath=.

The first thing that we need the Deployment Tool to do is create the J2EE application. 7. A New Enterprise Bean Wizard appears. Now we’ll create the JAR file in which the session bean classes and resources will be packaged. 5. Then click the Edit Contents button.> Start Default Server 2. perform the following steps: In the tree component. A new application deployment tool screen will be displayed.> Sun Micro Systems .> Application Server PE > Deploy Tool 3. Select the Connection Factories node. In the JNDI Name field. and the application name that you want displayed. Start the deploy tool utility as Start . From the combo box of Create New Jar Module in Application. which will be bundled together in an Enterprise Application Resource (EAR) file. enter SimpleMessageJar.class. type jms/MyMDBQcf Choose javax. Select the Destination Resources node. expand the Resources node Then expand the JMS Resources node. Click New Application and in the next window that appears click OK to accept the changes to this dialog. A screen showing a new enterprise bean wizard will be displayed.> Application Server PE . click New. and click the Add button. A dialog box will be displayed. The Create JMS Destination Resource page appears. To do this. To create the application EAR file.Queue from the Type combo box. a) b) c) d) e) f) g) h) 4. Click Next 8. Select the Enabled checkbox. navigate to the msgdirectory of SimpleMessageApp. The Create JMS Connection Factory page appears.> All Program .QueueConnectionFactory from the Type combo box.3.> All Program .> Sun Micro Systems .jms. Those bean classes will appear in the Contents of <EJB Bundle> panel as seen below: . Click Browse and select the mdb folder and give the New Application name as SimpleMessageApp 6. 4. In the JAR display name. Choose javax. c) On the JMS Destination Resources page. In the Additional Properties area. expand the Resources node. choose File -> New -> Enterprise Bean menu item. Choose the SimpleMessageBean. then expand the JMS Resources node. select SimpleMessageApp. perform the following steps: In the tree component. On the JMS Connection Factories page. 9. prompting you to enter the name of the EAR file. type PhysicalQueue in the Value field for the Name property. a) b) To create the connection factory. Creating the J2EE Application 1. Click OK. To create the destination resource and link it to the physical destination. Select the Enabled checkbox. In the Available Files panel of the dialog box shown below. click New. Start the J2EE server as Start . d) e) f) g) h) In the JNDI Name field.jms. from the File menu choose New ->Application. type jms/MyQueue. Click OK.

Select SimpleMessageApp on the left. shown above. Do File -> Save All. And click Edit Contents button 3. * Type jms/MyMDBQcf in the Connection Factory JNDI Name field.MessageListener is chosen in the Message Listener Interface drop-down list. In the Message-Driven Bean Settings dialog. * Type SimpleMessageEjb in the Enterprise Bean Name box.SimpleMessageBean. Now select the Non-JMS option from the Messaging Service drop-down list on that page. Select SimpleMessageJar in the left panel and MessageDestinations Tab in the right panel and do the following: a) Click Add. In that select the SimpleMessageClient. 18. After finishing the wizard. 13. to add each of two Activation Configuration Properties: * The destinationType property. Choose Container-Managed and let the Transaction Attribute default to Required. 17. . Now click the Sun-specific Settings button and enter jaxr into the Resource Adapter field as shown below. and select the Transactions tab. * Type PhysicalQueue into the Target Destination Name field. jms/ MyQueue) in the JNDI Name field 19. which is PhysicalQueue * The message-driven bean will listen for messages arriving at the destination specified in these properties. 11. In the Application Deployment Tool screen. b) Type the physical destination name (for this example. which as explained previously is javax. and in this case allows the JMS provider to interact with the J2EE server ) 16. choose msg.jms. select SimpleMessageEjb in the left panel. Click Next and click finish in the wizard that appears. go to File . do the following: * Select the JMS option from the Messaging Service drop-down list * Select javax. PhysicalQueue) in the Destination Name field.jms. 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.jms. A screen saying Edit contents of SimpleMessageClient will be displayed. and click OK. c) Type the JNDI name of the destination resource (for this example. * Don’t click the Next button just yet. shown below. In the Message-Driven Bean Settings page javax.> New . Click Next in the Introduction wizard that appears. This is the interface that specifies the onMessage() method: 14.10. * From the Enterprise Bean Type dropdown list choose Message-Driven.class in the client folder and click Add and then click Next in the wizard that appears.>Application Client.Queue * The destination property. and press Enter. and select Sun-Specific Settings in the right and then assign the JNDI name as jms/MyQueue Creating & Packaging the Application Client 1. 12. 15. The New Application Client wizard screen will be displayed as shown below: Give the Jar Display name as SimpleMessageClient.Queue from the Destination Type drop-down list. 2. Use the Add button. ( A resource adapter is analogous to a JDBC driver.

Click Add. In the Coded Name field of the dialog box that appears. PhysicalQueue) and press Return. because the coded name should be jms/MyMDBQcf 4. The destination class in the code is javax.jms. In the Sun-specific Settings area. make sure that the checkbox is selected. 2.Queue). In the JNDI Name field. Select the simpleMessageApp application. The name also appears in the Display Name field. In this example. Setting the Resource References of the client Select the SimpleMessageClient in the Left pane and use the Resource Ref’s tabbed pane on the right to specify the connection factory references for the component.SimpleMessageClient. In the Destination Name field. 7. 3. Select the Message Destinations tab. 6. Setting the Message Destination References For any new application. javax. 2. Under Connection Settings. Deploying the J2EE Application 1. 5. choose the class that matches the destination type (in this case. 7. PhysicalQueue).jms. select the connection factory class that matches the destination type. This choice allows the container to optimize connections. enter the user name and password for the Application Server. Setting the Message Destinations 1. 1. Click Add. 6. In the Authentication field select Container. In the Destination Name field. . enter jms/MyMDBQcf in the JNDI Name field. depending on whether this component sends messages or both sends and receives messages. 4. 2. 2. 3. Enter guest in both the User Name and the Password fields. In the Coded Name field. In the window that appears Select the Main class as Client. Click Add. Select the Msg Dest Ref’s tab. choose Produces. enter the name that matches the parameter of the lookup method in the component code. enter the name of the connection factory in this case. so select that class. type the name of the destination (in this case. type the name of the JMS resource you created (in this case.4. In the Destination Type combo box. 1. choose either Produces or ConsumesProduces. the the coded name is jms/MyQueue 4. In the Type field. 3. Click Next and then click finish to return to the main window. we use the Msg Dest Ref’s tab to specify the destination of messages. From the Usage combo box. For our example. In the Sharable field. 8. type a name that matches the parameter of the lookup call that locates the queue or topic. 5. For this example.QueueConnectionFactory. 3. Select the Resource Ref’s tab. type the name of the physical destination you created (in this case. jms/MyQueue). The names of the components that consume and produce messages for the destination appear in the Producers and Consumers areas. Select Tools -> Deploy.

} . click Close when the deployment completes.jar resides in C:\mdb Running the Application Client 1. Select the Return Client JAR checkbox. 13. 3. 5.naming. QueueSender queueSender = null. enter C:\mdb Click OK. 14. { 19. { 9. TextMessage message = null.*/ 7. public class SimpleMessageClient { /* The main method of the client.*. a. Check C:/Sun/AppServer/domains/domain1/logs/server. jndiContext = new InitialContext().*. import javax. The client sends three messages to the message queue and on the other hand the bean receives these messges asynchronously from the queue. import javax. QueueConnection queueConnection = null. 2.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. QueueConnectionFactory queueConnectionFactory = null. package client. QueueSession queueSession = null. public static void main(String[] args) 8. 5. Verify that a stub client JAR named SimpleMessageAppClient. 10. 6. Context jndiContext = null. the following lines should be displayed.4. Tell deploytool to create a JAR file that contains the client stubs. 16. In the command prompt go to the directory C:\mdb set APPCPATH=c:\mdb\SimpleMessageAppClient. 2.jms. In the field below the checkbox. 20. 15. try 18. 12. In the server log file. In the Distribute Module dialog box. 7. 4. 3.jar set path=c:\Sun\AppServer\bin Run the client as C:\mdb>appclient -client SimpleMessageApp. 4. 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.log. b.java 1. 6. 17. Queue queue = null. 11. final int NUM_MSGS = 3.

rmi.setMessageDrivenContext()").out. 6. 47. import javax. /* Sets the context for the bean */ 20. System.out.lookup("java:comp/env/jms/MyMDBQcf"). 40. } // class SimpleMessageBean. } // if 63. { 59.createQueueSession (false. } 48. 41. { 55. import javax. public class SimpleMessageBean implements MessageDrivenBean.*. package msg. System. import javax.Serializable.*/ 26. import java. System. import java. import javax.toString()). 24. catch (NamingException e) 22.exit(0). 34. 2.println("In SimpleMessageBean.out. i < NUM_MSGS. System. { 12.exit(1). */ 15. { 44. public void ejbCreate() 27.CreateException. } 61. try 37.ejb.jms.*. import javax. private Context context.toString()). queueSession= queueConnection. try 58.toString()).ejb.naming. { 38. Required by EJB spec. { 51. queueConnection = queueConnectionFactory. message = queueSession. { 17. System.out.createSender(queue). } 53. private transient MessageDrivenContext mdc = null. { 22. for (int i = 0. if (queueConnection != null) 56.ejb. MessageListener 11. 10. 7. queueSender.Session. { . 45.lookup ("java:comp/env/jms/MyQueue"). public void setMessageDrivenContext(MessageDrivenContext mdc) 21. System. 42. Creates a bean.getText()). System. } 31. } 19.SimpleMessageBean()"). i++) 43. catch (Throwable e) 50. } // finally 65. 8. 25. } 49. System.MessageDrivenContext. /*Default constructor. catch (JMSException e) {} 62.exit(1).close(). public SimpleMessageBean() 16. 13.MessageDrivenBean. System. queue=(Queue) jndiContext. } 36. import javax.out. finally 54. queueConnection.out. { 57.AUTO_ACKNOWLEDGE). 39.java 1. { 33. { 28. 23.createQueueConnection().println("Exception occurred: " + e. 46. 18.RemoteException. message. 4. queueSender = queueSession. 9.println("JNDI lookup failed: " + e.println("In " + "SimpleMessageBean. { 23. Required by EJB spec. } 25. 24.createTextMessage(). 52.ejb. this. 30. queueConnectionFactory = (QueueConnectionFactory) jndiContext. 29.io. 64. 3. 35.println("Could not create JNDI " + "context: " + e.21. 60.send(message).println("Sending message: "+ message. /*Creates a bean. catch (NamingException e) 32.EJBException. 14. try 27. 5. } // main 66.setText("This is message " + (i + 1)).mdc = mdc. } 26.

6. */ 52. System.Create a folder called welcome and in that create two sub-directories called beans and client. if (inMessage instanceof TextMessage) 37. /* When the queue receives a message. 39. 4.java javac -d . Compile the java files as javac -d .jar e.ejbCreate()"). { 33.printStackTrace().java in the beans folder. System.java in the beans folder. Move to the welcome directory. TextMessage msg = null. { te.getText()). Set PATH=. 2. 55. { 54. /* Removes the bean. catch (JMSException e) 47. } 46.Write the code for client and save the file as WelcomeClient. System.Write code for a bean class and save the file as WelcomeBean.java in the client folder.. 44. try 35.java in the beans folder. the bean class. } 45. } // class Session Bean • • View Edit Aim: Write a program to develop a Enterprise Java Bean of "Session Bean" type.%j2ee_home%\jdk\bin d. and the client file. { 43. c. 29.remove()").. { 38. client\*.Write code for a Home interface and save the file as WelcomeHome. 3. 40.out. catch (Throwable te) 49.java . Procedure Steps for Execution 1. } 48.Write code for a Remote interface and save the file as Welcome. the Home interface. Required by EJB spec.%j2ee_home%\lib\j2ee. b. System. Set classpath=.out. { e. } 56.printStackTrace(). public void ejbRemove() 53.28.getClass(). Open the command prompt.println("In SimpleMessageBean.out. msg = (TextMessage) inMessage. } 50.getName()).println("In SimpleMessageBean.println("MESSAGE BEAN: Message received: "+ msg. else 42. } 30. public void onMessage(Message inMessage) 32.println("Message of wrong type: "+ inMessage. a. 34. { 36.out.Compile the Remote interface. } // onMessage 51. } 41.. the EJB container invokes the onMessage method of the message-driven */ 31. beans\*. 5.

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

Run the client as C:\welcome>appclient -client WelcomeApp.In the field below the checkbox.8 Click Ok.jar resides in C:\welcome. The New Application Client wizard screen will be displayed as shown below: Give the Jar Display name as WelcomeClient.In the terminal window.In the Distribute Module dialog box. 3.8 Select the Interfaces as Session8 Select the Home Interface as beans.8 Deploying the J2EE Application 1. click Close when the deployment completes. go to File 2.WelcomeHome8 Select the Remote Interface as beans. 2. a.In the Add Enterprise Bean Reference wizard provide the following values.In the window that appears select the Main class as Client.Tell deploytool to create a JAR file that contains the client stubs.A screen saying Edit contents of WelcomeClient will be displayed.Application Client.set path=c:\Sun\AppServer\bin 4.ear -name WelcomeClient -textauth 5.Under Connection Settings.WelcomeClient. select the JNDI Name option and select WelcomeJNDI. Give the Coded Name as WelcomeJNDI8 Select the EJB type as Session. enter C:\welcome 5. And click Edit Contents button 3.Verify that a stub client JAR named WelcomeAppClient. b. In that click Add 2. 4. 7. the client displays the result .Select Tools -> Deploy.jar 3. 6.In the Application Deployment Tool screen.8 In the Target EJB .Click Next in the Introduction wizard that appears. In that select the WelcomeClient.In the command prompt go to the directory C:\Welcome 2. 4.Click OK.Select the Return Client JAR checkbox. Running the Application Client 1.Welcome. Specifying the Application Client's Enterprise Bean Reference 1. enter the user name and password for the Application Server.class in the client folder and click Add and tehn click Next in the wizard that appears.◊New ◊1.click Next and then click finish to return to the main window.Select the WelcomeClient in the Left panel and select the EJB Ref’s tab.Select the WelcomeApp application.set APPCPATH=c:\welcome\WelcomeAppClient.

3. } Welcome.remove(). } 20. { 18. 18. } 23.println("Create Exception Occured" + e). 4. 2. InitialContext ic=new InitialContext(). String retval=wel. } 27. System. 10. } 16. public void ejbRemove() 16. RemoteException. { 9. { 4.RemoteException. import java.create(). { 17. 14.*.java 1. 3. ". } 8. public class WelcomeClient 4.println("Remote Exception Occured" + e). { 21. WelcomeHome welhome = (WelcomeHome)ic.ejb.ejb. Program WelcomeBean. try 8. System. public interface WelcomeHome extends EJBHome { public Welcome create() throws CreateException. 6. } 23.ejb. 2. public void setSessionContext(SessionContext ctx) 20. } WelcomeClient. 22.rmi. } 19.ejb. 7.printMessage().naming. 14. } 15. import java. } WelcomeHome.out. 15. 2. 12.java 1.java 1. 13. import javax. } 11.*.out. { 13. 4. return "Welcome to your first EJB program. public void ejbActivate() 5.*. 26. 19.CreateException e) 21. wel. import java. catch(java. public class WelcomeBean implements SessionBean 3. public void ejbCreate() 12.lookup("WelcomeJNDI"). { 25.java 1. 3. { 7.RemoteException e) 17.rmi.println(retval).*.RemoveException e) . public interface Welcome extends EJBObject { public String printMessage() throws RemoteException. import javax.ejb.rmi. Welcome wel=welhome.*. { 10. 5.Welcome to your first EJB program. catch(javax. public void ejbPassivate() 9. 2. { 22.RemoteException. public static void main(String args[]) 6. import javax. 11. 6. public String printMessage() 24.rmi. System. import javax.out. catch(javax. { 5. 5. { 6.

} Output: . 25. 28. 27. 31.24.out. 30.out. 26. 32. } { } System. 29. } catch(javax.naming.println("Remove Exception Occured" + e).println("Naming Exception occured"+e).NamingException e) { System.