KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sample > jms > topics > Chat


1 package sample.jms.topics.Chat;
2
3 /*
4  * Copyright 2002 by
5  * <a HREF="http://www.coridan.com">Coridan</a>
6  * <a HREF="mailto: support@coridan.com ">support@coridan.com</a>
7  *
8  * The contents of this file are subject to the Mozilla Public License Version
9  * 1.1 (the "License"); you may not use this file except in compliance with the
10  * License. You may obtain a copy of the License at
11  * http://www.mozilla.org/MPL/
12  *
13  * Software distributed under the License is distributed on an "AS IS" basis,
14  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
15  * for the specific language governing rights and limitations under the
16  * License.
17  *
18  * The Original Code is "MantaRay" (TM).
19  *
20  * The Initial Developer of the Original Code is Coridan.
21  * Portions created by the Initial Developer are Copyright (C) 2006
22  * Coridan Inc. All Rights Reserved.
23  *
24  * Contributor(s): all the names of the contributors are added in the source
25  * code where applicable.
26  *
27  * Alternatively, the contents of this file may be used under the terms of the
28  * LGPL license (the "GNU LESSER GENERAL PUBLIC LICENSE"), in which case the
29  * provisions of LGPL are applicable instead of those above. If you wish to
30  * allow use of your version of this file only under the terms of the LGPL
31  * License and not to allow others to use your version of this file under
32  * the MPL, indicate your decision by deleting the provisions above and
33  * replace them with the notice and other provisions required by the LGPL.
34  * If you do not delete the provisions above, a recipient may use your version
35  * of this file under either the MPL or the GNU LESSER GENERAL PUBLIC LICENSE.
36  
37  *
38  * This library is free software; you can redistribute it and/or modify it
39  * under the terms of the MPL as stated above or under the terms of the GNU
40  * Lesser General Public License as published by the Free Software Foundation;
41  * either version 2.1 of the License, or any later version.
42  *
43  * This library is distributed in the hope that it will be useful, but WITHOUT
44  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
45  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
46  * License for more details.
47  */

48
49
50 /*==============================================================================
51   For instructions on how to run this sample please refer to the file
52   sample\jms\topics\Chat\Readme.txt under the MantaRay installation directory.
53 ==============================================================================*/

