Sams Teach Yourself BEA WebLogic Server 7.0 in 21 Days
The architecture of the restaurant example system now works as follows:
The code in Listings 15.1 through 15.4 implements messaging; only the classes that have been added or changed are shown. Two classes have changed:
The classes that have been added are
Listing 15.1 WaiterBean.java
/****************************************************************************** * Class Name : WaiterBean.java * Description : Picks Chef from Chef pool, passes the ordered items to the * Chef and gets the cooked items. Then serves the client. * @author Mandar S. Chitnis, Lakshmi AM. @version 1.3 * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.ejb.jms; import java.util.*; import java.rmi.RemoteException; import java.util.Properties; import javax.ejb.CreateException; import javax.ejb.RemoveException; import javax.naming.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.rmi.PortableRemoteObject; import javax.ejb.*; public class WaiterBean implements SessionBean { //defining private and public variables, for the list of items ordered //by client, and items cooked by chef private Vector orderedItemsList = new Vector(); private Vector cookedItems = new Vector(); private static final String CHEFHOME_JNDI_NAME = "Chef_Home"; private static final boolean ENABLE_WEBLOGIC_LOGGING = true; private SessionContext ctx; // Using WebLogic's log service to log events private void webLogicLog(String logMessage) { if (ENABLE_WEBLOGIC_LOGGING) System.out.println(logMessage); } //end of webLogicLog /** * Per EJB specifications to be implemented by bean, * Used when create is called on the remote interface */ public void ejbCreate() { webLogicLog("Method ejbCreate has been called"); } /** * Per EJB specifications to be implemented by bean, * Presently not being used */ public void ejbActivate() { webLogicLog("Method ejbActivate has been called"); }//end of ejbActivate /** * Per EJB specifications to be implemented by bean, * Presently not being used */ public void ejbRemove() { webLogicLog("Method ejbRemove has been called"); }//end of ejbRemove /** * Per EJB specifications to be implemented by bean, * Presently not being used */ public void ejbPassivate() { webLogicLog("Method ejbPassivate has been called"); }//end of ejbPassivate /** * Sets the session context. * * @param ctx SessionContext Context for session */ public void setSessionContext(SessionContext ctx) { webLogicLog("Method setSessionContext has been called"); this.ctx = ctx; }//end of setSessionContext //method called by client to get a list of Menu items. public MenuList getMenu(){ return MenuList.getMenu(); } //method called by client to get the order. //The client gets the menu item id from the menu list, and also //specifies the number of items. public void getOrder(MenuItem orderedItem, int quantity){ System.out.println("Item ordered : "+orderedItem.getItemDesc()); System.out.println("Item qty ordered : "+quantity); orderedItemsList.addElement(new Order(orderedItem, quantity)); } //the client calls this method to confirm his order. //When he does this, the waiter requests for an available chef //from the chef pool, and sends the item to be prepared to the chef. // The chef returns the cooked item. // The waiter then collects all the cooked items into his tray // (the global vector) and returns the cook to the cook pool public void confirmOrder(){ CookedItemImpl currentCookedItem; int itemsOrderedCtr = 0; MenuItem menuItemToBeProcessed; Enumeration orderedItemsEnum = orderedItemsList.elements(); while(orderedItemsEnum.hasMoreElements()) { try{ ChefInterface currentChef = getChefFromChefPool(); menuItemToBeProcessed = ((Order)orderedItemsEnum.nextElement()). getItem(); itemsOrderedCtr++; //currentCookedItem = currentChef.cookItem(menuItemToBeProcessed); //cookedItems.addElement(currentCookedItem); } catch(Exception e){ e.printStackTrace(); } }//end of while //calling the static method cookedItems = ReceiveMessagesFromQueue.getAllCookedItems (itemsOrderedCtr); } //called by the waiter to get a chef from the chef pool public ChefInterface getChefFromChefPool(){ ChefInterface chef=null; try{ ChefHome chefHome = lookupHome(); chef = (ChefInterface)PortableRemoteObject.narrow(chefHome.create(),ChefInterface.class); } catch(Exception e){ e.printStackTrace(); } return chef; } /** * Lookup the EJBs home in the JNDI tree */ private ChefHome lookupHome() throws NamingException { // Lookup the beans home using JNDI //(Properties can be used instead of Hashtable, to keep the code // compatible with jdk1.1 also.) try{ Hashtable h = new Hashtable(); h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); h.put(Context.PROVIDER_URL, "t3://localhost:7001"); Context ctx = new InitialContext(h); System.out.println("Initial context to look up chef home created "+ctx); Object home = ctx.lookup(CHEFHOME_JNDI_NAME); System.out.println("Lookup performed"); return (ChefHome)PortableRemoteObject.narrow(home, ChefHome.class); } catch (NamingException namingException) { System.out.println("Unable to lookup EJBHome ChefHome."); System.out.println("Check JNDI name "+CHEFHOME_JNDI_NAME+" on the WebLogic server"); throw namingException; } } //performed by the waiter after all the items are cooked, //and collected in the vector, and then served to the client. public Vector serveCookedItem(){ return cookedItems; } //called by the client, to get his check. public float getCheck(){ float checkSum = 0; Enumeration orderedItemsEnum = orderedItemsList.elements(); while(orderedItemsEnum.hasMoreElements()) { Order individualCurrOrder = (Order)orderedItemsEnum.nextElement(); checkSum += (individualCurrOrder.getItem()).getItemPrice() *individualCurrOrder.getQty(); } return checkSum; } }; Listing 15.2 ChefBean.java
/****************************************************************************** * Class Name : ChefBean.java * Description : Gets item to be cooked from the Waiter. After preparing item, * puts the prepared items onto the queue. * @author Mandar S. Chitnis, Lakshmi AM. @version 1.3 * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.ejb.jms; import javax.naming.*; import javax.ejb.*; import java.util.*; import javax.rmi.PortableRemoteObject; import javax.ejb.CreateException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import javax.naming.InitialContext; import javax.naming.NamingException; public class ChefBean implements SessionBean { private String chefId; private static final boolean ENABLE_WEBLOGIC_LOGGING = true; private boolean isAvailable; private SessionContext ctx; //Defining context factory. //This is the default WebLogic's context factory. //This class can be found in the weblogic.jar package located in the //C:\bea\weblogic700\server\lib directory. public static final String WEBLOGIC_JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory"; //defining the name of the JMS connection factory which contains our queues. //this has to be configured via the admin console. public static final String JMS_FACTORY = "learnweblogic7.jms.QueueConnectionFactory"; //defining the name of the queue to be used for sending //OrderedItem Messages. public static final String ORDERED_ITEMS_QUEUE = "learnweblogic7.jms.orderedItemsQueue"; /** * Per EJB specifications to be implemented by bean, * Used when create is called on the remote interface */ public void ejbCreate(){ webLogicLog("Method ejbCreate has been called"); } // Using WebLogic's log service to log events private void webLogicLog(String logMessage) { if (ENABLE_WEBLOGIC_LOGGING) System.out.println(logMessage); } //end of webLogicLog /** * Per EJB specifications to be implemented by bean, * Presently not being used */ public void ejbActivate() { webLogicLog("Method ejbActivate has been called"); }//end of ejbActivate /** * Per EJB specifications to be implemented by bean, * Presently not being used */ public void ejbRemove() { webLogicLog("Method ejbRemove has been called"); }//end of ejbRemove /** * Per EJB specifications to be implemented by bean, * Presently not being used */ public void ejbPassivate() { webLogicLog("Method ejbPassivate has been called"); }//end of ejbPassivate /** * Sets the session context. * * @param ctx SessionContext Context for session */ public void setSessionContext(SessionContext ctx) { webLogicLog("Method setSessionContext has been called"); this.ctx = ctx; }//end of setSessionContext /** * Look up the bean's home interface using JNDI. */ private ItemHome lookupHome() throws NamingException { Hashtable h = new Hashtable(); h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); h.put(Context.PROVIDER_URL, "t3://localhost:7001"); Context ctx = new InitialContext(h); System.out.println("Initial context to look up BMP ItemHome created "+ctx); try { Object home = (ItemHome)ctx.lookup("BMP_ItemHome"); return (ItemHome)PortableRemoteObject.narrow(home, ItemHome.class); } catch (NamingException ne) { webLogicLog("Unable to lookup the EJBHome. Verify the ejb JNDI name BMP_ItemHome on the WebLogic server"); throw ne; } } /** * This method is called by the waiter to cook the item. * * @param orderedItem MenuItem object ordered item * @return object CookedItem */ public void cookItem(MenuItem orderedItem){ ItemHome home; ItemPK orderedItemPk; String EJBQLIngredients; String orderedItemName; String orderedItemServingSize; String orderedItemTaste; String orderedItemIngredients; String orderedItemTemperature; webLogicLog("cook Item called"); int orderedItemId = orderedItem.getItemId(); CookedItemImpl preparedItem = new CookedItemImpl(); System.out.println("The ordered item desc is:"+ orderedItem.getItemDesc()); //call the entity bean now to get the attributes for the cooked Item. try{ home = lookupHome(); orderedItemPk = new ItemPK(orderedItemId); ItemInterface orderedItemInterface = (ItemInterface)home.findByPrimaryKey(orderedItemPk); System.out.println("Item interface object created"+ System.currentTimeMillis()); orderedItemName = orderedItem.getItemDesc(); preparedItem.setItemName(orderedItemName); orderedItemServingSize = orderedItemInterface.getItemServingSize(); preparedItem.setServingSize(orderedItemServingSize); orderedItemTaste = orderedItemInterface.getItemTaste(); preparedItem.setTaste(orderedItemTaste); orderedItemIngredients = orderedItemInterface.getItemIngredients(); preparedItem.setIngredients(orderedItemIngredients); orderedItemTemperature = orderedItemInterface.getItemTemperature(); preparedItem.setTemperature(orderedItemTemperature); InitialContext ic = getInitialContext("t3://local host:7001"); SendMessagesToQueue messageSender = new SendMessagesToQueue(); messageSender.init(ic, ORDERED_ITEMS_QUEUE); SendMessagesToQueue.readAndSend(messageSender,preparedItem); messageSender.close(); // return preparedItem; } catch(Exception e){ e.printStackTrace(); } //changed here for JMS. }//end of cookItem private static InitialContext getInitialContext(String url) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, WEBLOGIC_JNDI_FACTORY); env.put(Context.PROVIDER_URL, url); return new InitialContext(env); } } Listing 15.3 SendMessagesToQueue.java
/****************************************************************************** * Class Name : SendMessagesToQueue.java * Description : Sends the prepared items on the queue * @author Mandar S. Chitnis, Lakshmi AM. @version 1.3 * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.ejb.jms; import java.io.*; import java.util.*; import javax.transaction.*; import javax.naming.*; import javax.jms.*; public class SendMessagesToQueue { //Defining context factory. //This is the default WebLogic's context factory. //This class can be found in the weblogic.jar package located in the // C:\bea\weblogic700\server\lib directory. public static final String WEBLOGIC_JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory"; //defining the name of the JMS connection factory which contains our queues. //this has to be configured via the admin console. public static final String JMS_FACTORY = "learnweblogic7.jms.QueueConnectionFactory"; //defining the name of the queue //to be used for sending OrderedItem Messages. public static final String ORDERED_ITEMS_QUEUE = "learnweblogic7.jms.orderedItemsQueue"; private QueueConnectionFactory qConnFactory; private QueueConnection qConn; private QueueSession qSession; private QueueSender qSender; private Queue queue; public static ObjectMessage orderedMsg; /**** Method to obtain the initial context of the queue factory ***/ private static InitialContext getInitialContext(String contextProviderUrl) throws NamingException { Hashtable envHash = new Hashtable(); envHash.put(Context.INITIAL_CONTEXT_FACTORY, WEBLOGIC_JNDI_FACTORY); //contextProviderUrl is "t3://localhost:7001" in case of weblogic envHash.put(Context.PROVIDER_URL, contextProviderUrl); return new InitialContext(envHash); } /** * Creates all the necessary objects for sending * messages to a JMS queue. * * @param ctx JNDI initial context * @param queueName name of queue * @exception NamingException if operation cannot be performed * @exception JMSException if JMS fails to initialize due to internal error */ public void init(Context ctx, String queueName) throws NamingException, JMSException { qConnFactory(QueueConnectionFactory) ctx.lookup(JMS_FACTORY); qConn = qConnFactory.createQueueConnection(); qSession = qConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queue = (Queue) ctx.lookup(queueName); qSender = qSession.createSender(queue); orderedMsg = qSession.createObjectMessage(); qConn.start(); } public static void readAndSend( SendMessagesToQueue itemSender, CookedItemImpl cookedItem) throws IOException, JMSException { boolean quitNow = false; do { itemSender.send(cookedItem); System.out.println("Sent Message "+cookedItem); }while(!quitNow); } /** * Send a message to a JMS queue using this method. * * @params message message to be sent *@exception JMSException if JMS fails to send message * due to internal error */ //public void send(ObjectMessage message) public void send(CookedItemImpl cookedItem) throws JMSException { /* Vector itemsVector = new Vector(); itemsVector.addElement("apple"); itemsVector.addElement("orange"); itemsVector.addElement("banana");*/ orderedMsg.setObject(cookedItem); qSender.send(orderedMsg); } /** * Closes JMS objects. * @exception JMSException if JMS fails to close objects * due to internal error */ public void close() throws JMSException { qSender.close(); qSession.close(); qConn.close(); } } Listing 15.4 ReceiveMessagesFromQueue.java
/****************************************************************************** * Class Name : ReceiveMessagesFromQueue.java * Description : Gets the prepared items from the queue * @author Mandar S. Chitnis, Lakshmi AM. @version 1.3 * Copyright (c) by Sams Publishing. All Rights Reserved. *******************************************************************************/ package com.sams.learnweblogic7.ejb.jms; import java.io.*; import java.util.*; import javax.transaction.*; import javax.naming.*; import javax.jms.*; public class ReceiveMessagesFromQueue implements MessageListener { //Defining context factory. //This is the default WebLogic's context factory. //This class can be found in the weblogic.jar package located in the // C:\bea\weblogic700\server\lib directory. public static final String WEBLOGIC_JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory"; //defining the name of the JMS connection factory which contains our queues. //this has to be configured via the admin console. public static final String JMS_FACTORY = "learnweblogic7.jms.QueueConnectionFactory"; //defining the name of the queue to be used for sending //OrderedItem Messages. public static final String ORDERED_ITEMS_QUEUE = "learnweblogic7.jms.orderedItemsQueue"; private QueueConnectionFactory qConnFactory; private QueueConnection qConn; private QueueSession qSession; private QueueReceiver qReceiver; private Queue queue; private boolean quit = false; static Vector cookedItems = null; static int orderedItemsCtr=0; static int receivedItemsCtr=0; /** * Message listener interface. * @param msg message */ // MessageListener interface public void onMessage(Message msg) { try { CookedItemImpl cookedItem=null; if(msg instanceof ObjectMessage){ ObjectMessage objMsg = (ObjectMessage)msg; cookedItem = (CookedItemImpl)objMsg.getObject(); } else{ System.out.println("Error in message"); } System.out.println("Message Received:"); cookedItems.addElement(cookedItem); receivedItemsCtr++; } catch (JMSException jmse) { jmse.printStackTrace(); } } /** * Creates all the necessary objects for receiving * messages from a JMS queue. * * @param ctx JNDI initial context * @param queueName name of queue * @exception NamingException if operation cannot be performed * @exception JMSException if JMS fails to initialize due to internal error */ public void init(Context ctx, String queueName) throws NamingException, JMSException { qConnFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY); qConn = qConnFactory.createQueueConnection(); qSession = qConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queue = (Queue)ctx.lookup(queueName); qReceiver = qSession.createReceiver(queue); qReceiver.setMessageListener(this); qConn.start(); } /** * Closes JMS objects. * @exception JMSException if JMS fails to close objects due to internal error */ public void close() throws JMSException { qReceiver.close(); qSession.close(); qConn.close(); } /** * main() method. * * @params args WebLogic Server URL * @exception Exception if execution fails */ public static void main(String[] args) throws Exception { InitialContext ic = getInitialContext("t3://localhost:7001"); ReceiveMessagesFromQueue qr = new ReceiveMessagesFromQueue(); qr.init(ic, ORDERED_ITEMS_QUEUE); System.out.println("JMS Ready To Receive Messages (To quit, send a \"quit\" message)."); // Wait until a "quit" message has been received. synchronized(qr) { while (! qr.quit) { try { qr.wait(); } catch (InterruptedException ie) {} } } qr.close(); } private static InitialContext getInitialContext(String url) throws NamingException { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, WEBLOGIC_JNDI_FACTORY); env.put(Context.PROVIDER_URL, url); return new InitialContext(env); } public static Vector getAllCookedItems(int itemsOrderedCtr){ orderedItemsCtr = itemsOrderedCtr; checkIfAllItemsCooked(); return cookedItems; } public static void checkIfAllItemsCooked(){ if(orderedItemsCtr < receivedItemsCtr){ try{ Thread.sleep(100); checkIfAllItemsCooked(); } catch(Exception e){ e.printStackTrace(); } } } |