KickJava   Java API By Example, From Geeks To Geeks.

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


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

46 package sample.jms.topics.ReliableChat;
47 import java.io.InputStreamReader JavaDoc;
48
49 import javax.jms.Session JavaDoc;
50 import javax.jms.TopicConnectionFactory JavaDoc;
51
52 import org.mr.MantaAgent;
53 import org.mr.api.jms.MantaTopicConnectionFactory;
54
55
56 /*======================================================================================
57   For instructions on how to run this sample please refer to the file
58   sample\jms\topics\ReliableChat\Readme.txt under the MantaRay installation directory.
59 ======================================================================================*/

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

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

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