Biblioteca Java - Blame information for rev 6

Subversion Repositories:
Rev:
Rev Author Line No. Line
6 mihai 1 /*
2  * To change this template, choose Tools | Templates
3  * and open the template in the editor.
4  */
5  
6 package mqdemo;
7  
8 /*
9  * @(#)SimpleChat.java  1.10 04/01/05
10  *
11  * Copyright (c) 2000-2002 Sun Microsystems, Inc. All Rights Reserved.
12  *
13  * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
14  * modify and redistribute this software in source and binary code form,
15  * provided that i) this copyright notice and license appear on all copies of
16  * the software; and ii) Licensee does not utilize the software in a manner
17  * which is disparaging to Sun.
18  *
19  * This software is provided "AS IS," without a warranty of any kind. ALL
20  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
21  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
22  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
23  * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
24  * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
25  * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
26  * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
27  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
28  * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGES.
30  *
31  * This software is not designed or intended for use in on-line control of
32  * aircraft, air traffic, aircraft navigation or aircraft communications; or in
33  * the design, construction, operation or maintenance of any nuclear
34  * facility. Licensee represents and warrants that it will not use or
35  * redistribute the Software for such purposes.
36  */
37  
38 import java.awt.*;
39 import java.awt.event.*;
40 import java.io.Serializable;
41 import java.net.InetAddress;
42 import java.util.Vector;
43 import java.util.Enumeration;
44  
45 import javax.jms.*;
46  
47 /**
48  * The SimpleChat example is a basic 'chat' application that uses
49  * the JMS APIs. It uses JMS Topics to represent chat rooms or
50  * chat topics.
51  *
52  * When the application is launched, use the 'Chat' menu to
53  * start or connect to a chat session.
54  *
55  * The command line options like '-DimqBrokerHostName=', and '-DimqBrokerHostPort='
56  * can be used to affect how the application connects to the message service
57  * provided by the Sun Java(tm) System Message Queue software.
58  *
59  * It should be pointed out that the bulk of the application is
60  * AWT - code for the GUI. The code that implements the messages
61  * sent/received by the chat application is small in size.
62  *
63  * The SimpleChat example consists of the following classes, all
64  * contained in one file:
65  *
66  *      SimpleChat              - contains main() entry point, GUI/JMS
67  *                                initialization code.
68  *      SimpleChatPanel         - GUI for message textareas.
69  *      SimpleChatDialog        - GUI for "Connect" popup dialog.
70  *      ChatObjMessage          - chat message class.
71  *
72  * Description of the ChatObjMessage class and how it is used
73  * ==========================================================
74  * The ChatObjMessage class is used to broadcast messages in
75  * the JMS simplechat example.
76  * The interface SimpleChatMessageTypes (defined in this file)
77  * has several message 'types':
78  *  
79  * From the interface definition:
80  *     public static int   JOIN    = 0;
81  *     public static int   MSG     = 1;
82  *     public static int   LEAVE   = 2;
83  *  
84  * JOIN    - for applications to announce that they just joined the chat
85  * MSG     - for normal text messages
86  * LEAVE   - for applications to announce that are leaving the chat
87  *  
88  * Each ChatObjMessage also has fields to indicate who the sender is
89  * - a simple String identifier.
90  *  
91  * When the chat application enters a chat session, it broadcasts a JOIN
92  * message. Everybody currently in the chat session will get this and
93  * the chat GUI will recognize the message of type JOIN and will print
94  * something like this in the 'Messages in chat:' textarea:
95  *  
96  *         *** johndoe has joined chat session
97  *  
98  * Once an application has entered a chat session, messages sent as part of
99  * a normal 'chat' are sent as ChatObjMessage's of type MSG. Upon seeing
100  * these messages, the chat GUI simply displays the sender and the message
101  * text as follows:
102  *  
103  *         johndoe: Hello World !
104  *  
105  * When a chat disconnect is done, prior to doing the various JMS cleanup
106  * operations, a LEAVE message is sent. The chat GUI sees this and prints
107  * something like:
108  *  
109  *         *** johndoe has left chat session
110  *  
111  *
112  */
113 public class SimpleChat implements ActionListener,
114                                 WindowListener,
115                                 MessageListener  {
116  
117     TopicConnectionFactory      topicConnectionFactory;
118     TopicConnection             topicConnection;
119     TopicSession                        topicSession;
120     TopicPublisher              topicPublisher;
121     TopicSubscriber             topicSubscriber;
122     Topic                               topic;
123  
124     boolean                     connected = false;
125  
126     String                      name, hostName,
127                                 topicName, outgoingMsgTypeString;
128     int                         outgoingMsgType;
129  
130     Frame                       frame;
131     SimpleChatPanel             scp;
132     SimpleChatDialog            scd = null;
133     MenuItem                    connectItem, disconnectItem,
134                                 clearItem, exitItem;
135     Button                      sendB, connectB, cancelB;
136  
137     SimpleChatMessageCreator    outgoingMsgCreator;
138  
139     SimpleChatMessageCreator    txtMsgCreator,
140                                 objMsgCreator,
141                                 mapMsgCreator,
142                                 bytesMsgCreator,
143                                 streamMsgCreator;
144  
145     /**
146      * @param args      Arguments passed via the command line. These are
147      *                  used to create the TopicConnectionFactory.
148      */
149     public static void main(String[] args) {
150         SimpleChat      sc = new SimpleChat();
151  
152         sc.initGui();
153         sc.initJms(args);
154     }
155  
156     /**
157      * SimpleChat constructor.
158      * Initializes the chat user name, topic, hostname.
159      */
160     public SimpleChat()  {
161         name = System.getProperty("user.name", "johndoe");
162         topicName = "defaulttopic";
163  
164         try  {
165             hostName = InetAddress.getLocalHost().getHostName();
166         } catch (Exception e)  {
167             hostName = "localhost";
168         }
169     }
170  
171     public SimpleChatMessageCreator getMessageCreator(int type)  {
172         switch (type)  {
173         case SimpleChatDialog.MSG_TYPE_TEXT:
174             if (txtMsgCreator == null)  {
175                 txtMsgCreator = new SimpleChatTextMessageCreator();
176             }
177             return (txtMsgCreator);
178  
179         case SimpleChatDialog.MSG_TYPE_OBJECT:
180             if (objMsgCreator == null)  {
181                 objMsgCreator = new SimpleChatObjMessageCreator();
182             }
183             return (objMsgCreator);
184  
185         case SimpleChatDialog.MSG_TYPE_MAP:
186             if (mapMsgCreator == null)  {
187                 mapMsgCreator = new SimpleChatMapMessageCreator();
188             }
189             return (mapMsgCreator);
190  
191         case SimpleChatDialog.MSG_TYPE_BYTES:
192             if (bytesMsgCreator == null)  {
193                 bytesMsgCreator = new SimpleChatBytesMessageCreator();
194             }
195             return (bytesMsgCreator);
196  
197         case SimpleChatDialog.MSG_TYPE_STREAM:
198             if (streamMsgCreator == null)  {
199                 streamMsgCreator = new SimpleChatStreamMessageCreator();
200             }
201             return (streamMsgCreator);
202         }
203  
204         return (null);
205     }
206  
207     public SimpleChatMessageCreator getMessageCreator(Message msg)  {
208         if (msg instanceof TextMessage)  {
209             if (txtMsgCreator == null)  {
210                 txtMsgCreator = new SimpleChatTextMessageCreator();
211             }
212             return (txtMsgCreator);
213         } else if (msg instanceof ObjectMessage)  {
214             if (objMsgCreator == null)  {
215                 objMsgCreator = new SimpleChatObjMessageCreator();
216             }
217             return (objMsgCreator);
218         } else if (msg instanceof MapMessage)  {
219             if (mapMsgCreator == null)  {
220                 mapMsgCreator = new SimpleChatMapMessageCreator();
221             }
222             return (mapMsgCreator);
223         } else if (msg instanceof BytesMessage)  {
224             if (bytesMsgCreator == null)  {
225                 bytesMsgCreator = new SimpleChatBytesMessageCreator();
226             }
227             return (bytesMsgCreator);
228         } else if (msg instanceof StreamMessage)  {
229             if (streamMsgCreator == null)  {
230                 streamMsgCreator = new SimpleChatStreamMessageCreator();
231             }
232             return (streamMsgCreator);
233         }
234  
235         return (null);
236     }
237  
238     /*
239      * BEGIN INTERFACE ActionListener
240      */
241     /**
242      * Detects the various UI actions and performs the
243      * relevant action:
244      *  Connect menu item (on Chat menu):       Show Connect dialog
245      *  Disconnect menu item (on Chat menu):    Disconnect from chat
246      *  Connect button (on Connect dialog):     Connect to specified
247      *                                          chat
248      *  Cancel button (on Connect dialog):      Hide Connect dialog
249      *  Send button:                            Send message to chat
250      *  Clear menu item (on Chat menu):         Clear chat textarea
251      *  Exit menu item (on Chat menu):          Exit application
252      *
253      * @param ActionEvent UI event
254      */
255     public void actionPerformed(ActionEvent e)  {
256         Object          obj = e.getSource();
257  
258         if (obj == connectItem)  {
259             queryForChatNames();
260         } else if (obj == disconnectItem)  {
261             doDisconnect();
262         } else if (obj == connectB)  {
263             scd.setVisible(false);
264  
265             topicName = scd.getChatTopicName();
266             name = scd.getChatUserName();
267             outgoingMsgTypeString = scd.getMsgTypeString();
268             outgoingMsgType = scd.getMsgType();
269             doConnect();
270         } else if (obj == cancelB)  {
271             scd.setVisible(false);
272         } else if (obj == sendB)  {
273             sendNormalMessage();
274         } else if (obj == clearItem)  {
275             scp.clear();
276         } else if (obj == exitItem)  {
277             exit();
278         }
279     }
280     /*
281      * END INTERFACE ActionListener
282      */
283  
284     /*
285      * BEGIN INTERFACE WindowListener
286      */
287     public void windowClosing(WindowEvent e)  {
288         e.getWindow().dispose();
289     }
290     public void windowClosed(WindowEvent e)  {
291         exit();
292     }
293     public void windowActivated(WindowEvent e)  { }
294     public void windowDeactivated(WindowEvent e)  { }
295     public void windowDeiconified(WindowEvent e)  { }
296     public void windowIconified(WindowEvent e)  { }
297     public void windowOpened(WindowEvent e)  { }
298     /*
299      * END INTERFACE WindowListener
300      */
301  
302     /*
303      * BEGIN INTERFACE MessageListener
304      */
305     /**
306      * Display chat message on gui.
307      *
308      * @param msg message received
309      */
310     public void onMessage(Message msg)  {
311         String          sender, msgText;
312         int             type;
313         SimpleChatMessageCreator        inboundMsgCreator;
314  
315         inboundMsgCreator = getMessageCreator(msg);
316  
317         if (inboundMsgCreator == null)  {
318             errorMessage("Message received is not supported ! ");
319             return;
320         }
321  
322         /*
323          *  Need to fetch msg values in this order.
324          */
325         type = inboundMsgCreator.getChatMessageType(msg);
326         sender = inboundMsgCreator.getChatMessageSender(msg);
327         msgText = inboundMsgCreator.getChatMessageText(msg);
328  
329         if (type == SimpleChatMessageTypes.BADTYPE)  {
330             errorMessage("Message received in wrong format ! ");
331             return;
332         }
333  
334         scp.newMessage(sender, type, msgText);
335     }
336     /*
337      * END INTERFACE MessageListener
338      */
339  
340  
341     /*
342      * Popup the SimpleChatDialog to query the user for the chat user
343      * name and chat topic.
344      */
345     private void queryForChatNames()  {
346         if (scd == null)  {
347             scd = new SimpleChatDialog(frame);
348             connectB = scd.getConnectButton();
349             connectB.addActionListener(this);
350             cancelB = scd.getCancelButton();
351             cancelB.addActionListener(this);
352         }
353  
354         scd.setChatUserName(name);
355         scd.setChatTopicName(topicName);
356         scd.show();
357     }
358  
359     /*
360      * Performs the actual chat connect.
361      * The createChatSession() method does the real work
362      * here, creating:
363      *          TopicConnection
364      *          TopicSession
365      *          Topic
366      *          TopicSubscriber
367      *          TopicPublisher
368      */
369     private void doConnect()  {
370         if (connectedToChatSession())
371             return;
372  
373         outgoingMsgCreator = getMessageCreator(outgoingMsgType);
374  
375         if (createChatSession(topicName) == false) {
376             errorMessage("Unable to create Chat session.  " +
377                          "Please verify a broker is running");
378             return;
379         }
380         setConnectedToChatSession(true);
381  
382         connectItem.setEnabled(false);
383         disconnectItem.setEnabled(true);
384  
385         scp.setUserName(name);
386         scp.setDestName(topicName);
387         scp.setMsgType(outgoingMsgTypeString);
388         scp.setHostName(hostName);
389         scp.setEnabled(true);
390     }
391  
392     /*
393      * Disconnects from chat session.
394      * destroyChatSession() performs the JMS cleanup.
395      */
396     private void doDisconnect()  {
397         if (!connectedToChatSession())
398             return;
399  
400         destroyChatSession();
401  
402         setConnectedToChatSession(false);
403  
404         connectItem.setEnabled(true);
405         disconnectItem.setEnabled(false);
406         scp.setEnabled(false);
407     }
408  
409     /*
410      * These methods set/return a flag that indicates
411      * whether the application is currently involved in
412      * a chat session.
413      */
414     private void setConnectedToChatSession(boolean b)  {
415         connected = b;
416     }
417     private boolean connectedToChatSession()  {
418         return (connected);
419     }
420  
421     /*
422      * Exit application. Does some cleanup if
423      * necessary.
424      */
425     private void exit()  {
426         doDisconnect();
427         System.exit(0);
428     }
429  
430     /*
431      * Create the application GUI.
432      */
433     private void initGui() {
434  
435         frame = new Frame("Simple Chat");
436  
437         frame.addWindowListener(this);
438  
439         MenuBar menubar = createMenuBar();
440  
441         frame.setMenuBar(menubar);
442  
443         scp = new SimpleChatPanel();
444         scp.setUserName(name);
445         scp.setDestName(topicName);
446         scp.setHostName(hostName);
447         sendB = scp.getSendButton();
448         sendB.addActionListener(this);
449  
450         frame.add(scp);
451         frame.pack();
452         frame.setVisible(true);
453  
454         scp.setEnabled(false);
455     }
456  
457     /*
458      * Create menubar for application.
459      */
460     private MenuBar createMenuBar() {
461         MenuBar mb = new MenuBar();
462         Menu chatMenu;
463  
464         chatMenu = (Menu) mb.add(new Menu("Chat"));
465         connectItem = (MenuItem) chatMenu.add(new MenuItem("Connect ..."));
466         disconnectItem = (MenuItem) chatMenu.add(new MenuItem("Disconnect"));
467         clearItem = (MenuItem) chatMenu.add(new MenuItem("Clear Messages"));
468         exitItem = (MenuItem) chatMenu.add(new MenuItem("Exit"));
469  
470         disconnectItem.setEnabled(false);
471  
472         connectItem.addActionListener(this);
473         disconnectItem.addActionListener(this);
474         clearItem.addActionListener(this);
475         exitItem.addActionListener(this);
476  
477         return (mb);
478     }
479  
480     /*
481      * Send message using text that is currently in the SimpleChatPanel
482      * object. The text message is obtained via scp.getMessage()
483      *
484      * An object of type ChatObjMessage is created containing the typed
485      * text. A JMS ObjectMessage is used to encapsulate this ChatObjMessage
486      * object.
487      */
488     private void sendNormalMessage()  {
489         Message         msg;
490  
491         if (!connectedToChatSession())  {
492             errorMessage("Cannot send message: Not connected to chat session!");
493  
494             return;
495         }
496  
497         try  {
498             msg = outgoingMsgCreator.createChatMessage(topicSession,
499                                         name,
500                                         SimpleChatMessageTypes.NORMAL,
501                                         scp.getMessage());
502  
503             topicPublisher.publish(msg);
504             scp.setMessage("");
505             scp.requestFocus();
506         } catch (Exception ex)  {
507             errorMessage("Caught exception while sending NORMAL message: " + ex);
508         }
509     }
510  
511     /*
512      * Send a message to the chat session to inform people
513      * we just joined the chat.
514      */
515     private void sendJoinMessage()  {
516         Message         msg;
517  
518         try  {
519             msg = outgoingMsgCreator.createChatMessage(topicSession,
520                                         name,
521                                         SimpleChatMessageTypes.JOIN,
522                                         null);
523  
524             topicPublisher.publish(msg);
525         } catch (Exception ex)  {
526             errorMessage("Caught exception while sending JOIN message: " + ex);
527         }
528     }
529     /*
530      * Send a message to the chat session to inform people
531      * we are leaving the chat.
532      */
533     private void sendLeaveMessage()  {
534         Message         msg;
535  
536         try  {
537             msg = outgoingMsgCreator.createChatMessage(topicSession,
538                                         name,
539                                         SimpleChatMessageTypes.LEAVE,
540                                         null);
541  
542             topicPublisher.publish(msg);
543         } catch (Exception ex)  {
544             errorMessage("Caught exception while sending LEAVE message: " + ex);
545         }
546     }
547  
548     /*
549      * JMS initialization.
550      * This is simply creating the TopicConnectionFactory.
551      */
552     private void initJms(String args[]) {
553         /* XXX: chg for JMS1.1 to use BasicConnectionFactory for non-JNDI useage
554          * remove --- Use BasicTopicConnectionFactory directly - no JNDI
555         */
556         try  {
557             topicConnectionFactory
558                 = new com.sun.messaging.TopicConnectionFactory();
559         } catch (Exception e)  {
560             errorMessage("Caught Exception: " + e);
561         }
562     }
563  
564     /*
565      * Create 'chat session'. This involves creating:
566      *          TopicConnection
567      *          TopicSession
568      *          Topic
569      *          TopicSubscriber
570      *          TopicPublisher
571      */
572     private boolean createChatSession(String topicStr) {
573         try  {
574             /*
575              * Create the connection...
576              *
577             */
578             topicConnection = topicConnectionFactory.createTopicConnection();
579  
580             /*
581              * Not transacted
582              * Auto acknowledegement
583              */
584             topicSession = topicConnection.createTopicSession(false,
585                                                 Session.AUTO_ACKNOWLEDGE);
586  
587             topic = topicSession.createTopic(topicStr);
588             topicPublisher = topicSession.createPublisher(topic);
589             /*
590              * Non persistent delivery
591              */
592             topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
593             topicSubscriber = topicSession.createSubscriber(topic);
594             topicSubscriber.setMessageListener(this);
595  
596             topicConnection.start();
597  
598             sendJoinMessage();
599  
600             return true;
601  
602         } catch (Exception e)  {
603             errorMessage("Caught Exception: " + e);
604             e.printStackTrace();
605             return false;
606         }
607     }
608     /*
609      * Destroy/close 'chat session'.
610      */
611     private void destroyChatSession()  {
612         try  {
613             sendLeaveMessage();
614  
615             topicSubscriber.close();
616             topicPublisher.close();
617             topicSession.close();
618             topicConnection.close();
619  
620             topic = null;
621             topicSubscriber = null;
622             topicPublisher = null;
623             topicSession = null;
624             topicConnection = null;
625  
626         } catch (Exception e)  {
627             errorMessage("Caught Exception: " + e);
628         }
629  
630     }
631  
632     /*
633      * Display error. Right now all we do is dump to
634      * stderr.
635      */
636     private void errorMessage(String s)  {
637         System.err.println(s);
638     }
639  
640  
641 }
642  
643 /**
644  * This class provides the bulk of the UI:
645  *      sendMsgTA       TextArea for typing messages to send
646  *      msgsTA          TextArea for displaying messages in chat
647  *      sendB           Send button for activating a message 'Send'.
648  *
649  *      ...and various labels to indicate the chat topic name,
650  *      the user name, and host name.
651  *
652  */
653 class SimpleChatPanel extends Panel implements SimpleChatMessageTypes  {
654     private String      destName,
655                         userName,
656                         msgType,
657                         hostName;
658  
659     private Button      sendB;
660  
661     private Label       destLabel, userLabel, msgTypeLabel, msgsLabel,
662                         sendMsgLabel;
663  
664     private TextArea    msgsTA;
665  
666     private TextArea    sendMsgTA;
667  
668     /**
669      * SimpleChatPanel constructor
670      */
671     public SimpleChatPanel()  {
672         init();
673     }
674  
675     /**
676      * Set the chat username
677      * @param userName Chat userName
678      */
679     public void setUserName(String userName)  {
680         this.userName = userName;
681         userLabel.setText("User Id: " + userName);
682         sendB.setLabel("Send Message as " + userName);
683     }
684     /**
685      * Set the chat hostname. This is pretty much
686      * the host that the router is running on.
687      * @param hostName Chat hostName
688      */
689     public void setHostName(String hostName)  {
690         this.hostName = hostName;
691     }
692     /**
693      * Sets the topic name.
694      * @param destName Chat topic name
695      */
696     public void setDestName(String destName)  {
697         this.destName = destName;
698         destLabel.setText("Topic: " + destName);
699     }
700  
701     public void setMsgType(String msgType)  {
702         this.msgType = msgType;
703         msgTypeLabel.setText("Outgoing Msg Type: " + msgType);
704     }
705  
706     /**
707      * Returns the 'Send' button.
708      */
709     public Button getSendButton()  {
710         return(sendB);
711     }
712  
713     /**
714      * Clears the chat message text area.
715      */
716     public void clear()  {
717         msgsTA.setText("");
718     }
719  
720     /**
721      * Appends the passed message to the chat message text area.
722      * @param msg Message to display
723      */
724     public void newMessage(String sender, int type, String text)  {
725         switch (type)  {
726         case NORMAL:
727             msgsTA.append(sender +  ": " + text + "\n");
728         break;
729  
730         case JOIN:
731             msgsTA.append("*** " +  sender +  " has joined chat session\n");
732         break;
733  
734         case LEAVE:
735             msgsTA.append("*** " +  sender +  " has left chat session\n");
736         break;
737  
738         default:
739         }
740     }
741  
742     /**
743      * Sets the string to display on the chat message textarea
744      * @param s String to display
745      */
746     public void setMessage(String s)  {
747         sendMsgTA.setText(s);
748     }
749     /**
750      * Returns the contents of the chat message textarea
751      */
752     public String getMessage()  {
753         return (sendMsgTA.getText());
754     }
755  
756     /*
757      * Init chat panel GUI elements.
758      */
759     private void init()  {
760  
761         Panel   dummyPanel;
762  
763         setLayout(new BorderLayout(0, 0));
764  
765         destLabel = new Label("Topic:");
766  
767         userLabel = new Label("User Id: ");
768  
769         msgTypeLabel = new Label("Outgoing Msg Type:");
770  
771  
772  
773         dummyPanel = new Panel();
774         dummyPanel.setLayout(new BorderLayout(0, 0));
775         dummyPanel.add("North", destLabel);
776         dummyPanel.add("Center", userLabel);
777         dummyPanel.add("South", msgTypeLabel);
778         add("North", dummyPanel);
779  
780         dummyPanel = new Panel();
781         dummyPanel.setLayout(new BorderLayout(0, 0));
782         msgsLabel = new Label("Messages in chat:");
783         msgsTA = new TextArea(15, 40);
784         msgsTA.setEditable(false);
785  
786         dummyPanel.add("North", msgsLabel);
787         dummyPanel.add("Center", msgsTA);
788         add("Center", dummyPanel);
789  
790         dummyPanel = new Panel();
791         dummyPanel.setLayout(new BorderLayout(0, 0));
792         sendMsgLabel = new Label("Type Message:");
793         sendMsgTA = new TextArea(5, 40);
794         sendB = new Button("Send Message");
795         dummyPanel.add("North", sendMsgLabel);
796         dummyPanel.add("Center", sendMsgTA);
797         dummyPanel.add("South", sendB);
798         add("South", dummyPanel);
799     }
800 }
801  
802 /**
803  * Dialog for querying the chat user name and chat topic.
804  *
805  */
806 class SimpleChatDialog extends Dialog  {
807  
808     public final static int     MSG_TYPE_UNDEFINED      = -1;
809     public final static int     MSG_TYPE_OBJECT         = 0;
810     public final static int     MSG_TYPE_TEXT           = 1;
811     public final static int     MSG_TYPE_MAP            = 2;
812     public final static int     MSG_TYPE_BYTES          = 3;
813     public final static int     MSG_TYPE_STREAM         = 4;
814  
815     private TextField   nameF, topicF;
816     private Choice      msgTypeChoice;
817     private Button      connectB, cancelB;
818  
819     /**
820      * SimpleChatDialog constructor.
821      * @param f Parent frame.
822      */
823     public SimpleChatDialog(Frame f)  {
824         super(f, "Simple Chat: Connect information", true);
825         init();
826         setResizable(false);
827     }
828  
829     /**
830      * Return 'Connect' button
831      */
832     public Button getConnectButton()  {
833         return (connectB);
834     }
835     /**
836      * Return 'Cancel' button
837      */
838     public Button getCancelButton()  {
839         return (cancelB);
840     }
841  
842     /**
843      * Return chat user name entered.
844      */
845     public String getChatUserName()  {
846         if (nameF == null)
847             return (null);
848         return (nameF.getText());
849     }
850     /**
851      * Set chat user name.
852      * @param s chat user name
853      */
854     public void setChatUserName(String s)  {
855         if (nameF == null)
856             return;
857         nameF.setText(s);
858     }
859  
860     /**
861      * Set chat topic
862      * @param s chat topic
863      */
864     public void setChatTopicName(String s)  {
865         if (topicF == null)
866             return;
867         topicF.setText(s);
868     }
869     /**
870      * Return chat topic
871      */
872     public String getChatTopicName()  {
873         if (topicF == null)
874             return (null);
875         return (topicF.getText());
876     }
877  
878     /*
879      * Get message type
880      */
881     public int getMsgType()  {
882         if (msgTypeChoice == null)
883             return (MSG_TYPE_UNDEFINED);
884         return (msgTypeChoice.getSelectedIndex());
885     }
886  
887     public String getMsgTypeString()  {
888         if (msgTypeChoice == null)
889             return (null);
890         return (msgTypeChoice.getSelectedItem());
891     }
892  
893     /*
894      * Init GUI elements.
895      */
896     private void init()  {
897         Panel                   p, dummyPanel, labelPanel, valuePanel;
898         GridBagLayout           labelGbag, valueGbag;
899         GridBagConstraints      labelConstraints, valueConstraints;
900         Label                   chatNameLabel, chatTopicLabel,
901                                 msgTypeLabel;
902         int                     i, j;
903  
904         p = new Panel();
905         p.setLayout(new BorderLayout());
906  
907         dummyPanel = new Panel();
908         dummyPanel.setLayout(new BorderLayout());
909  
910         /***/
911         labelPanel = new Panel();
912         labelGbag = new GridBagLayout();
913         labelConstraints = new GridBagConstraints();
914         labelPanel.setLayout(labelGbag);
915         j = 0;
916  
917         valuePanel = new Panel();
918         valueGbag = new GridBagLayout();
919         valueConstraints = new GridBagConstraints();
920         valuePanel.setLayout(valueGbag);
921         i = 0;
922  
923         chatNameLabel = new Label("Chat User Name:", Label.RIGHT);
924         chatTopicLabel = new Label("Chat Topic:", Label.RIGHT);
925         msgTypeLabel = new Label("Outgoing Msg Type:", Label.RIGHT);
926  
927         labelConstraints.gridx = 0;
928         labelConstraints.gridy = j++;
929         labelConstraints.weightx = 1.0;
930         labelConstraints.weighty = 1.0;
931         labelConstraints.anchor = GridBagConstraints.EAST;
932         labelGbag.setConstraints(chatNameLabel, labelConstraints);
933         labelPanel.add(chatNameLabel);
934  
935         labelConstraints.gridy = j++;
936         labelGbag.setConstraints(chatTopicLabel, labelConstraints);
937         labelPanel.add(chatTopicLabel);
938  
939         labelConstraints.gridy = j++;
940         labelGbag.setConstraints(msgTypeLabel, labelConstraints);
941         labelPanel.add(msgTypeLabel);
942  
943         nameF = new TextField(20);
944         topicF = new TextField(20);
945         msgTypeChoice = new Choice();
946         msgTypeChoice.insert("ObjectMessage", MSG_TYPE_OBJECT);
947         msgTypeChoice.insert("TextMessage", MSG_TYPE_TEXT);
948         msgTypeChoice.insert("MapMessage", MSG_TYPE_MAP);
949         msgTypeChoice.insert("BytesMessage", MSG_TYPE_BYTES);
950         msgTypeChoice.insert("StreamMessage", MSG_TYPE_STREAM);
951         msgTypeChoice.select(MSG_TYPE_STREAM);
952  
953         valueConstraints.gridx = 0;
954         valueConstraints.gridy = i++;
955         valueConstraints.weightx = 1.0;
956         valueConstraints.weighty = 1.0;
957         valueConstraints.anchor = GridBagConstraints.WEST;
958         valueGbag.setConstraints(nameF, valueConstraints);
959         valuePanel.add(nameF);
960  
961         valueConstraints.gridy = i++;
962         valueGbag.setConstraints(topicF, valueConstraints);
963         valuePanel.add(topicF);
964  
965         valueConstraints.gridy = i++;
966         valueGbag.setConstraints(msgTypeChoice, valueConstraints);
967         valuePanel.add(msgTypeChoice);
968  
969         dummyPanel.add("West", labelPanel);
970         dummyPanel.add("Center", valuePanel);
971         /***/
972  
973         p.add("North", dummyPanel);
974  
975         dummyPanel = new Panel();
976         connectB = new Button("Connect");
977         cancelB = new Button("Cancel");
978         dummyPanel.add(connectB);
979         dummyPanel.add(cancelB);
980  
981         p.add("South", dummyPanel);
982  
983         add(p);
984         pack();
985     }
986 }
987  
988 interface SimpleChatMessageTypes  {
989     public static int   JOIN    = 0;
990     public static int   NORMAL  = 1;
991     public static int   LEAVE   = 2;
992     public static int   BADTYPE = -1;
993 }
994  
995 interface SimpleChatMessageCreator  {
996     public Message createChatMessage(Session session, String sender,
997                                         int type, String text);
998     public boolean isUsable(Message msg);
999     public int getChatMessageType(Message msg);
1000     public String getChatMessageSender(Message msg);
1001     public String getChatMessageText(Message msg);
1002 }
1003  
1004 class SimpleChatTextMessageCreator implements
1005                         SimpleChatMessageCreator, SimpleChatMessageTypes  {
1006     private static String MSG_SENDER_PROPNAME = "SIMPLECHAT_MSG_SENDER";
1007     private static String MSG_TYPE_PROPNAME =   "SIMPLECHAT_MSG_TYPE";
1008  
1009     public Message createChatMessage(Session session, String sender,
1010                                         int type, String text)  {
1011         TextMessage             txtMsg = null;
1012  
1013         try  {
1014             txtMsg = session.createTextMessage();
1015             txtMsg.setStringProperty(MSG_SENDER_PROPNAME, sender);
1016             txtMsg.setIntProperty(MSG_TYPE_PROPNAME, type);
1017             txtMsg.setText(text);
1018         } catch (Exception ex)  {
1019             System.err.println("Caught exception while creating message: " + ex);
1020         }
1021  
1022         return (txtMsg);
1023     }
1024  
1025     public boolean isUsable(Message msg)  {
1026         if (msg instanceof TextMessage)  {
1027             return (true);
1028         }
1029  
1030         return (false);
1031     }
1032  
1033     public int getChatMessageType(Message msg)  {
1034         int     type = BADTYPE;
1035  
1036         try  {
1037             TextMessage txtMsg = (TextMessage)msg;
1038             type = txtMsg.getIntProperty(MSG_TYPE_PROPNAME);
1039         } catch (Exception ex)  {
1040             System.err.println("Caught exception: " + ex);
1041         }
1042  
1043         return (type);
1044     }
1045  
1046     public String getChatMessageSender(Message msg)  {
1047         String  sender = null;
1048  
1049         try  {
1050             TextMessage txtMsg = (TextMessage)msg;
1051             sender = txtMsg.getStringProperty(MSG_SENDER_PROPNAME);
1052         } catch (Exception ex)  {
1053             System.err.println("Caught exception: " + ex);
1054         }
1055  
1056         return (sender);
1057     }
1058  
1059     public String getChatMessageText(Message msg)  {
1060         String  text = null;
1061  
1062         try  {
1063             TextMessage txtMsg = (TextMessage)msg;
1064             text = txtMsg.getText();
1065         } catch (Exception ex)  {
1066             System.err.println("Caught exception: " + ex);
1067         }
1068  
1069         return (text);
1070     }
1071 }
1072  
1073 class SimpleChatObjMessageCreator implements
1074                 SimpleChatMessageCreator, SimpleChatMessageTypes  {
1075     public Message createChatMessage(Session session, String sender,
1076                                         int type, String text)  {
1077         ObjectMessage           objMsg = null;
1078         ChatObjMessage  sMsg;
1079  
1080         try  {
1081             objMsg = session.createObjectMessage();
1082             sMsg = new ChatObjMessage(sender, type, text);
1083             objMsg.setObject(sMsg);
1084         } catch (Exception ex)  {
1085             System.err.println("Caught exception while creating message: " + ex);
1086         }
1087  
1088         return (objMsg);
1089     }
1090  
1091     public boolean isUsable(Message msg)  {
1092         try  {
1093             ChatObjMessage      sMsg = getSimpleChatMessage(msg);
1094             if (sMsg == null)  {
1095                 return (false);
1096             }
1097         } catch (Exception ex)  {
1098             System.err.println("Caught exception: " + ex);
1099         }
1100  
1101         return (true);
1102     }
1103  
1104     public int getChatMessageType(Message msg)  {
1105         int     type = BADTYPE;
1106  
1107         try  {
1108             ChatObjMessage      sMsg = getSimpleChatMessage(msg);
1109             if (sMsg != null)  {
1110                 type = sMsg.getType();
1111             }
1112         } catch (Exception ex)  {
1113             System.err.println("Caught exception: " + ex);
1114         }
1115  
1116         return (type);
1117     }
1118  
1119     public String getChatMessageSender(Message msg)  {
1120         String          sender = null;
1121  
1122         try  {
1123             ChatObjMessage      sMsg = getSimpleChatMessage(msg);
1124             if (sMsg != null)  {
1125                 sender = sMsg.getSender();
1126             }
1127         } catch (Exception ex)  {
1128             System.err.println("Caught exception: " + ex);
1129         }
1130  
1131         return (sender);
1132     }
1133  
1134     public String getChatMessageText(Message msg)  {
1135         String                  text = null;
1136  
1137         try  {
1138             ChatObjMessage      sMsg = getSimpleChatMessage(msg);
1139             if (sMsg != null)  {
1140                 text = sMsg.getMessage();
1141             }
1142         } catch (Exception ex)  {
1143             System.err.println("Caught exception: " + ex);
1144         }
1145  
1146         return (text);
1147     }
1148  
1149     private ChatObjMessage getSimpleChatMessage(Message msg)  {
1150         ObjectMessage           objMsg;
1151         ChatObjMessage  sMsg = null;
1152  
1153         if (!(msg instanceof ObjectMessage))  {
1154             System.err.println("SimpleChatObjMessageCreator: Message received not of type ObjectMessage!");
1155             return (null);
1156         }
1157  
1158         objMsg = (ObjectMessage)msg;
1159  
1160         try  {
1161             sMsg = (ChatObjMessage)objMsg.getObject();
1162         } catch (Exception ex)  {
1163             System.err.println("Caught exception: " + ex);
1164         }
1165  
1166         return (sMsg);
1167     }
1168 }
1169  
1170 class SimpleChatMapMessageCreator implements
1171                         SimpleChatMessageCreator, SimpleChatMessageTypes  {
1172     private static String MAPMSG_SENDER_PROPNAME =      "SIMPLECHAT_MAPMSG_SENDER";
1173     private static String MAPMSG_TYPE_PROPNAME =        "SIMPLECHAT_MAPMSG_TYPE";
1174     private static String MAPMSG_TEXT_PROPNAME =        "SIMPLECHAT_MAPMSG_TEXT";
1175  
1176     public Message createChatMessage(Session session, String sender,
1177                                         int type, String text)  {
1178         MapMessage              mapMsg = null;
1179  
1180         try  {
1181             mapMsg = session.createMapMessage();
1182             mapMsg.setInt(MAPMSG_TYPE_PROPNAME, type);
1183             mapMsg.setString(MAPMSG_SENDER_PROPNAME, sender);
1184             mapMsg.setString(MAPMSG_TEXT_PROPNAME, text);
1185         } catch (Exception ex)  {
1186             System.err.println("Caught exception while creating message: " + ex);
1187         }
1188  
1189         return (mapMsg);
1190     }
1191  
1192     public boolean isUsable(Message msg)  {
1193         if (msg instanceof MapMessage)  {
1194             return (true);
1195         }
1196  
1197         return (false);
1198     }
1199  
1200     public int getChatMessageType(Message msg)  {
1201         int     type = BADTYPE;
1202  
1203         try  {
1204             MapMessage  mapMsg = (MapMessage)msg;
1205             type = mapMsg.getInt(MAPMSG_TYPE_PROPNAME);
1206         } catch (Exception ex)  {
1207             System.err.println("Caught exception: " + ex);
1208         }
1209  
1210         return (type);
1211     }
1212  
1213     public String getChatMessageSender(Message msg)  {
1214         String  sender = null;
1215  
1216         try  {
1217             MapMessage  mapMsg = (MapMessage)msg;
1218             sender = mapMsg.getString(MAPMSG_SENDER_PROPNAME);
1219         } catch (Exception ex)  {
1220             System.err.println("Caught exception: " + ex);
1221         }
1222  
1223         return (sender);
1224     }
1225  
1226     public String getChatMessageText(Message msg)  {
1227         String  text = null;
1228  
1229         try  {
1230             MapMessage  mapMsg = (MapMessage)msg;
1231             text = mapMsg.getString(MAPMSG_TEXT_PROPNAME);
1232         } catch (Exception ex)  {
1233             System.err.println("Caught exception: " + ex);
1234         }
1235  
1236         return (text);
1237     }
1238 }
1239  
1240 class SimpleChatBytesMessageCreator implements
1241                         SimpleChatMessageCreator, SimpleChatMessageTypes  {
1242  
1243     public Message createChatMessage(Session session, String sender,
1244                                         int type, String text)  {
1245         BytesMessage            bytesMsg = null;
1246  
1247         try  {
1248             byte        b[];
1249  
1250             bytesMsg = session.createBytesMessage();
1251             bytesMsg.writeInt(type);
1252             /*
1253              * Write length of sender and text strings
1254              */
1255             b = sender.getBytes();
1256             bytesMsg.writeInt(b.length);
1257             bytesMsg.writeBytes(b);
1258  
1259             if (text != null)  {
1260                 b = text.getBytes();
1261                 bytesMsg.writeInt(b.length);
1262                 bytesMsg.writeBytes(b);
1263             } else  {
1264                 bytesMsg.writeInt(0);
1265             }
1266         } catch (Exception ex)  {
1267             System.err.println("Caught exception while creating message: " + ex);
1268         }
1269  
1270         return (bytesMsg);
1271     }
1272  
1273     public boolean isUsable(Message msg)  {
1274         if (msg instanceof BytesMessage)  {
1275             return (true);
1276         }
1277  
1278         return (false);
1279     }
1280  
1281     public int getChatMessageType(Message msg)  {
1282         int     type = BADTYPE;
1283  
1284         try  {
1285             BytesMessage        bytesMsg = (BytesMessage)msg;
1286             type = bytesMsg.readInt();
1287         } catch (Exception ex)  {
1288             System.err.println("Caught exception: " + ex);
1289         }
1290  
1291         return (type);
1292     }
1293  
1294     public String getChatMessageSender(Message msg)  {
1295         String  sender = null;
1296  
1297         sender = readSizeFetchString(msg);
1298  
1299         return (sender);
1300     }
1301  
1302     public String getChatMessageText(Message msg)  {
1303         String  text = null;
1304  
1305         text = readSizeFetchString(msg);
1306  
1307         return (text);
1308     }
1309  
1310     private String readSizeFetchString(Message msg)  {
1311         String  stringData = null;
1312  
1313         try  {
1314             BytesMessage        bytesMsg = (BytesMessage)msg;
1315             int                 length, needToRead;
1316             byte                b[];
1317  
1318             length = bytesMsg.readInt();
1319  
1320             if (length == 0)  {
1321                 return ("");
1322             }
1323  
1324             b = new byte [length];
1325  
1326             /*
1327              * Loop to keep reading until all the bytes are read in
1328              */
1329             needToRead = length;
1330             while (needToRead > 0)  {
1331                 byte tmpBuf[] = new byte [needToRead];
1332                 int ret = bytesMsg.readBytes(tmpBuf);
1333                 if (ret > 0)  {
1334                     for (int i=0; i < ret; ++i)  {
1335                         b[b.length - needToRead +i] = tmpBuf[i];
1336                     }
1337                     needToRead -= ret;
1338                 }
1339             }
1340  
1341             stringData = new String(b);
1342         } catch (Exception ex)  {
1343             System.err.println("Caught exception: " + ex);
1344         }
1345  
1346         return (stringData);
1347     }
1348 }
1349  
1350 class SimpleChatStreamMessageCreator implements
1351                         SimpleChatMessageCreator, SimpleChatMessageTypes  {
1352  
1353     public Message createChatMessage(Session session, String sender,
1354                                         int type, String text)  {
1355         StreamMessage           streamMsg = null;
1356  
1357         try  {
1358             byte        b[];
1359  
1360             streamMsg = session.createStreamMessage();
1361             streamMsg.writeInt(type);
1362             streamMsg.writeString(sender);
1363  
1364             if (text == null)  {
1365                 text = "";
1366             }
1367             streamMsg.writeString(text);
1368         } catch (Exception ex)  {
1369             System.err.println("Caught exception while creating message: " + ex);
1370         }
1371  
1372         return (streamMsg);
1373     }
1374  
1375     public boolean isUsable(Message msg)  {
1376         if (msg instanceof StreamMessage)  {
1377             return (true);
1378         }
1379  
1380         return (false);
1381     }
1382  
1383     public int getChatMessageType(Message msg)  {
1384         int     type = BADTYPE;
1385  
1386         try  {
1387             StreamMessage       streamMsg = (StreamMessage)msg;
1388             type = streamMsg.readInt();
1389         } catch (Exception ex)  {
1390             System.err.println("getChatMessageType(): Caught exception: " + ex);
1391         }
1392  
1393         return (type);
1394     }
1395  
1396     public String getChatMessageSender(Message msg)  {
1397         String  sender = null;
1398  
1399         try  {
1400             StreamMessage       streamMsg = (StreamMessage)msg;
1401             sender = streamMsg.readString();
1402         } catch (Exception ex)  {
1403             System.err.println("getChatMessageSender(): Caught exception: " + ex);
1404         }
1405  
1406         return (sender);
1407     }
1408  
1409     public String getChatMessageText(Message msg)  {
1410         String  text = null;
1411  
1412         try  {
1413             StreamMessage       streamMsg = (StreamMessage)msg;
1414             text = streamMsg.readString();
1415         } catch (Exception ex)  {
1416             System.err.println("getChatMessageText(): Caught exception: " + ex);
1417         }
1418  
1419         return (text);
1420     }
1421  
1422 }
1423  
1424  
1425  
1426  
1427 /**
1428  * Object representing a message sent by chat application.
1429  * We use this class and wrap a javax.jms.ObjectMessage
1430  * around it instead of using a javax.jms.TextMessage
1431  * because a simple string is not sufficient. We want
1432  * be able to to indicate that a message is one of these
1433  * types:
1434  *      join message    ('Hi, I just joined')
1435  *      regular message (For regular chat messages)
1436  *      leave message   ('Bye, I'm leaving')
1437  *
1438  */
1439 class ChatObjMessage implements java.io.Serializable, SimpleChatMessageTypes  {
1440     private int         type = NORMAL;
1441     private String      sender,
1442                         message;
1443  
1444     /**
1445      * ChatObjMessage constructor. Construct a message with the given
1446      * sender and message.
1447      * @param sender Message sender
1448      * @param type Message type
1449      * @param message The message to send
1450      */
1451     public ChatObjMessage(String sender, int type, String message)  {
1452         this.sender = sender;
1453         this.type = type;
1454         this.message = message;
1455     }
1456  
1457     /**
1458      * Returns message sender.
1459      */
1460     public String getSender()  {
1461         return (sender);
1462     }
1463  
1464     /**
1465      * Returns message type
1466      */
1467     public int getType()  {
1468         return (type);
1469     }
1470  
1471     /**
1472      * Sets the message string
1473      * @param message The message string
1474      */
1475     public void setMessage(String message)  {
1476         this.message = message;
1477     }
1478     /**
1479      * Returns the message string
1480      */
1481     public String getMessage()  {
1482         return (message);
1483     }
1484 }