Tutorial for building J2ee Applications Using JBoss and Eclipse -7

xiaoxiao2021-03-06  78

Chapter 7.

Creating a Message Driven Bean

This chapter covers how to create a Message Driven Bean (MDB) EJB component. We will create two MDB beans, DeliverItems and RequestItems as shown below. The DeliverItems bean will replenish the stocks of various items within MyStore, and the RequestItems bean will send requests To Various Suppliers To Deliver Items Which Are Out of stock. The MyStore Manager Will Issue / Send this request.

Note:. Both message-driven beans access the StoreAccess bean through its remote interface, even though the StoreAcessBean is in the same JVM This is because we have implemented StoreAccessBean as a Remote Bean, so it only exposes its remote interface However, in accessing. ................. ..

Tasks:

.. Create a MD bean named RequestItems under package au.com.tusc.mdb Create an Immutable Value Object named RequestItem under package au.com.tusc.mdb Add attributes and implement their accessor and mutator methods The attributes are:. Private String username private String passwd private String itemID private int quantity Implement the onMessage method. Deploy the RequestItems Bean. Create your test client named RequestMDBClient under package au.com.tusc.mdb. Add a method named testMDBBean with the following signature and implement it. public void Testmdbbean Run Your Client and test the bean.

Create RequestItems MDB Bean:

Go to Package Explorer> Expand MyStore (Project) Node> SELECT SRC, RIGHT CLICK AND A MENU WILL POP UP.

On The Pop Up Menu> New> Lomboz EJB CREATION WIZARD.

Enter package name au.com.tusc.mdb, bean name requestItems and select bean type as message driving bean (queue) AS Shown Below.Press Finish.

This Will Create a package named au.com.tusc.mdb under src and requestitemsbean within That Package As Shown Below.

Note: Message-driven beans listen for messages from a JMS Producer, which gets information from a producer (perhaps another bean) and transfers it to the relevant Consumer bean Since it is only responsible for processing such messages, it does not need any. helper classes such as Remote and RemoteHome interfaces, Util classes, DAO class, etc. like our previous types of beans. The only helper classes we have to create are immutable value objects, which will be responsible for holding the information extracted from messages and then Transferred to the bean.

Let's Examine What Methods and Tags Are Generated by The EJB CREATION WIZARD..

IT Creates One @ Ejb.bean Tag Which Assigns The Name, Transaction Type, Destination Type and Some Other Properties As Shown Below.

Unlike Our Previous Beans It Has A SetMessageContext Method for Setting The Context.

IT Has Ejbcreate and Ejbremove Methods Like The Other Types of Beans, As Shown Below.

IT Has A New Method Named OnMessage Which is The One of Significance To US, WHERE All The Business Logic Will Be Written (As Shown Below).

Once a message is received from the JMS producer as a Message object, its data is extracted and filled into the immutable value object and then transferred to the relevant bean. This is covered later on in this chapter.

NOW, Before We add anyb, create a class or immutable value object for extracting information from it.

Create Immutable Value Object RequestItem:

Go to SRC> Under package au.com.tusc.mdb> new> Class.

The Java Class Wizard Will Pop Up> Add Class Name As RequestItem, Superclass As Java.lang.Object and Interfaces As Serializable As As Shown Below In Figure.

This Will Generate A RequestItem Class Under au.com.tusc.mdb as shown below.

Add The Following Attributes to The RequestItem Class As Shown Below.

PRIVATE STRING UserName;

PRIVATE STRING Passwd;

PRIVATE STRING ITEMID;

Private int quantity;

Add Accessor and Mutator Method for The attributes.

Select All Attributes> Right Click> Select Source> Generate getter and setter as shown below.

Add a constructor for the Class Which Has Parameters with the Same Type as the attributes and assigns the the attributes as shown bellow.

The RequestItem Constructor is Complete. Now TO IMPLEMENT The OnMessage Method in The RequestIn

Implement OnMessage Method:

................. ..

THE MyStore Manager Will Check for Items Which Are Out of stock and generate a request to support and quantity required.

First Import the packagelist and java.util.Iterator.

Add The Following Variables to Store References.

ArrayList OutofstockItems = NULL;

Iterator itemsiterator = null;

PRIVATE STOREACCESSHOME StoreAccess = NULL;

Private supportLocalhome sales = NULL;

Private itemlocalhome itemlocalhome = null;

Extract The Data from The Message Into The Immutable Value Object As Shown Below.

