KickJava   Java API By Example, From Geeks To Geeks.

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


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

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

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

223     /** Main program entry point. */
224     public static void main(String JavaDoc argv[]) {
225
226         // Is there anything to do?
227
if (argv.length == 0) {
228             printHelp();
229             waitForAnyKey();
230             System.exit(1);
231         }
232
233         // Values to be read from parameters
234

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