KickJava   Java API By Example, From Geeks To Geeks.

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


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.SelectorTalk;
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   For instructions on how to run this sample please refer to the file
60   sample\jms\queues\SelectorTalk\Readme.txt under the MantaRay installation directory.
61 ======================================================================================*/

62
63
64 public class SelectorTalk
65     implements javax.jms.MessageListener JavaDoc
66 {
67
68     private static final int MESSAGE_TTL = 6000000;
69     private static final String JavaDoc PROPERTY_NAME = "Ticket";
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, String JavaDoc selection)
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, PROPERTY_NAME + " = \'" + selection + "\'");
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                         "with a message selector set to: \"" +PROPERTY_NAME + " = \'" + selection + "\'\"\n");
123                 con.start();
124             }
125         }
126         catch (javax.jms.JMSException JavaDoc jmse)
127         {
128             jmse.printStackTrace();
129             exit();
130         }
131         // Create Sender on queues and start to talk
132
try
133         {
134            // Read all standard input and send it as a message.
135
java.io.BufferedReader JavaDoc stdin =
136                 new java.io.BufferedReader JavaDoc( new java.io.InputStreamReader JavaDoc( System.in ) );
137             if (sQueue != null){
138                 System.out.println("Enter text to send to queue \"" + sQueue + "\".");
139                 System.out.println("Press Enter to send each message.");
140                 System.out.println("Empty messages will not be sent.");
141                 System.out.println("Typing 'exit' will stop the program.");
142             }
143
144             while ( true )
145             {
146                 System.out.print(userName+">");
147                 String JavaDoc s = stdin.readLine();
148
149                 if(s == null)
150                     continue;
151                 //trim white spaces
152
s =s.trim();
153
154                 if(s.length() ==0)
155                     continue;
156
157                 if ( s.equalsIgnoreCase("exit"))
158                     exit();
159
160                 else if ( s.length() > 0 && sQueue != null)
161                 {
162                     javax.jms.TextMessage JavaDoc msg = sendSession.createTextMessage();
163                     // NOTE: here we set the property for each sent message.
164
msg.setStringProperty(PROPERTY_NAME, selection);
165                     msg.setText( userName + ": " + s );
166                     // for PERSISTENT see ReliableTalk (hint: use PERSISTENT flag)
167
// Hold messages for MESSAGE_TTL millisecs.
168
sender.send( msg,
169                                  javax.jms.DeliveryMode.NON_PERSISTENT,
170                                  javax.jms.Message.DEFAULT_PRIORITY,
171                                  MESSAGE_TTL);
172                 }
173             }
174         }
175         catch ( java.io.IOException JavaDoc ioe )
176         {
177             ioe.printStackTrace();
178         }
179         catch ( javax.jms.JMSException JavaDoc jmse )
180         {
181             jmse.printStackTrace();
182         }
183         // Close the connection.
184
exit();
185     }
186
187     /**
188      * Handle the message
189      * (as specified in the javax.jms.MessageListener interface).
190      */

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

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

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