RequestItem Ri = ((ObjectMessage) message .GetObject ();

Add The Lines of Code Shown Below, So That The Manager CAN Login.

STOREACCESS = storeAccessutil.getHome (). CREATE ();

String mgraccessid = access.loginuser (ri.getusername (), ri.getpasswd ());

Get Items with Zero Quantity (No stock), by Invoking GetOfstockItems () on The StoreAccess Bean (Which Returns A Collection).

OutofstockItems = Access.getOutofStockItems ();

Now, iterating over each item, get the supplierId associated with it by invoking the finder methods on the Supplier Bean, finally sending the required message to that supplier by invoking the business method requestItem () on the Supplier Bean.

Itemsiterator = OutofstockItems.IutofstockItems.Iuterator ();

While (itemsiterator.hasnext ()) {

Itemdata itemdata = (itemdata) itemsiterator.next ();

String support = itemdata.getsupplierID ();

SupplierLocal Supplier = this.supplocalHome.FindByPrimaryKey (Suppod);

Integer QUANTITY = New Integer (ri.getquantity ());

String itemid = ri.getItemid ();

Supplier.RequestItem (itemid, quantity);

}

Code Snippet of Onmessage Is Shown Below.

Nowur Bean is Complete, And All That Remains Are The Deployment Descriptors for the bean.

Deploy RequestItems Bean:

In Order to Deploy this Bean we have to add a few deployment descriptors. AS Shown Below, Five Tags Have Been Added.

First Add The Tag Shown Below At Class Level in The ReferenceTitems Bean To Obtain A Reference To StoreAccessBean, So That Methods Can Be Invoked On That Bean.

@ ejb.ejb-ref

EJB-Name = "storeAccess"

View-type = "remote"

Ref-name = "storeAccess"

This tag will generate deployment descriptors in ejb-jar.xml when you generate your ejb classes, as this message bean has to authenticate, before transferring information to the relevant bean. This will generate these descriptors as shown below.Add another tag as shown below To Obtain a Reference to The Supplier Bean from this bean.

@ ejb.ejb-ref

EJB-Name = "Supplier"

View-type = "local"

Ref-name = "SupplierLocal"

This tag will generate also generate descriptors in ejb-jar.xml when you generate your ejb classes, as this message bean transfers information to the Supplier bean. The following descriptors are generated as shown below.

NOTE: Another Descriptor Which Has Been generated is , which is generated by the tag @ Ejb.bean That Was added by the EJB CREATION WIZARD.

THIS TAG GENERATES The FOLLOWING Descriptors in EJB-jar.xml:

Add ANOTHER TAG As Shown Below. This Tag is Jboss-Specific, and is buy to register a message-driven bean with a jndi-name, using the format "queue / name".

@ jboss.destination-jndi-name

Name = "queue / mdbqueue"

This Will Generate The Following Deployment Descriptors in jboss.xml:

NOTE: For Further Documentation ON MDB Development with Jboss, please refer to the jboss documentation.

Add ANOTHER TAG As Shown Below, Required by Jboss, for Finding The Supplier Bean Using ITS JNDI Name.

@ jboss.ejb-ref-jndi ref-name = "supportlierlocal"

JNDI-NAME = "SupplierLocal"

Note: as discussed in chapter5, this tag generates incorrect descriptors within jboss.xml. For view-type = "local" it generates AN TAG Rather Than AN TAG.

Correct The Following Tags:

Find these tags in jboss.xml and change the.......................... ..

@ jboss.ejb-ref-jndi ref-name = "storeAccess"

JNDI-Name = "StoreAccessBean"

THIS TAG WILL Generate The Following Descriptors in jboss.xml:

Nowur RequestItems Bean is Complete, So Now Add your bean and generate your ejb class.

Go to the requestitemsbean node under au.com.tusc.mdb> Right Click> SELECT LOMBOZ J2EE ...> Add Ejb to module> OK.

Go to the MyStoremgr Node in Package Explorer> Right Click> SELECT LOMBOZ J2EE ...> Generate EJB Classes.

Note: Since: Since You Have Generated Your Classes You Have To Again Fix The IncorRectly-Generated Deployment Descriptors in jboss.xml, Under and .

Now, Let's Deployur bean. Go to Lomboz J2EE View, Start Your Server IT IT IS Not Running, and Deploy Your Bean.

Messages Will Appear in Console Showing Deployment Status.

NOTE: Steps for Deploying Beans Have Been Detailed in Previous Chapter.

Once The Bean Is Deployed Success, Create Your Test Client.

Create Test Client:

Now, to create a test client in this case, the Test Client Wizard can not help us, because it requires a Home interface and EJB interface to be selected, whereas for Message Driven Beans there is no Home interface and EJB interface required (as Discussed Above).

SO, WRITE A CLASS AND THE Necessary Methods to Invoke Operations on The RequestItems Bean.

Add a class named requestmdbclient under the package au.com.tusc.mdb.

Add A Method Named getContext with the folloading signature:

Private InitialContext getContext () throws namingexceptionAdd The Following Lines of code to get the instance of int attext as shown bellow.

Add A Method Named Testmdbbean with The Following Signature.

Public void testmdbbean ()

NOW IMPLEMENT THIS METHOD, IN which the folloading steps are needed:

Add a Data Object which is to be sent as the message. Create the Initial context reference. Create the Connection factory reference. Use this context to perform the lookup, where the lookup string is "queue / MdbQueue". Create the QueueConnection. Create the QueueSender. Create the QueueSession for the bean. Create the Object Message and pass the Data Object in message. Send the message. Finally, commit the session, and then close both the session and the connection. A code snippet of the testMDBean method is shown Below.

Now Your Test Client Is Complete, So Let's Test The Client.

Test Your Client:

Test Your Client, SELECT RequestmdbClient Node> Go to The Top Level Menu and SETHE 'RUNNING MAN' icon.

On That Select 'Run As'> Select Java Application.

Note: The Steps to Run Test Clients Have Been Covered In Previous Chapter.

Now, Under Your Console, You Should Get The Following Messages:

This message on the console does not tell us whether the message has been delivered to relevant beans or not. In order to verify that, go to the database using JMX Management Console View> Hypersonic> Invoke Database Manager and then run a query on table 'Supplier' to see if a message has been added for the support.

NOTE: Details on Accessing this Database Manager Are Provided in Chapter 1.

Since A Supplier Named Sebastian Has Received Our Message, Our message has been transfert successfully.exercise:

Now, To Progress Further, please completion the following excercise. Implement DeliverItems as an md bean. Detailed Tasks Are Given Below.

... Create an MD Bean named DeliverItems under the package au.com.tusc.mdb Create an Immutable Value Object named DeliverItem under the package au.com.tusc.mdb Add some attributes and implement their accessor and mutator methods The attributes are: . private String username private String passwd private String itemID private int quantity Implement the onMessage method in your DeliverItems Bean Add these two variables to store references private StoreAccessHome storeAccess = null.;

private ItemLocalHome itemLocalHome = null; Extract the data from the message into your immutable value object as shown below.DelieverItem di = (DeliverItem) ((ObjectMessage) message) .getObject (); Get the references for the StoreAccess and Item beans.StoreAccess access = StoreAccessutil.getHome (). CREATE ();

itemLocalHome = ItemUtil.getLocalHome (); Invoke the loginUser method for supplier to get the Supplier's userid (accessID) and then find the Supplier's ID by invoking the getSupplierData method.String suppAcessID = access.loginUser (di.getUsername (), di.getPasswd ())

SupplierData SD = Access.getsupplierData (SuppaCcessID);

String suppID = sd.getSupplierID (); If suppID is not equal to null, then invoke the finder method on the Item bean to get the details of the item to be delivered, by extracting itemID from message.ItemLocal item = this.itemLocalHome. findByPrimaryKey (di.getItemID ()); Get the supplier ID associated with the item found, so we can fill up the stock.String itemSuppID = item.getSupplierID (); Compare itemSuppID and ItemID, if these are the same then fill the stock For That Item by Invoking The FillStock Method in Item Bean.if (Suppod.Equals (itemsuppid) {

System.out.println ("Deliver Items in Store ...:");

Integer QUANTITY = New Integer (Di.Getquantity ());

Item.fillstock (Quantity);

System.out.println ("stock of iten instator is:" item.getItemData ());

.

@ Ejb.ejb-ref

EJB-Name = "storeAccess"

View-type = "remote"

Ref-name = "storeAccess"

2. @ ejb.ejb-ref

EJB-Name = "item"

View-type = "local"

REF-Name = "itemlocal"

3. @ jboss.ejb-ref-jndi ref-name = "itemlocal"

JNDI-NAME = "itemlocal"

4. @ jboss.ejb-ref-jndi ref-name = "storeAccess"

JNDI-Name = "StoreAccessBean"

5. @ JBoss.Destination-JNDi-Name

Name = "Queue / Delmdbqueue"

Deploy your DeliverItems Bean. Create a test client named DeliverMDBClient under the package au.com.tusc.mdb. Add a method named testMDBBean with the following signature. Public void testMDBBean Implement testMDBBean, for this a few steps have to be carried out. Add A Data Object Which Is To Be Sent As The Message. Create Initial Context.create Connection Factory.

Using this context Perform The JNDI Lookup, where the lookup string is "queue / delmdbqueue".

CREATE QueueConnection.

Create Queuesender.

Create queness for the bean.

Create Object Message and Pass The Data Object in The Message.

Send the message.

Finally, Commit The session and close both the session and the connection.

Run Your Client and Test the Bean.

转载请注明原文地址:https://www.9cbs.com/read-121909.html

New Post(0)