Tutorial for building J2EE applications using JBoss and eclipse (7)

Source: Internet
Author: User
Document directory
  • Tasks:
  • Implement onmessage method:
  • Deploy requestitems Bean:
  • Create test client:
  • Test your client:
  • Exercise:
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 varous 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 the manager and item beans, which are also used by these message-driven beans weCanUse their local interfaces as they are in the same JVM, And we have exposed their local interfaces.

Tasks:
  1. Create a MD bean named requestitems under package au.com. tusc. MDB.

  2. 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

  3. Implement the onmessage method.

  4. Deploy the requestitems bean.

  5. Create your test client named requestmdbclient under package au.com. tusc. MDB.

  6. Add a method named tew.dbbean with the following signature and implement it.

    Public void testmdbbean

  7. 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 drive 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 doesn't 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 (s ).

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 any functionality, create a class or immutable value object for extracting information from the message.

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 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 these 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 them to the attributes as shown below.


The requestitem constructor is complete. Now to implement the onmessage method in the requestitem bean.

Implement onmessage method:

This method is responsible for extracting the information from the message and transferring it to the relevant bean.

The mystore manager will check for items which are out of stock and generate a request to suppliers specifying the Itemid and quantity required.

First import the packages java. util. arraylist and Java. util. iterator.

Add the following variables to store references.

ArrayList outOfStockItems = null;       Iterator itemsIterator = null;private StoreAccessHome storeAccess = null;private SupplierLocalHome suppLocalHome = null;private ItemLocalHome itemLocalHome = null;

Extract the data from the message into the immutable value object as shown below.

RequestItem ri =  (RequestItem) ((ObjectMessage) message).getObject();

Add the lines of code shown below, so that the manager can login.

StoreAccess access = StoreAccessUtil.getHome().create();                                String mgrAccessID = access.loginUser(ri.getUsername(),ri.getPasswd());                                           

Get items with zero quantity (no stock), by invoking getoutofstockitems () 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.iterator();while ( itemsIterator.hasNext() ) {                         ItemData itemData= ( ItemData ) itemsIterator.next();    String suppID = itemData.getSupplierID();    SupplierLocal supplier = this.suppLocalHome.findByPrimaryKey(suppID);    Integer quantity = new Integer (ri.getQuantity());    String itemID = ri.getItemID();    supplier.requestItem( itemID, quantity); }                                       

Code snippet of onmessage is shown below.


Now our 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 requestitems bean, to obtain a reference to storeaccessbean, so that methods can be invoked on that bean.

@ejb.ejb-refejb-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-refejb-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 <EJB-Name>, 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 used 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="SupplierLocal" jndi-name="SupplierLocal"

Note: As discussed in Chapter5, this tag generates incorrect descriptors within JBoss. XML. for view-type = "local" it generates an <EJB-ref> tag rather than <EJB-local-ref> tag.

Correct the following tags:


Find these tags in JBoss. xml and change them to <EJB-local-ref> as shown below.


Now add this last tag as shown below for our storeaccess bean, to reference the storeaccess bean using its JNDI name.

@jboss.ejb-ref-jndi ref-name="StoreAccess"jndi-name="StoreAccessBean"

This tag will generate the following descriptors in JBoss. xml:


Now our requestitems bean is complete, so now add your bean and generate your EJB classes.

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 you have generated your classes you have to again fix the incorrectly-generated deployment descriptors in JBoss. XML, under <message-driven> and <session>.

Now, let's deploy our Bean. Go to lomboz J2EE view, start your server if 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 chapters.

Once the bean is deployed successfully, create your test client.

Create test client:

Now, to create a test client in this case, the test client wizard can't 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 following signature:

private InitialContext getContext() throws NamingException 

Add the following lines of code to get the instance of intialcontextAs shown below.


Add a method named tew.dbbean with the following signature.

public void testMDBBean()

Now implement this method, in which the following steps are needed:

  1. Add a data object which is to be sent as the message.

  2. Create the initial context reference.

  3. Create the connection factory reference.

  4. Use this context to perform the lookup, where the lookup string is "queue/mdbqueue ".

  5. Create the queueconnection.

  6. Create the queuesender.

  7. Create the queuesession for the bean.

  8. Create the object message and pass the data object in message.

  9. Send the message.

  10. 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:

To test your client, select requestmdbclient node> go to the top level menu and select the 'running man' icon.

On that select 'run as'> select Java application.

Note: The steps to run test clients have been covered in previous chapters.

Now, under your console, you shocould get the following messages:


This message on the console doesn' t 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 'provision' to see if a message has been added for the supplier.


Note: Details on accessing this database manager are provided in Chapter 1.

Since a supplier named Sebastian has received ed our message, our message has been transferred successfully.

Exercise:

Now, to progress further, please complete the following exercise. Implement deliveritems as an MD bean. detailed tasks are given below.

  1. Create an MD bean named deliveritems under the package au.com. tusc. MDB.

  2. 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

  3. 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 ( suppID.equals(itemSuppID)) {    System.out.println ("Delivering items in store now... :");    Integer quantity = new Integer (di.getQuantity());    item.fillStock(quantity);    System.out.println ("Stock of iten after dleivery is :" + item.getItemData());}
  4. Add the following tags for deployment at the class level for linking/referencing supplier.

    1. @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" 
  1. Deploy your deliveritems bean.

  2. Create a test client named delivermdbclient under the package au.com. tusc. MDB.

  3. Add a method named tew.dbbean with the following signature.

    Public void testmdbbean

  4. Implement temo-dbbean, 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 queuesession 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.

  1. Run your client and test the bean.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.