54
55
56 import java.io.InputStreamReader JavaDoc;
57
58 import javax.jms.Session JavaDoc;
59 import javax.jms.TopicConnectionFactory JavaDoc;
60
61 import org.mr.api.jms.MantaTopicConnectionFactory;
62
63
64 public class Chat
65     implements javax.jms.MessageListener JavaDoc
66 {
67     private static final int MESSAGE_TTL = 6000000;
68
69     static int counter = 0;
70     private javax.jms.TopicConnection JavaDoc connect = null;
71     private javax.jms.TopicSession JavaDoc pubSession = null;
72     private javax.jms.TopicSession JavaDoc subSession = null;
73     private javax.jms.TopicPublisher JavaDoc publisher = null;
74
75     /** Create JMS client for publishing and subscribing to messages. */
76     private void chatter(String JavaDoc username, String JavaDoc chatTopic) {
77         // Create a connection.
78
try {
79             TopicConnectionFactory JavaDoc factory;
80             factory = new MantaTopicConnectionFactory();
81             connect = factory.createTopicConnection();
82             pubSession =
83                 connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
84             subSession =
85                 connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
86         } catch (javax.jms.JMSException JavaDoc jmse) {
87             System.err.println("error while creating connection - " +
88                                jmse.toString());
89             jmse.printStackTrace();
90             System.exit(1);
91         }
92
93         // Create Publisher and Subscriber to 'chat' topics
94
try {
95             javax.jms.Topic JavaDoc topic = pubSession.createTopic(chatTopic);
96             javax.jms.TopicSubscriber JavaDoc subscriber = subSession.createSubscriber(topic);
97             subscriber.setMessageListener(this);
98             publisher = pubSession.createPublisher(topic);
99             // Now that setup is complete, start the Connection
100
connect.start();
101         } catch (javax.jms.JMSException JavaDoc jmse) {
102             jmse.printStackTrace();
103         }
104
105         try {
106             // Read all standard input and send it as a message.
107
java.io.BufferedReader JavaDoc stdin =
108                 new java.io.BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
109             System.out.println("\nEnter text messages to clients that " +
110                                "subscribe to the " + chatTopic + " topic." +
111                                "\nPress Enter to publish each message.\n");
112             while (true) {
113                 String JavaDoc s = stdin.readLine();
114
115                 if (s == null)
116                     exit();
117                 else if (s.length() > 0) {
118                     javax.jms.TextMessage JavaDoc msg = pubSession.createTextMessage();
119                     msg.setText(username + ": " + s);
120                     publisher.publish(msg,
121                                       javax.jms.DeliveryMode.NON_PERSISTENT,
122                                       javax.jms.Message.DEFAULT_PRIORITY,
123                                       MESSAGE_TTL);
124                 }
125             }
126         }
127         catch (java.io.IOException JavaDoc ioe) {
128             ioe.printStackTrace();
129         } catch (javax.jms.JMSException JavaDoc jmse) {
130             jmse.printStackTrace();
131         }
132     }
133
134     /**
135      * Handle the message
136      * (as specified in the javax.jms.MessageListener interface).
137      */

138     public void onMessage(javax.jms.Message JavaDoc aMessage)
139     {
140         try {
141             // Cast the message as a text message.
142
javax.jms.TextMessage JavaDoc textMessage =
143                 (javax.jms.TextMessage JavaDoc) aMessage;
144
145             // This handler reads a single String from the
146
// message and prints it to the standard output.
147
try {
148                 String JavaDoc string = textMessage.getText();
149                 System.out.println(string);
150             } catch (javax.jms.JMSException JavaDoc jmse) {
151                 jmse.printStackTrace();
152             }
153         } catch (java.lang.RuntimeException JavaDoc rte) {
154             rte.printStackTrace();
155         }
156     }
157
158     /** Cleanup resources and then exit. */
159     private void exit()
160     {
161         try {
162             connect.close();
163         } catch (javax.jms.JMSException JavaDoc jmse) {
164             jmse.printStackTrace();
165         }
166
167         System.exit(0);
168     }
169
170     //
171
// NOTE: the remainder of this sample deals with reading arguments
172
// and does not utilize any JMS classes or code.
173
//
174

175     /** Main program entry point. */
176     public static void main(String JavaDoc argv[]) {
177
178         // Is there anything to do?
179
if (argv.length == 0) {
180             printUsage();
181             System.exit(1);
182         }
183
184         // Values to be read from parameters
185
String JavaDoc username = null;
186         String JavaDoc chatTopic = null;
187
188         // Check parameters
189
for (int i = 0; i < argv.length; i++) {
190             String JavaDoc arg = argv[i];
191
192             if (arg.equals("-u")) {
193                 if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
194                     System.err.println("error: missing user name");
195                     System.exit(1);
196                 }
197                 username = argv[++i];
198                 continue;
199             }
200
201             if (arg.equals("-t")) {
202                 if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
203                     System.err.println("error: missing topic name");
204                     System.exit(1);
205                 }
206                 chatTopic = argv[++i];
207                 continue;
208             }
209
210             if (arg.equals("-h")) {
211                 printUsage();
212                 System.exit(1);
213             }
214
215             // Invalid argument
216
System.err.println ("error: unexpected argument: "+arg);
217             printUsage();
218             System.exit(1);
219         }
220
221         // Check values read in.
222
if (username == null) {
223             System.err.println ("error: user name must be supplied");
224             printUsage();
225             System.exit(1);
226         }
227
228         if (chatTopic == null) {
229             System.err.println ("error: topic name must be supplied");
230             printUsage();
231             System.exit(1);
232         }
233
234         // Start the JMS client for the "chat".
235
Chat chat = new Chat();
236         chat.chatter(username, chatTopic);
237
238     }
239
240     /** Prints the usage. */
241     private static void printUsage() {
242
243         StringBuffer JavaDoc use = new StringBuffer JavaDoc();
244         use.append("usage: java Chat (options) ...\n\n");
245         use.append("options:\n");
246         use.append(" -u name Specify unique user name. (Required)\n");
247         use.append(" -t topic Specify a topic for chat.\n");
248         use.append(" -h This help screen.\n");
249         System.err.println(use);
250     }
251
252 }
253
254
Popular Tags