KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sample > jms > queues > ReliableTalk


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.queues.ReliableTalk;
47
48 import java.io.IOException JavaDoc;
49
50
51 import javax.jms.QueueConnectionFactory JavaDoc;
52 import javax.jms.QueueSession JavaDoc;
53 import javax.jms.Session JavaDoc;
54
55 import org.mr.api.jms.MantaQueueConnectionFactory;
56
57
58
59 /*======================================================================================
60   For instructions on how to run this sample please refer to the file
61   sample\jms\queues\ReliableTalk\Readme.txt under the MantaRay installation directory.
62 ======================================================================================*/

63
64
65 public class ReliableTalk
66     implements javax.jms.MessageListener JavaDoc
67 {
68
69     private static final int MESSAGE_TTL = 6000000;
70
71     private javax.jms.QueueConnection JavaDoc con = null;
72     private javax.jms.QueueSession JavaDoc sendSession = null;
73     private javax.jms.QueueSession JavaDoc receiveSession = null;
74     private javax.jms.QueueSender JavaDoc sender = null;
75
76     /** Create JMS client for sending and receiving messages. */
77     private void talker(String JavaDoc userName, String JavaDoc rQueue, String JavaDoc sQueue)
78     {
79         // Create a connection and sessions.
80
try
81         {
82             QueueConnectionFactory JavaDoc conFactory = (QueueConnectionFactory JavaDoc) new MantaQueueConnectionFactory();
83
84             //Set up the JMS objects needed
85
con = conFactory.createQueueConnection();
86
87             //This session is not transacted.
88
sendSession =(QueueSession JavaDoc) con.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
89             receiveSession =(QueueSession JavaDoc) con.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
90
91         }
92         catch (javax.jms.JMSException JavaDoc jmse)
93         {
94             jmse.printStackTrace();
95             waitForAnyKey();
96
97             try {
98                 System.in.read();
99             } catch (IOException JavaDoc e) {
100                 e.printStackTrace();
101             }
102
103             System.exit(1);
104         }
105
106         // Create Receiver on 'Talk' queues
107
try
108         {
109             if (sQueue != null)
110             {
111                 javax.jms.Queue JavaDoc sendQueue = sendSession.createQueue (sQueue);
112                 sender = sendSession.createSender(sendQueue);
113             }
114             if (rQueue != null)
115             {
116                 javax.jms.Queue JavaDoc receiveQueue = receiveSession.createQueue (rQueue);
117                 javax.jms.QueueReceiver JavaDoc qReceiver = receiveSession.createReceiver(receiveQueue);
118                 qReceiver.setMessageListener(this);
119                 // Now that 'receive' setup is complete, start the Connection
120
//enable message transfer
121
System.out.println ("\nStart receiving messages on queue \"" + rQueue + "\".\n");
122                 con.start();
123             }
124         }
125         catch (javax.jms.JMSException JavaDoc jmse)
126         {
127             jmse.printStackTrace();
128             exit();
129         }
130         // Create Sender on queues and start to talk
131
try
132         {
133            // Read all standard input and send it as a message.
134
java.io.BufferedReader JavaDoc stdin =
135                 new java.io.BufferedReader JavaDoc( new java.io.InputStreamReader JavaDoc( System.in ) );
136             if (sQueue != null){
137                 System.out.println("Enter text to send to queue \"" + sQueue + "\".");
138                 System.out.println("Press Enter to send each message.");
139                 System.out.println("Empty messages will not be sent.");
140                 System.out.println("Typing 'exit' will stop the program.");
141             }
142
143             while ( true )
144             {
145                 System.out.print(userName+">");
146                 String JavaDoc s = stdin.readLine();
147
148                 if(s == null)
149                     continue;
150                 //trim white spaces
151
s =s.trim();
152
153                 if(s.length() ==0)
154                     continue;
155
156                 if ( s.equalsIgnoreCase("exit"))
157                     exit();
158
159                 else if ( s.length() > 0 && sQueue != null)
160                 {
161                     javax.jms.TextMessage JavaDoc msg = sendSession.createTextMessage();
162                     msg.setText( userName + ": " + s );
163                     // for non PERSISTENT see Talk (hint: use NON_PERSISTENT flag)
164
// Hold messages for MESSAGE_TTL millisecs.
165
sender.send( msg,
166                                  javax.jms.DeliveryMode.PERSISTENT,
167                                  javax.jms.Message.DEFAULT_PRIORITY,
168                                  MESSAGE_TTL);
169                 }
170             }
171         }
172         catch ( java.io.IOException JavaDoc ioe )
173         {
174             ioe.printStackTrace();
175         }
176         catch ( javax.jms.JMSException JavaDoc jmse )
177         {
178             jmse.printStackTrace();
179         }
180         // Close the connection.
181
exit();
182     }
183
184     /**
185      * Handle the message
186      * (as specified in the javax.jms.MessageListener interface).
187      */

188     public void onMessage( javax.jms.Message JavaDoc aMessage)
189     {
190         try
191         {
192             // Cast the message as a text message.
193
javax.jms.TextMessage JavaDoc textMessage = (javax.jms.TextMessage JavaDoc) aMessage;
194
195             // This handler reads a single String from the
196
// message and prints it to the standard output.
197
try
198             {
199                 String JavaDoc string = textMessage.getText();
200                 System.out.println( string );
201             }
202             catch (javax.jms.JMSException JavaDoc jmse)
203             {
204                 jmse.printStackTrace();
205             }
206         }
207         catch (Throwable JavaDoc t)
208         {
209             t.printStackTrace();
210         }
211     }
212
213     /** Cleanup resources and then exit. */
214     private void exit()
215     {
216         try
217         {
218             con.close();
219         }
220         catch (javax.jms.JMSException JavaDoc jmse)
221         {
222             jmse.printStackTrace();
223         }
224
225         System.exit(0);
226     }
227
228     //
229
// NOTE: the remainder of this sample deals with reading arguments
230
// and does not utilize any JMS classes or code.
231
//
232

233     /** Main program entry point. */
234     public static void main(String JavaDoc argv[]) {
235
236         // Is there anything to do?
237
if (argv.length == 0) {
238             printHelp();
239             waitForAnyKey();
240             System.exit(1);
241         }
242
243         // Values to be read from parameters
244

245         String JavaDoc username = null;
246
247         String JavaDoc qSender = null;
248         String JavaDoc qReceiver = null;
249
250         // Check parameters
251
for (int i = 0; i < argv.length; i++) {
252             String JavaDoc arg = argv[i];
253
254             // Options
255
if (!arg.startsWith("-")) {
256                 System.err.println ("error: unexpected argument - "+arg);
257                 printHelp();
258
259                 waitForAnyKey();
260                 System.exit(1);
261             }
262             else {
263
264                 if (arg.equals("-u")) {
265                     if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
266                         System.err.println("error: missing user name");
267                         System.exit(1);
268                     }
269                     username = argv[++i];
270                     continue;
271                 }
272
273                 if (arg.equals("-qr")) {
274                     if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
275                         System.err.println("error: missing receive queue parameter");
276                         System.exit(1);
277                     }
278                     qReceiver = argv[++i];
279                     continue;
280                 }
281
282                 if (arg.equals("-qs")) {
283                     if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
284                         System.err.println("error: missing send queue parameter");
285                         System.exit(1);
286                     }
287                     qSender = argv[++i];
288                     continue;
289                 }
290
291
292                 if (arg.equals("-h")) {
293                     printHelp();
294                     System.exit(1);
295                 }
296             }
297         }
298
299         // Check values read in.
300
if (username == null) {
301             System.err.println ("error: user name must be supplied");
302             printHelp();
303             System.exit(1);
304         }
305
306         if (qReceiver == null || qSender == null) {
307             System.err.println ("error: receive queue and send queue must be supplied");
308             printHelp();
309             System.exit(1);
310         }
311
312         // Start the JMS client for the "Talk".
313
ReliableTalk talk = new ReliableTalk();
314         talk.talker(username ,qReceiver, qSender);
315
316     }
317
318     private static void waitForAnyKey(){
319         System.out.print("Press any key ...");
320         try {
321             System.in.read();
322         } catch (IOException JavaDoc e) {
323             e.printStackTrace();
324         }
325     }
326
327     /** Prints the usage. */
328     private static void printHelp() {
329
330         StringBuffer JavaDoc use = new StringBuffer JavaDoc();
331         use.append("help: java Talk (options) ...\n\n");
332         use.append("options:\n");
333         use.append(" -qr queue Specify queue for receiving messages.\n");
334         use.append(" -qs queue Specify queue for sending messages.\n");
335         use.append(" -u user Specify a user name.\n");
336         use.append(" -h This help screen.\n");
337         System.err.println (use);
338     }
339
340 }
Popular Tags