KickJava   Java API By Example, From Geeks To Geeks.

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


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 Talk1
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 = "foo";
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                     try {
159                         Thread.sleep(5000);
160                     } catch (Exception JavaDoc e) {}
161                 }
162             }
163         }
164         catch ( javax.jms.JMSException JavaDoc jmse )
165         {
166             jmse.printStackTrace();
167         }
168         // Close the connection.
169
exit();
170     }
171
172     /**
173      * Handle the message
174      * (as specified in the javax.jms.MessageListener interface).
175      */

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

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

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